Function Declarations vs. Function Expressions
On this page
The core difference is that function declarations are evaluated at compile time and fully hoisted, allowing them to be called before they appear in the code, whereas function expressions are created when the execution flow reaches them and cannot be invoked beforehand.
#Function Declaration
function greet() {
console.log("Hello!");
}This is a function declaration (also called a "function statement"). It has the keyword function, followed directly by a name, and it stands on its own as a statement — it's not assigned to a variable.
"Evaluated at compile time and fully hoisted"
Before your JavaScript code actually starts running line-by-line, the JavaScript engine does a quick pass over the code (this is often called the "creation phase" or informally "compile time"). During this pass, it looks for function declarations and fully processes them — meaning it stores the entire function (name and body) in memory, ready to use.
This is what "hoisting" means: it's as if the function declaration gets physically lifted to the top of its scope, even though you wrote it further down.
#"Allowing them to be called before they appear in the code"
Because the whole function is set up in advance, this works perfectly fine:
sayHi(); // ✅ Works! Logs "Hi there!"function sayHi() {
console.log("Hi there!");
}Even though sayHi() is called before its definition appears in the source code, it works — because by the time any code executes, sayHi has already been fully defined behind the scenes.
#Function Expression
const greet = function() {
console.log("Hello!");
};This is a function expression. Here, an (often anonymous) function is created as a value and assigned to a variable (greet). It's treated like any other expression — similar to assigning a number or string to a variable.
#"Created when the execution flow reaches them"
Unlike declarations, function expressions are not hoisted with their full function body. Only the variable (greet, declared with const, let, or var) is set up in advance — but the function itself isn't attached to that variable until the code actually executes that line, in normal top-to-bottom order.
#"Cannot be invoked beforehand"
This means:
sayHi(); // ❌ Error!const sayHi = function() {
console.log("Hi there!");
};This throws an error. Why? It depends on how you declared the variable:
With
constorlet: You get aReferenceError: Cannot access 'sayHi' before initialization. The variable exists in memory (hoisted) but is in a "temporal dead zone" — inaccessible until the actual assignment line runs.With
var: You get aTypeError: sayHi is not a function. The variablesayHiis hoisted and initialized toundefined, so calling it before assignment is like callingundefined().
Either way — it fails, because the function value simply doesn't exist yet at that point in execution.