In JavaScript, functions are first-class objects, meaning they can be assigned to variables, passed as arguments, and returned from other functions. There are several types of functions, including function declarations, function expressions, arrow functions, immediately invoked function expressions (IIFEs), generator functions, and async functions. This article explains each type, how they differ, and when to use them.
Function Declarations
A function declaration is the classic way to define a function. It starts with the function keyword, followed by a name, a parameter list, and a body. Function declarations are hoisted, meaning they are available throughout the enclosing scope even if defined later in the code.
function greet(name) {
return 'Hello, ' + name;
}
console.log(greet('Alice')); // "Hello, Alice"
Because of hoisting, you can call a function declaration before its definition in the same scope. This makes them useful for organizing code where the order of definitions doesn’t matter.
Function Expressions
A function expression assigns a function to a variable. Unlike declarations, function expressions are not hoisted; they are created when the line is executed. They can be anonymous (no name) or named (useful for recursion or debugging).
const square = function(x) {
return x * x;
};
console.log(square(5)); // 25
Function expressions are commonly used as callbacks or when you need to conditionally define a function. For example, you might assign different implementations based on a runtime condition.
Arrow Functions
Arrow functions, introduced in ES6, provide a concise syntax and do not have their own this binding. Instead, they inherit this from the surrounding lexical scope. This makes them ideal for callbacks and methods that need to preserve the context of the enclosing object.
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
Arrow functions also have implicit return when the body is a single expression, and they cannot be used as constructors. They are not hoisted and must be defined before use. Use them for short, simple functions, but avoid when you need dynamic this or a arguments object (arrow functions don’t have their own arguments).
Immediately Invoked Function Expressions (IIFEs)
An IIFE is a function expression that is executed immediately after it is defined. It is wrapped in parentheses to make it an expression, then followed by () to invoke it. IIFEs create a new scope, which is useful for avoiding global variable pollution.
(function() {
const secret = 'hidden';
console.log(secret); // "hidden"
})();
console.log(typeof secret); // "undefined"
IIFEs are often used in module patterns or to initialize code that should run once. With modern ES modules, IIFEs are less common, but they still appear in legacy code and some libraries.
Generator Functions
Generator functions are defined with function* and can be paused and resumed. They return a generator object that can be iterated over. The yield keyword pauses execution and returns a value, and the next call to next() resumes from that point.
function* idGenerator() {
let id = 1;
while (true) {
yield id++;
}
}
const gen = idGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
Generators are useful for lazy evaluation, handling infinite sequences, or simplifying asynchronous code with libraries like co (though async/await has largely replaced this). They are also used in state machines and custom iterators.
Async Functions
Async functions, defined with the async keyword, always return a Promise. They can contain await expressions, which pause execution until a Promise resolves. This makes asynchronous code look synchronous and easier to read.
async function fetchData(url) {
const response = await fetch(url);
return response.json();
}
Async functions are the modern standard for handling promises. They work with any thenable, and errors can be caught with try/catch. Note that await can only be used inside async functions (except in modules with top-level await).
Choosing the Right Function Type
The choice depends on the context and requirements:
- Function declarations for hoisted, named functions that are used throughout a scope.
- Function expressions for callbacks or when you need to assign a function to a property or pass it as an argument.
- Arrow functions for concise, lexical
thisbinding, especially in callbacks or array methods. - IIFEs for creating a private scope or running code immediately (though modules are preferred now).
- Generators for lazy sequences or custom iteration.
- Async functions for any function that deals with promises or asynchronous operations.
In practice, most modern code uses arrow functions for callbacks and async/await for asynchronous logic. Function declarations are still common for top-level functions.
Common Misconceptions and Pitfalls
One common mistake is assuming arrow functions are just syntactic sugar for function expressions. They differ in key ways: no this binding, no arguments object, and cannot be used as constructors. Another pitfall is relying on hoisting in blocks; function declarations inside if blocks behave inconsistently in strict mode.
Also, async functions always return a Promise, so if you forget to await a call, you’ll get a Promise instead of the value. Generators are not for general-purpose functions; using them where a simple loop would do adds unnecessary complexity.
Frequently Asked Questions
What is the difference between a function declaration and a function expression?
A function declaration is hoisted and can be called before its definition, while a function expression is not hoisted and is only available after the line executes. Function expressions can be anonymous, whereas declarations require a name.
When should I use an arrow function instead of a regular function?
Use arrow functions when you need a short, concise function and want to preserve the lexical this (e.g., in callbacks within a class method). Avoid them when you need dynamic this, a arguments object, or when you want to use the function as a constructor.
Can I use await in a non-async function?
No, await is only valid inside an async function (or at the top level of a module). If you try to use it in a regular function, you’ll get a syntax error.
What is an IIFE and why would I use one?
An IIFE is a function that runs immediately after definition. It creates a new scope, which helps avoid polluting the global namespace. Before modules, IIFEs were used to encapsulate code and expose only specific parts via the return value.
How do generators differ from regular functions?
Generators can pause execution with yield and resume later, allowing them to produce a sequence of values over time. Regular functions run to completion and return a single value. Generators are iterable and are useful for lazy evaluation.
Are arrow functions supported in all browsers?
Arrow functions are supported in all modern browsers, but not in older ones like Internet Explorer. If you need to support legacy browsers, you may need to transpile with Babel or use regular functions.
Related
- Solar Installation with Battery Calculator: How to Size
- Traffic Signs Manual Chapter 5: All You Need
- Bosch PS41 Impact Driver: Specs, Power, and Real-World Use
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- COUNTIF with Criteria: How It Works in ExcelThe quick answer: use =COUNTIF(range, criteria) to count cells that meet one condition, and =COUNTIFS(criteria_range1, criteria1, ...) for…
- Excel Scenario Manager Tutorial: Compare What-If PlansTo use Excel Scenario Manager, build a worksheet model, then select Data > What-If Analysis > Scenario Manager…
- How to Filter in Excel to Find the Exact Data You NeedTo filter in Excel, click a cell in your data, then choose Data > Filter; use the arrow…
- Excel Filter Shortcut: Ctrl+Shift+L and How to Use ItIn Excel for Microsoft 365 on Windows, press Ctrl+Shift+L to turn AutoFilter on or off for a selected…
- Excel SORT and INDEX: How to Sort Data and Return ValuesTo sort a range in Excel for Microsoft 365, use =SORT(A2:C6,3,-1) to sort its rows by the third…
- Rank in Excel by Multiple Criteria: Formulas and TipsWith primary scores in B2:B5, secondary scores in C2:C5, and a third tie-breaker in D2:D5, enter this in…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.