Var, Let and Const in JavaScript

Var, Let and Const in JavaScript

After reading this article, you will have a clear understanding of how, when, and where you should use each type of variable declaration.

·

2 min read

JavaScript is a dynamic programming language that allows you to declare variables using three different keywords: "var", "let", and "const". Each of these keywords has its own unique behavior and use cases. Understanding the differences between them is crucial for writing clean, efficient, and bug-free code.

  1. Var : The Legacy Variable

Scope: var is function-scoped, meaning it’s accessible within the function it’s declared in or globally if declared outside any function.

Example:

function example() {

var message = "Hello, World!";

console.log(message); // "Hello, World!"

}

console.log(message); // ReferenceError

Hoisting: var variables are hoisted to the top of their scope but only the declaration, not the assignment.

console.log(msg); // undefined

var msg = "Hi!";

Re-declaration: You can re-declare var variables, which can lead to unintended bugs.

var name = "Shizuka";

var name = "Nobita"; // No error

  1. Let: The Modern Replacement

Scope: let is block-scoped, meaning it’s confined to the nearest {} block.

if (true) {

let greeting = "Hello!";

console.log(greeting); // "Hello!"

}

console.log(greeting); // ReferenceError

Hoisting: let is hoisted, but not initialized, creating a "temporal dead zone" where accessing it before declaration results in a ReferenceError.

console.log(count); // ReferenceError

let count = 10;

Re-declaration: let does not allow re-declaration in the same scope, preventing accidental overwrites.

let age = 25;

let age = 30; // SyntaxError

  1. Const: The Immutable Choice

    Scope: const, like let, is block-scoped.

    {

    const PI = 3.14;

    console.log(PI); // 3.14

    }

    console.log(PI); // ReferenceError

Immutability:
const prevents reassignment of the variable itself, but if the variable is an object or array, its contents can still be modified.

const person = { name: "Shizuka" };

person.name = "Nobita"; // This is allowed

// person = { name: "Jiyan" }; // TypeError

Best Practices

  • Use const by default for variables that shouldn’t change.

  • Use let when you need to reassign a variable.

  • Avoid var due to its quirks, which can introduce bugs.

Conclusion

Understanding var, let, and const is key to writing modern JavaScript. While var has its place in older code, let and const provide safer and more predictable behavior, making them the preferred choices for variable declarations in modern JavaScript development.