Functions and scope
Parameters, defaults, arrow functions, closures and this — the ideas behind almost every JavaScript interview question.
Ways to write one
function add(a, b = 0) {
return a + b;
}
// arrow function: concise, and does not rebind `this`
const mult = (a, b) => a * b;
const double = n => n * 2; // one param, no parens needed
const makeObj = id => ({ id }); // wrap object literal in parens
// rest parameters collect the remainder
function sum(...nums) {
return nums.reduce((t, n) => t + n, 0);
}💡
Arrow functions inherit
this from where they were defined. That makes them ideal for callbacks, and wrong for object methods that need their own this.Scope and closures
let and const are block-scoped; var is function-scoped. A closure is simply a function that keeps access to variables from the scope where it was created, even after that scope has returned.
function makeCounter() {
let n = 0; // private to each counter
return () => ++n;
}
const next = makeCounter();
next(); // 1
next(); // 2⚠️
Creating closures inside a loop with
var captures one shared variable — the classic 'all values are the last value' bug. Use let, which creates a fresh binding per iteration.Understanding this
| Called as | this is |
|---|---|
obj.method() | the object before the dot |
plain fn() | undefined in strict mode |
new Fn() | the new instance |
| arrow function | inherited from enclosing scope |
fn.call/apply/bind | whatever you pass |
const obj = {
n: 1,
inc() { this.n += 1; } // method shorthand: this === obj
};
const inc = obj.inc;
inc(); // TypeError - lost its receiver
const safe = obj.inc.bind(obj); // permanently attached
safe();FAQ
Arrow or regular function?
Arrow for callbacks and short expressions. Regular methods on objects and constructors, because you need your own
this.What is hoisting?
Function declarations are available throughout their scope before the line they appear on;
let/const are not initialized until their declaration executes (the temporal dead zone).Related
JavaScript basics Arrays and iteration
Last refreshed 2026-09-17.