Functions in JavaScript
Functions are first‑class values. Define them with declarations, expressions, or arrow syntax.
Declarations and expressions
function add(a, b) { return a + b } // declaration (hoisted)
const mul = function (a, b) { return a * b } // expression
Arrow functions
Concise syntax; lexical this and arguments.
const inc = n => n + 1
const sum = (a, b) => { return a + b }
Avoid arrows when you need your own this (use function declarations/expressions).
Default and rest parameters
function power(x, exp = 2) { return x ** exp }
function log(event, ...args) { console.log(event, args) }
Destructuring and params
function greet({ name = 'anon' }) { return `Hi ${name}` }
Return values
No return means undefined. Functions can return objects/arrays/other functions.
this and binding
this is dynamic in classic functions; use call/apply/bind to control it.
function show() { console.log(this.id) }
const obj = { id: 1, show }
show.call({ id: 2 }) // 2
Arrows capture this from the defining scope.
Overloads and arguments
JS has no overloads; inspect params or use object options. The arguments object is array‑like for classic functions.
IIFE (module‑like scope)
(() => { const hidden = 1 })()
Summary
- Prefer declarations for named functions; arrows for concise callbacks
- Use default/rest parameters and destructuring for ergonomic APIs
- Understand
thissemantics; arrows are lexical