ResourcesJavascriptGuides

Declaration vs assignment

Introduction

In this article we will explore difference between declaration and assignment and their implications on scope, closures, and hoisting, and provide resources to related topics for deeper understanding.


Declaration

Declaration is the process of creating a variable, function, or object.

let x;
 
const y = 10;
 
var z;
 
function greet() {
  return "Hello, world!";
}

Important: Declarations create the identifiers in memory, making them available for use in the code.

Assignment

Assignment is the process of assigning a value to a declared variable.

let x;
x = 5; // Assignment
 
let greet = function() { // Assignment + declaration
  return "Hello, world!";
};
 
let obj = {}; // Assignment + declaration
obj.name = "Alice";
 
const name = "Pawel" // Assignment + declaration

Important: Assignments give declared identifiers their values.

Hoisting

Hoisting is Javascript's default behavior of moving declarations to the top of their containing scope during the compilation phase.

Only declarations are hoisted, not assignments. This means that a variable can be referenced before its declaration but will return undefined until the assignment is reached.

Explore the topic: Hoisting in Javascript

Scope

Scope determines the accessibility of variables and functions in different parts of your code.

When you declare a variable within a scope, it is only accessible within that scope. Assigning a value to the declared variable within the same scope does not change its accessibility.

Explore the topic: Scope in Javascript

Closures

A closure is a function that retains access to its outer scope even after the outer function has finished executing.

In closures, the declaration of variables in the outer function allows the inner function to access them. The assignment of values to these variables is retained even after the outer function completes execution.

Explore the topic: Closures in Javascript

Resources

MDN Web docs

On this page