Secure & Private (Zero Data Retention)
Free Access • No Sign-Up
Functions
Functions bundle reusable chunks of code that can accept inputs (parameters) and produce outputs (return values).
Try It Yourself
📋 Copy JavaScript Function Styles & Rest Parameters Snippet
// Standard Function vs Arrow Function
// Regular Function: has own 'this', 'arguments', hoisted
function calculateTotal(taxRate, ...items) {
return items.reduce((sum, item) => sum + item * (1 + taxRate), 0);
}
// Arrow Function: inherits lexical 'this', cannot be constructor
const multiply = (a, b = 1) => a * b;
⚠️ 5 Fatal Traps & JavaScript Pitfalls
Trap #1: Lexical this in Arrow Functions Used as Methods
Arrow functions do NOT bind their own this; they inherit this from the enclosing lexical scope. Defining an object method with an arrow function leaves this bound to window or undefined.
Trap #2: Invoking Arrow Functions with new Keyword
Arrow functions lack a [[Construct]] internal method and prototype property. Calling new MyArrow() throws an immediate TypeError: ... is not a constructor.
Trap #3: Function Declaration vs Expression Hoisting Mismatch
Function declarations (function f() {}) are fully hoisted with their body. Function expressions (const f = () => {}) are hoisted as uninitialized variables in the TDZ.
The legacy arguments object is array-like but is not an Array; calling arguments.map() throws a TypeError. Always use rest parameters: (...args) => {}.
Trap #5: Default Parameters Evaluated at Call-Time
Default parameters evaluate dynamically on each invocation. function get(id = randomId()) calls the function every time the argument is omitted.
💬 Frequently Asked Questions
What is the primary difference between arrow functions and regular functions?
Arrow functions have lexical this (they do not bind their own this, arguments, super, or new.target) and cannot be used as constructors.
What is a closure in JavaScript?
A closure is the combination of a function bundled together with references to its surrounding lexical environment, allowing inner functions to access outer variables even after the outer function has closed.
What do rest parameters (...args) do?
Rest parameters capture indefinite remaining arguments into a genuine JavaScript Array, enabling full array method access (map, filter, reduce).
What is the difference between call(), apply(), and bind()?
call(thisArg, ...args) invokes immediately with comma-separated arguments. apply(thisArg, [args]) invokes immediately with an array of arguments. bind(thisArg) returns a new function with bound this.
Can a function return multiple values in JavaScript?
Not directly, but functions can return an array or object containing multiple values, which callers unpack using destructuring.