Function Basics
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure—a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it.
1. Function Declarations
A function declaration (also called a function statement) consists of the function keyword, followed by the name of the function, a list of parameters, and the JavaScript statements that define the function.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // "Hello, Alice!"
Note on Hoisting: Function declarations are hoisted to the top of their scope, meaning they can be called before they are defined in the code.
2. Function Expressions
A function expression is very similar to and has almost the same syntax as a function declaration. The main difference is that the function name can be omitted in function expressions to create anonymous functions.
const square = function(number) {
return number * number;
};
console.log(square(4)); // 16
Function expressions are not hoisted. You must define them before you can use them.
Named Function Expressions
You can also provide a name in a function expression. This name is local to the function body and can be useful for recursion or debugging.
const factorial = function fact(n) {
return n < 2 ? 1 : n * fact(n - 1);
};
3. Arrow Functions
Introduced in ES6, arrow functions provide a more concise syntax. They are particularly popular for inline callbacks and higher-order functions.
const multiply = (a, b) => a * b;
// With implicit return and single parameter
const double = n => n * 2;
Key Differences:
- Arrow functions do not have their own
thiscontext. They inheritthisfrom the enclosing lexical scope. - They do not have an
argumentsobject. - They cannot be used as constructors (no
newkeyword).
4. The arguments Object vs ...rest Parameters
Before ES6, the arguments object was used to access an indefinite number of arguments passed to a function.
function sumAll() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
However, arguments is an array-like object, not a real array. In modern JavaScript, rest parameters (...) are heavily preferred:
function sumAllModern(...numbers) {
return numbers.reduce((sum, num) => sum + num, 0);
}
5. IIFE (Immediately Invoked Function Expression)
An IIFE is a function that runs as soon as it is defined. It's an established design pattern for creating private scopes.
(function() {
const privateVar = "I cannot be accessed from outside";
console.log("IIFE executed!");
})();
In modern JavaScript (ES6+), module systems and block-scoping (let and const) have largely reduced the need for IIFEs, though they are still useful in certain scenarios like async initialization.