Milind Daraniya

Understanding var, let, and const in JavaScript with Examples

Published September 28th, 2023 20 min read

JavaScript, as one of the most popular programming languages, offers different ways to declare variables: var, let, and const. Each of these declarations has its own scope and behavior. In this tutorial, we'll explore the differences between var, let, and const in JavaScript, along with practical examples.

1. var Declaration:

The var keyword was traditionally used to declare variables in JavaScript, but it has some limitations regarding scope and hoisting.

var name = "John";
console.log(name); // Output: John

// Hoisting example
console.log(age); // Output: undefined
var age = 30;

2. let Declaration:

The let keyword was introduced in ES6 (ECMAScript 2015) to address the shortcomings of var. It has block-level scope and doesn't hoist variables.

let city = "New York";
console.log(city); // Output: New York

// Block-level scope
if (true) {
    let localCity = "Los Angeles";
}
console.log(localCity); // Error: localCity is not defined

3. const Declaration:

The const keyword is used to declare constants, which cannot be reassigned after they are declared. Like let, it has block-level scope.

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

// Cannot reassign const variables
PI = 3.14; // Error: Assignment to constant variable

// Mutable object example
const person = {
    name: "Alice",
    age: 25,
};
person.age = 26; // No error, object properties can be modified

Key Takeaways:

  • Use var if you need variable hoisting or compatibility with older codebases.
  • Prefer let for variables that may be reassigned and have block-level scope.
  • Use const for constants that shouldn't be reassigned and for object properties that you don't intend to change.

Comparison Summary:

  • var has function-level scope, hoists variables, and can be redeclared.
  • let has block-level scope, doesn't hoist variables, and can be reassigned.
  • const has block-level scope, doesn't hoist variables, and can't be reassigned (though objects and arrays assigned to const can have their properties modified).

Final Thoughts:

In modern JavaScript development, it's recommended to use let and const over var due to their more predictable scoping rules and better handling of variable assignments. Choose the declaration that best suits your use case and coding style to write cleaner and more maintainable JavaScript code. Happy coding!