Functions
Declare functions, arrow syntax, scope, and higher-order patterns
Overview
Functions are first-class values in JavaScript—you can pass them as arguments, return them, and assign them to variables. Choose function declarations for hoisting, arrow functions for concise callbacks and lexical this.
Syntax / Usage
// Declaration (hoisted)
function add(a, b) {
return a + b
}
// Expression
const multiply = function (a, b) {
return a * b
}
// Arrow function
const square = (x) => x * x
const sum = (a, b) => {
const total = a + b
return total
}
// Default parameters
function greet(name = 'Guest') {
return `Hello, ${name}`
}
// Rest parameters
function logAll(...args) {
console.log(args)
}
Examples
Higher-order function for reusable filtering:
function filterBy(items, predicate) {
return items.filter(predicate)
}
const adults = filterBy(users, (u) => u.age >= 18)
Immediately invoked function for a private scope:
const counter = (() => {
let count = 0
return () => ++count
})()
counter() // 1
counter() // 2
Common Mistakes
- Arrow functions as object methods when you need dynamic
this - Forgetting that
returnon its own line after{inserts a semicolon (ASI) - Relying on hoisting with
const/letfunction expressions - Creating functions inside loops without
let—classic closure bug withvar
See Also
closures promises async-await destructuring