All books/JavaScript Fundamentals

Functions

Learn how to write reusable code with functions.

3 min read

Functions are reusable blocks of code that perform specific tasks. They're fundamental to writing clean, organized JavaScript.

Function Declaration

The traditional way to define a function:

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

console.log(greet("Alice")); // "Hello, Alice!"

Function Expression

Storing a function in a variable:

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

console.log(greet("Bob")); // "Hello, Bob!"

Arrow Functions

Modern, concise syntax (ES6+):

// Basic arrow function
const greet = (name) => {
  return `Hello, ${name}!`;
};

// Shorter: implicit return
const greet = (name) => `Hello, ${name}!`;

// Even shorter for single parameter
const greet = name => `Hello, ${name}!`;

Parameters and Arguments

Functions can accept multiple parameters:

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

console.log(add(5, 3)); // 8

Default Parameters

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

console.log(greet());        // "Hello, World!"
console.log(greet("Alice")); // "Hello, Alice!"

Rest Parameters

Collect multiple arguments into an array:

function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}

console.log(sum(1, 2, 3, 4)); // 10

Return Values

Functions can return values:

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

const result = multiply(4, 5);
console.log(result); // 20

Functions without a return statement return undefined:

function logMessage(message) {
  console.log(message);
  // No return statement
}

const result = logMessage("Hi"); // Logs "Hi"
console.log(result); // undefined

Scope

Variables declared inside a function are local:

function myFunction() {
  const localVar = "I'm local";
  console.log(localVar); // ✓ Works
}

myFunction();
console.log(localVar); // ✗ Error! Not defined

Callbacks

Functions can be passed as arguments to other functions:

function doSomething(callback) {
  console.log("Doing something...");
  callback();
}

doSomething(() => {
  console.log("Done!");
});
// "Doing something..."
// "Done!"

Practical Examples

Calculator Functions

const calculator = {
  add: (a, b) => a + b,
  subtract: (a, b) => a - b,
  multiply: (a, b) => a * b,
  divide: (a, b) => b !== 0 ? a / b : "Cannot divide by zero"
};

console.log(calculator.add(10, 5));      // 15
console.log(calculator.divide(10, 2));   // 5
console.log(calculator.divide(10, 0));   // "Cannot divide by zero"

Array Processing

const numbers = [1, 2, 3, 4, 5];

// Using arrow functions with array methods
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);

console.log(doubled); // [2, 4, 6, 8, 10]
console.log(evens);   // [2, 4]
console.log(sum);     // 15

Summary

  • Functions help organize code into reusable pieces
  • Arrow functions provide concise syntax
  • Parameters can have default values
  • Functions create their own scope
  • Callbacks enable powerful patterns

In the next chapter, we'll explore objects and arrays in detail.