Declarations vs Expressions

Understanding the difference between declarations and expressions is fundamental in JavaScript. Both are ways to define functions or variables, but they behave differently.

Illustration of declarations_vs_expressions
Illustration of declarations_vs_expressions

💡 What is a Declaration?

A declaration explicitly defines a function or variable and is hoisted, meaning it is available anywhere in its scope before its actual place in the code.

💡 What is an Expression?

An expression produces a value and can be assigned to a variable. Function expressions are not hoisted and only available after the assignment.

Function Declaration vs Function Expression
FeatureDeclarationExpression
Syntaxfunction foo() {}const foo = function() {}
HoistingHoisted (usable before declaration)Not hoisted (usable after assignment)
Named/AnonymousAlways namedCan be anonymous or named
Use caseStandard function definitionAssign functions dynamically or inline
Variable Declaration vs Expression
FeatureDeclarationExpression
Examplelet x;let x = 5 + 3;
PurposeCreates a variableComputes a value to assign
ExecutionVariable is declaredExpression is evaluated to produce a value

📌 Deep Dive: Function Declaration vs Expression Hoisting

JAVASCRIPT
// Function Declaration (hoisted)
sayHello();

function sayHello() {
  console.log("Hello from declaration!");
}

// Function Expression (not hoisted)
try {
  sayHi();
} catch (e) {
  console.log(e.message); // sayHi is not a function
}

const sayHi = function() {
  console.log("Hello from expression!");
};

sayHi();
Output
Hello from declaration!
sayHi is not a function
Hello from expression!

⚠️ Important

Function declarations are hoisted completely, but function expressions behave like normal variables and are not initialized until assigned.

💡 Summary

  • Declarations define functions or variables upfront and are hoisted.
  • Expressions produce values and are evaluated when the code runs.
  • Use declarations when you want hoisting and clear function definitions.
  • Use expressions for more flexible or conditional function assignments.