Interactive Computer Science Tutoring

Learn programming concepts interactively

AHA Schools Logo

JavaScript Functions

Function Declarations vs. Expressions
In JavaScript, functions can be defined as declarations or expressions. A key difference between them is hoisting.
Function Declaration
Function declarations are hoisted to the top of their scope. This means you can call them before they are defined in the code.
JavaScript Code
Live JavaScript representation with highlighted changes
// Function Declaration
console.log(square(5)); // 25
function square(n) {
return n * n;
}
Function Expression
Function expressions are not hoisted. If you try to call them before they are defined, you'll get an error.
JavaScript Code
Live JavaScript representation with highlighted changes
// Function Expression
try {
console.log(square(5));
} catch (e) {
console.error(e.message);
}
const square = function(n) {
return n * n;
};
Visualization: Hoisting
How the JavaScript engine interprets the code.

Function declarations are moved to the top of their containing scope during the compilation phase. This is why you can call them before they appear in the code.

Declaration Hoisted
Live JavaScript representation with highlighted changes
// How JavaScript sees it (Hoisting)
function square(n) {
return n * n;
}
console.log(square(5));

Variables declared with `const` (and `let`) are also hoisted, but they are not initialized. They are in a "temporal dead zone" from the start of the block until the declaration is encountered. This is why you get a `ReferenceError` when trying to access a function expression before it's defined.