Classic JS Tutorial | JS in VS 2026 | JS Examples | jQuery
⚡ Lesson 06 of 30

Functions

Declare, invoke, and compose functions — including arrow functions, default parameters, and rest arguments.

Function Declaration

A named function declaration is hoisted — you can call it before it appears in the file:

greet("Alice"); // works due to hoisting

function greet(name) {
  console.log("Hello, " + name + "!");
}

Function Expression

Assign a function to a variable. Not hoisted — must be defined before use:

const square = function(x) {
  return x * x;
};
console.log(square(5)); // 25

Arrow Functions

Arrow functions provide a concise syntax and do not have their own this binding:

const double = x => x * 2;
console.log(double(7)); // 14

const add = (a, b) => a + b;
console.log(add(3, 4)); // 7

// Multi-line arrow function
const clamp = (val, min, max) => {
  if (val < min) return min;
  if (val > max) return max;
  return val;
};

Default Parameters

Provide fallback values for parameters that aren't passed by the caller:

function createUser(name, role = "viewer") {
  return { name, role };
}

console.log(createUser("Bob"));           // { name:"Bob", role:"viewer" }
console.log(createUser("Alice","admin")); // { name:"Alice", role:"admin" }

Rest Parameters & Spread

...rest collects extra arguments into an array; ...spread expands an array into arguments:

function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4)); // 10

const nums = [1, 2, 3];
console.log(Math.max(...nums)); // 3
← Lesson 05🏠 HomeLesson 07 →