<htmlstart/>

JS Functions

Functions let you group reusable code into named blocks.

Declaring a Function

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

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

Parameters and Return

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

add(2, 3);   // 5
add(10, 20); // 30

// Default parameter values
function greet(name = "World") {
  return `Hello, ${name}!`;
}
greet();         // "Hello, World!"
greet("Alice");  // "Hello, Alice!"

Arrow Functions

// Traditional
function square(x) { return x * x; }

// Arrow function
const square = (x) => x * x;

// Single parameter — parens optional
const double = x => x * 2;

// Multi-line — needs braces + return
const add = (a, b) => {
  const sum = a + b;
  return sum;
};

Function Expressions

// Stored in a variable
const multiply = function(a, b) {
  return a * b;
};

// Immediately Invoked Function Expression (IIFE)
(function() {
  console.log("Runs immediately!");
})();

Higher-Order Functions

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

repeat(3, i => console.log("Step", i));
// Step 0
// Step 1
// Step 2
Arrow functions don't have their own this — they inherit it from the surrounding scope. Use them for callbacks and short expressions. Use regular functions when you need this (class methods, event handlers on DOM elements).
🧩

Test Yourself

4 questions
Q1.What does a function return when no return statement is used?
Q2.How do you write an arrow function that returns x * 2 in one line?
Q3.What is the key difference between arrow functions and regular functions?
Q4.What is a default parameter value used for?