JavaScript Variables and Constant.

JavaScript variables are fundamental to programming, acting as containers for storing data values. Historically, var was the only way to declare variables. However, with the introduction of ECMAScript 2015 (ES6), let and const were introduced to address shortcomings of var, particularly concerning scoping and mutability. Understanding the differences between these three keywords is crucial for writing modern, maintainable, and error-free JavaScript code.

Before we start understanding JavaScript variables and constants, let us first understand one important term that we are going to use again and again in our further discussion.

What is Hoisting?

Hoisting is a fundamental JavaScript mechanism where variable and function declarations are conceptually moved to the top of their containing scope during the compilation phase, before code execution.

This means that regardless of where variables and functions are declared, they are processed first. However, the exact behavior of hoisting differs significantly between var, let/const, and functions.

JavaScript Variables and Constant

The Legacy Keyword: var

The var keyword is the oldest way to declare a variable in JavaScript.

Scope of var.

Variables declared with var are function-scoped or globally-scoped. This means a var declared inside a function is only available within that function. If declared outside any function, it is global. Crucially, var ignores block scope (blocks defined by curly braces {}, such as in if statements or for loops).

JavaScript Example Code:

function exampleVarScope() {
  if (true) {
    var x = 10;
  }
  console.log(x); // Output: 10 (var ignores block scope)
}
// console.log(x); // Throws ReferenceError: x is not defined (x is function-scoped)

Hoisting of var

Variables declared with var are hoisted to the top of their scope (function or global). However, only the declaration is hoisted, not the initialization. This leads to a behavior where you can use a var before it is declared in the code, but its value will be undefined.

JavaScript Example of var Hoisting.

console.log(a); // Output: undefined
var a = 5;
console.log(a); // Output: 5

The Modern Standard: let

The let keyword was introduced in ES6 to provide better variable declaration management, primarily by introducing block scoping.

Scope of let

Variables declared with let are block-scoped. A block is any section of code enclosed in curly braces {} (e.g., if blocks, for loops, or just a standalone block). The variable is only accessible within that block and any nested sub-blocks.

JavaScript Example Code:
function exampleLetScope() {
  if (true) {
    let y = 20;
    console.log(y); // Output: 20
  }
  // console.log(y); // Throws ReferenceError: y is not defined (y is block-scoped)
}

Hoisting of let

let is also hoisted, but unlike var, it is not initialized. If you try to access a let variable before its declaration, JavaScript throws a ReferenceError. The time between the start of the scope and the declaration is called the Temporal Dead Zone (TDZ).

Example of let and TDZ:
// console.log(b); // ReferenceError: Cannot access 'b' before initialization (TDZ in effect)
let b = 15;
console.log(b); // Output: 15

Variables declared with let can be reassigned a new value.
let count = 1;
count = 2; // Allowed
console.log(count); // Output: 2

The Constant Keyword: const

The const keyword, also introduced in ES6, is used for declaring constant variables whose value is intended to remain unchanged.

Scope and Hoisting of const

Like let, const is block-scoped and is also subject to the Temporal Dead Zone (TDZ). This means attempting to use a const before its declaration results in a ReferenceError. Variables declared with const must be initialized at the time of declaration and cannot be reassigned later.

JavaScript Example Code:
const PI = 3.14159;
// PI = 3.14; // Throws TypeError: Assignment to constant variable.

Important Note on Objects/Arrays: While a const variable itself cannot be reassigned to a different value, if the value is an object or array, the contents of that object or array can be mutated.
const user = { name: "Alice" };
user.name = "Bob"; // Allowed: Object property modification
console.log(user.name); // Output: Bob

const numbers = [1, 2];
numbers.push(3); // Allowed: Array mutation
// numbers = [4, 5]; // NOT Allowed: Reassignment of the const variable

Modern Best Practice: In modern JavaScript, it's generally recommended to:
  • Use const by default for any variable that won't be reassigned. This prevents accidental changes and makes the code's intent clearer.
  • Use let for variables that need to be reassigned (e.g., loop counters, variables holding a state that changes).
  • Avoid using var completely due to its confusing scope and hoisting behavior.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS