JavaScript Functions

JavaScript functions are reusable blocks of code. You define a function once, give it a name and inputs (parameters), and call it whenever you need it. Functions are also values: you can store them in variables and pass them to other functions.

Declaring and Calling a Function

return sends a value back to the caller and ends the function. A function without return gives undefined.

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

console.log(greet("Sana"));
console.log(greet("Hamza"));
Hello, Sana!
Hello, Hamza!

Default and Rest Parameters

Default values are used when an argument is missing. A rest parameter (...name) collects any number of extra arguments into an array.

function price(amount, taxRate = 0.17) {
  return amount * (1 + taxRate);
}
console.log(price(100));
console.log(price(100, 0.05));

function sum(...nums) {
  return nums.reduce((t, n) => t + n, 0);
}
console.log(sum(1, 2, 3, 4));
117
105
10

Arrow Functions

Arrow functions are a shorter syntax. If the body is a single expression, the braces and return can be dropped. Arrow functions do not have their own this, which makes them ideal for callbacks.

const square = (x) => x * x;
const add = (a, b) => a + b;
const log = () => console.log("no params");

console.log(square(6), add(2, 3));
log();
console.log([1, 2, 3].map((n) => n * 10).join(", "));
36 5
no params
10, 20, 30

Function Declarations vs Expressions

Function declarations are hoisted, so you can call them before the line where they appear. Function expressions (including arrow functions assigned to const) only exist after their line runs.

console.log(double(4)); // works: declaration is hoisted

function double(n) {
  return n * 2;
}

const triple = function (n) {
  return n * 3;
};
console.log(triple(4));
8
12

Scope and Closures

Variables declared inside a function are local to it. An inner function can access variables of the outer function even after the outer one has returned. This is called a closure, and it is how you create private state.

function makeCounter() {
  let count = 0;
  return () => ++count;
}
const next = makeCounter();
console.log(next(), next(), next());
1 2 3

Frequently asked questions

When should I use an arrow function?

Arrow functions are great for short callbacks and functions that should use the surrounding this. Use regular functions for object methods that need their own this, and for constructors.

What does a function return if there is no return statement?

It returns undefined.

What is a closure in JavaScript?

A closure is a function that remembers variables from the scope where it was created, even after that scope has finished running.