Back to Tutorials
Beginner

Functions Fundamentals

6 min read | Functions

Functions Fundamentals

Functions are reusable blocks of code in JavaScript.

Function Declaration

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

greet('World'); // "Hello, World!"

Function Expression

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

Arrow Functions (ES6)

// Full syntax
const add = (a, b) => {
  return a + b;
};

// Implicit return const add = (a, b) => a + b;

// Single parameter (no parentheses needed) const double = n => n * 2;

Default Parameters

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

greet(); // "Hello, World!" greet('Alice'); // "Hello, Alice!"

Rest Parameters

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

sum(1, 2, 3, 4); // 10

Higher-Order Functions

// Function that takes a function
function repeat(n, action) {
  for (let i = 0; i < n; i++) {
    action(i);
  }
}

repeat(3, console.log); // 0, 1, 2

// Function that returns a function function multiplier(factor) { return n => n * factor; }

const double = multiplier(2); double(5); // 10