Declarations vs Expressions
Overview
A function is a block of code designed to perform a particular task. There are two primary ways to define them in classic JavaScript: Function Declarations and Function Expressions.
The most critical difference between the two is Hoisting. Function Declarations are fully hoisted by the JS engine, meaning you can call them before they appear in the code. Function Expressions are stored in variables (like const), meaning they are trapped in the Temporal Dead Zone and cannot be invoked before initialization.
Syntax
// This works perfectly fine!
greet("Kartik");
function greet(name) {
console.log("Hello, " + name);
}// sayHi(); // ReferenceError! Cannot access before initialization
const sayHi = function(name) {
console.log("Hi, " + name);
};
// Must be called AFTER the definition
sayHi("Aman");Common Pitfalls
- Assuming function expressions are hoisted. Beginners often define all their functions at the bottom of a file using
const myFunc = function(){}, and then get crashing ReferenceErrors when trying to call them at the top of the file.
Interview Questions
Declarations are fully hoisted, allowing them to be invoked before they are defined in the file. Expressions are assigned to variables, meaning they follow the hoisting rules of var/let/const and cannot be used before they are assigned.
Real-World Example
Function expressions are often used as 'anonymous functions' (functions without a name) passed directly as arguments to methods like .map() or .forEach().
arr.map(function(item) {
return item * 2;
});Check Your Knowledge
Test your understanding of Declarations vs Expressions with these quick questions.