let, var, and const in Javascript
Arifuzzaman Tanin
Software Engineer | C# | .NET | React | Blazor | JavaScript | Full Stack | Azure | DevOps | Agile | Microservices | gRPC
In JavaScript, variables are fundamental for storing and manipulating data. Traditionally, developers used var to declare variables. However, with the introduction of ES6 (ECMAScript 2015), two new variable declaration keywords emerged: let and const. Each of these keywords serves a distinct purpose and offers different behavior in terms of scope, reassignment, and immutability. Let's delve into each of them to understand their usage and implications in JavaScript programming.
var
var is the oldest way of declaring variables in JavaScript. It has a function-level scope, meaning variables declared with var are either globally scoped or function-scoped.
function example() {
var x = 10;
if (true) {
var y = 20;
console.log(x); // Output: 10
}
console.log(y); // Output: 20
}
In the example above, both x and y are accessible within the example() function, illustrating var's function-level scope.
However, one of the major drawbacks of var is its lack of block-level scoping. Variables declared with var can be accessed outside of their block scope.
function example() {
if (true) {
var z = 30;
}
console.log(z); // Output: 30
}
let
let was introduced in ES6 to address the shortcomings of var regarding block scoping. Variables declared with let are block-scoped, which means they exist only within the block they are defined in, including loops, conditional statements, and functions.
function example() {
let x = 10;
if (true) {
let y = 20;
console.log(x); // Output: 10
console.log(y); // Output: 20
}
console.log(y); // ReferenceError: y is not defined
}
In the example above, x is accessible both inside and outside the if block, while y is only accessible within the if block due to its block-level scope.
const
const also came with ES6 and is used to declare constants. Once a value is assigned to a variable using const, it cannot be reassigned.
const PI = 3.14;
PI = 3.14159; // TypeError: Assignment to constant variable.
Constants declared with const must be assigned a value during declaration, and attempting to reassign them will result in a TypeError.
const person = {
name: 'John',
age: 30
};
person.age = 31; // Valid
person = {}; // TypeError: Assignment to constant variable.
However, it's important to note that when using const with objects and arrays, the properties or elements of the object/array can still be modified. The immutability only applies to the variable reference itself, not its contents.