JavaScript Coding Day 4 | Var vs. Let: Understanding the Difference

Var vs. Let: Understanding the Difference

Watch the lesson tutorial  ðŸ”»

The primary differences between var and let revolve around scoping and redeclaration.


1. Variable Redeclaration (The Key Difference)

Featurevarlet
RedeclarationAllowedNOT Allowed

A. var: Redeclaration is Allowed

When you declare a variable with var, you can redeclare it later within the same scope without causing an error. The second declaration simply overwrites the first one.

Example 1: Redeclaration with var

HTML
<script>
   var a = 25; // First declaration and assignment
   var a = 35; // Second declaration and assignment (Redeclaration is allowed)

   console.log(a); // Logs the latest value: 35
</script>

Output: 35

B. let: Redeclaration is NOT Allowed

If you try to redeclare a variable using let within the same scope, JavaScript will throw a SyntaxError. This prevents accidental overwriting of variables, which helps write safer code.

Example 2: Redeclaration with let

HTML
<script>
var a = 25;
var a = 35; // Valid: 'a' declared with var

let b = 125;
let b = 500; // 🛑 Invalid: 'b' declared with let and redeclared in the same scope

console.log(b);
</script>

Output: SyntaxError: Identifier 'b' has already been declared


2. Variable Scoping (Global and Local)

The other major difference is how variables declared with var and let are scoped.

A. var Scope: Global or Function/Local Scope

  • Function/Local Scope: A var declared inside a function is only accessible within that function.

  • Global Scope: A var declared outside any function is globally scoped and accessible everywhere.

Crucially, var does NOT respect block scope (i.e., code blocks defined by {} like if statements or for loops).

B. let Scope: Global, Function, and Block Scope (The Modern Standard)

  • Block Scope: A let variable declared inside a code block ({}) is only accessible within that block. This is often referred to as Local Scope (or Block Scope).

  • Global/Function Scope: It also respects global and function scope, similar to var.

This block-scoping feature of let is the key improvement over var.

Practical Example: Block Scope and Function Scope

This example directly addresses your final prompt, demonstrating how let creates Block Scope and contrasting it with the standard Global/Function Scope.

HTML
<script>
// --- Global Scope ---
// 'a' is declared with var outside any function, making it globally accessible.
var a = 25; 
var a = 35; // Valid redeclaration

// 'b' is declared with let in the global scope.
let b = 65; 

console.log("Global a:", a); // Output: Global a: 35
console.log("Global b:", b); // Output: Global b: 65

// --- Function Scope and Block Scope ---
function x() {
    // This 'a' is a FUNCTION-SCOPED variable.
    // It's a new variable specific to this function's scope.
    var a = 50; 
    
    // This 'b' is a BLOCK-SCOPED variable.
    // Since 'b' is inside the function's block, it shadows the global 'b'.
    let b = 85; 

    // An inner block scope (like an 'if' or 'for' loop)
    if (true) {
        let b = 99; // A third 'b', scoped only to this 'if' block.
        console.log("If Block b:", b); // Output: If Block b: 99
    }
    
    console.log("Function a:", a); // Output: Function a: 50
    console.log("Function b:", b); // Output: Function b: 85 (The function-scoped one)
}

x(); // Call the function

// Back to Global Scope
console.log("Global a (after function call):", a); // Output: Global a (after function call): 35 (Global 'a' was not changed by 'function x')
console.log("Global b (after function call):", b); // Output: Global b (after function call): 65 (Global 'b' was not changed by 'function x')

</script>

Output Summary:

Global a: 35
Global b: 65
If Block b: 99
Function a: 50
Function b: 85
Global a (after function call): 35
Global b (after function call): 65

Scope Explanation

Global Scope

Variables declared outside any function or block (using var or let) are in the Global Scope. They can be accessed and modified from anywhere in the code. In the example, the initial var a = 35 and let b = 65 are in the global scope.

Local Scope (Block Scope)

When you declare a variable with let inside a pair of curly braces {} (a block), that variable is block-scoped or locally scoped.

  • In the function x(), the line let b = 85; creates a new variable b that exists only within that function's block.

  • It shadows (temporarily hides) the global b of 65.

  • Once the function x() finishes executing, that local b (85) is destroyed, and the global b (65) remains unchanged.

This behavior is why modern JavaScript development strongly favors using let and const over var to prevent unintended variable collisions and make the code easier to reason about.


- by Chirana Nimnaka

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