JavaScript Coding Day 3 | JavaScript Variables: var, let, and const

JavaScript Coding Day 3 | JavaScript Variables: var, let, and const

Watch the lesson tutorial  ðŸ”»

That's a great topic for a JavaScript article! Understanding the differences between var, let, and const is fundamental.

Here is an explanation of each keyword with practical, commented code examples, focusing on hoisting for var and block scoping for let and const.


1. var (Variable)

The var keyword was the original way to declare variables in JavaScript. It is primarily characterized by function-scoping and hoisting.

  • Scope: var variables are scoped to the nearest function or declared globally. They ignore block scopes (like if statements or for loops).

  • Hoisting: Declarations using var are hoisted (lifted) to the top of their scope (function or global) before execution. While the declaration is hoisted, the assignment (initialization) is not. If you try to access a var before its assignment, it will return undefined, not an error.

  • Re-declaration: A var variable can be re-declared in the same scope without an error.

Practical var Examples

➡️ Example 1: Function vs. Block Scoping

This shows how var variables declared inside an if block leak out into the function scope.

JavaScript
function checkVarScope() {
  if (true) {
    var car = 'Honda'; // Function-scoped, not block-scoped
    console.log(car); // Output: Honda
  }
  // 'car' is still accessible outside the 'if' block
  console.log(car); // Output: Honda
}

checkVarScope(); 
// console.log(car); // This would cause a 'ReferenceError' outside the function

Output (from inside checkVarScope):

Honda
Honda

➡️ Example 2: Hoisting and Re-declaration

This demonstrates hoisting—how the declaration is moved up, but the assignment remains—and re-declaration.

JavaScript
// Accessing 'a' here returns undefined because the declaration is hoisted
console.log(a); 

// The code is interpreted by JavaScript as:
// var a; 
// console.log(a); // Output: undefined

var a = 10;
a = 25; // Re-assignment is fine
console.log(a); // Output: 25

// Re-declaration is also fine (but often leads to confusion)
var a = 50;
console.log(a); // Output: 50

Output:

undefined
25
50

2. let and const (Block Scoping)

Both let and const were introduced in ECMAScript 2015 (ES6) to address the shortcomings of var, primarily by implementing block scoping and fixing the confusing nature of var's hoisting.

  • Scope: Both are block-scoped. A block is any code within curly braces ({ ... }), such as in if statements, for loops, or standalone blocks.

  • Hoisting (Temporal Dead Zone): While they are technically hoisted, they are not initialized. Attempting to access them before the actual declaration line results in a ReferenceError. This period is called the Temporal Dead Zone (TDZ), which prevents the unpredictable behavior of getting undefined with var.

  • Re-declaration: Neither let nor const can be re-declared in the same scope.

Comparison Table

Featurevarletconst
ScopeFunction/GlobalBlockBlock
Re-assignmentYesYesNo (Must be assigned on declaration)
HoistingInitialized to undefinedUninitialized (TDZ)Uninitialized (TDZ)
Re-declarationYesNoNo

3. const (Constant)

The const keyword is used to declare variables whose value is intended to remain constant.

  • Must be Initialized: You must assign a value immediately upon declaration.

  • Immutable Binding: The binding (the association between the variable name and its value) is immutable. You cannot re-assign the variable to a different value.

Note on Objects: For complex data types (Objects and Arrays), const only ensures that the binding to the object reference cannot change. The contents (properties/elements) of the object or array can still be modified.

Practical const Examples

➡️ Example 1: Block Scoping and Immutability

This shows block scope and the primary rule: no re-assignment.

JavaScript
const PI = 3.14159; 
console.log(PI); // Output: 3.14159

// PI = 3.14; // Uncaught TypeError: Assignment to constant variable. (Error)

if (true) {
  const PI = 3.14; // A new, separate variable in this block scope is allowed
  console.log(PI); // Output: 3.14
}

console.log(PI); // Output: 3.14159 (Original value is unchanged)

Output:

3.14159
3.14
3.14159

➡️ Example 2: Modifying const Object Properties

This demonstrates that const only prevents re-assignment, not modification of object properties.

JavaScript
const user = { name: "Alice", age: 30 };

// Modifying a property is allowed
user.age = 31;
console.log(user); // Output: { name: 'Alice', age: 31 }

// Re-assigning the variable 'user' to a different object is NOT allowed
// user = { name: "Bob", age: 25 }; // Uncaught TypeError: Assignment to constant variable. (Error) 

Output:

{ name: 'Alice', age: 31 }

4. let (Let)

The let keyword is the preferred way to declare variables that you know will need to be re-assigned later.

  • Mutable: Unlike const, let variables can be re-assigned a new value.

  • Block Scoped: Like const, they are scoped to the nearest block ({ ... }).

Practical let Examples

➡️ Example 1: Re-assignment and Block Scoping

This shows how let can be updated and its block scope behavior.

JavaScript
let count = 1;
console.log("Outside before block:", count); // Output: 1

if (true) {
  let count = 5; // A new 'count' variable, only exists in this block
  console.log("Inside block:", count); // Output: 5
}

// The outer 'count' remains unchanged
count = 10; // Re-assignment of the outer variable is allowed
console.log("Outside after block:", count); // Output: 10

Output:

Outside before block: 1
Inside block: 5
Outside after block: 10

➡️ Example 2: let in a Loop (Solving var's Classic Problem)

let creates a new variable binding for each iteration of a loop, which is critical for asynchronous operations like setTimeout.

JavaScript
// Using let
for (let i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(`With let, i is: ${i}`);
  }, 100);
}

// Using var (for comparison, showing the old problem)
for (var j = 0; j < 3; j++) {
  setTimeout(function() {
    // When the function runs, 'j' has already reached the final value (3)
    console.log(`With var, j is: ${j}`);
  }, 100);
}

Output (will appear after 100ms):

With let, i is: 0
With let, i is: 1
With let, i is: 2
With var, j is: 3
With var, j is: 3
With var, j is: 3

🔑 Key Takeaway

In modern JavaScript development (ES6+), the general rule of thumb is:

  1. Use const by default for variables that won't be re-assigned (the vast majority).

  2. Use let only when you explicitly need to re-assign a variable (e.g., in loops or counters).

  3. Avoid var completely to prevent issues with hoisting and function scoping.


Comments

Popular posts from this blog

Python Coding Day 1 | The print() Function and Comments

What is Python?

Set Up an Environment to Code in Python