~/hackweb.dev
JavaScript Functions Basics
Quiz
...

JavaScript Functions Basics

beginner · updated Tue Sep 08 2026Contribute

Master function declarations, expressions, and parameters.

JavaScript Functions Basics

Functions are reusable blocks of code that perform specific tasks. They are the building blocks of JavaScript programs.

Function Declarations

function add(a, b) {
  return a + b;
}

let result = add(5, 3);  // 8

Declarations are hoisted — they can be called before they appear in the code.

Function Expressions

Functions can be assigned to variables:

let multiply = function(a, b) {
  return a * b;
};

let result = multiply(4, 5);  // 20

Default Parameters

Provide default values if no argument is passed:

function greet(name, greeting = "Hello") {
  return `${greeting}, ${name}!`;
}

greet("John");        // "Hello, John!"
greet("John", "Hi");  // "Hi, John!"

Return Values

function getFullName(first, last) {
  return `${first} ${last}`;
}

let name = getFullName("John", "Doe");  // "John Doe"

Remember: A function without return returns undefined.

Arrow Functions

Shorter syntax for function expressions:

// Traditional
let add = function(a, b) { return a + b; };

// Arrow
let add = (a, b) => a + b;

Single expression functions get an implicit return.

Complete Example: Calculator

function calculate(num1, num2, operator) {
  switch (operator) {
    case "add": return num1 + num2;
    case "subtract": return num1 - num2;
    case "multiply": return num1 * num2;
    case "divide": return num1 / num2;
    default: return NaN;
  }
}

calculate(10, 5, "add");       // 15
calculate(10, 5, "multiply");  // 50

Complete Example: Data Processor

function processData(data, transform) {
  return data.map(transform);
}

let numbers = [1, 2, 3, 4, 5];
let doubled = processData(numbers, (n) => n * 2);
// [2, 4, 6, 8, 10]

let names = ["alice", "bob", "charlie"];
let capitalized = processData(names, (n) => n.charAt(0).toUpperCase() + n.slice(1));
// ["Alice", "Bob", "Charlie"]

Best Practices

  1. Keep functions small — One responsibility per function
  2. Use descriptive namescalculateTotal() not calc()
  3. Use default parameters — For optional values
  4. Return early — Reduce nesting with early returns
  5. Avoid side effects — Pure functions are easier to test

Common Mistakes

  1. Forgetting return — Functions return undefined by default
  2. Using var in functions — Use let or const
  3. Confusing parameters and arguments — Parameters in definition, arguments in call
  4. Using arrow functions for methods — They don’t have their own this
  5. Deep nesting — Break complex logic into smaller functions