Understanding JavaScript Variables: let, const, and var Explained

Understanding JavaScript Variables: let, const, and var Explained

Unlike programming languages like Python or Ruby, that do not need variables to be declared explicitly, or other programming languages like Java, C, C++, C#, that use type declarators to declare variables, JavaScript uses a unique method to declare variables. This method of declaraing variables might be confusing to beginners but understanding it’s distinctions will help you choose the appropriate declaration based on your programming needs.

JavaScript uses the following keywords to declare variables, var, let and const.

var:

  • Function Scope: Variables declared with var are function-scoped, meaning they are only accessible within the function where they are defined.

  • Hoisting: Variables declared with var are hoisted to the top of their scope. This means you can use a variable before it's declared, but the value will be undefined.

let:

  • Block Scope: Variables declared with let are block-scoped, confined to the block or statement where they are defined (e.g., inside loops or if statements).

  • No Hoisting: Unlike var, variables declared with let are not hoisted to the top of their scope. They remain in the temporal dead zone until the actual declaration.

const:

  • Block Scope: Similar to let, variables declared with const are block-scoped.

  • Immutable: Once assigned, the value of a const variable cannot be changed. However, it's important to note that for objects and arrays declared with const, the reference cannot be changed, but their properties or elements can.

Examples:

Scope

Using var:

function exampleVar() {
  if (true) {
    var x = 10;
  }
  console.log(x); // Outputs 10 (function-scoped)
}

exampleVar();

Using let:

function exampleLet() {
  if (true) {
    let y = 20;
  }
  console.log(y); // Error: y is not defined (block-scoped)
}

exampleLet();

Hoisting

Using var:

console.log(a); // Outputs undefined
var a = 5;
console.log(a); // Outputs 5 (hoisted to the top of the function)

Using let:

console.log(b); // Error: Cannot access 'b' before initialization
let b = 10;
console.log(b);

Reassignment and Immutability

Using let for reassignment:

let count = 3;
count = count + 1;
console.log(count); // Outputs 4

Using const for immutability:

const pi = 3.14;
// pi = 3.14159; // Error: Assignment to a constant variable
console.log(pi); // Outputs 3.14

Using const with objects:

const person = { name: 'John', age: 30 };
// person = { name: 'Jane', age: 25 }; // Error: Assignment to a constant variable
person.age = 31; // Valid: Modifying the object's properties
console.log(person); // Outputs { name: 'John', age: 31 }

In summary, use var if you need function scope, let if you want block scope with reassignment, and const if you want block scope with immutability. The choice between them depends on your specific use case and the desired behavior for your variables.