Declarations
Varjus supports variable declarations using let
and const
. Unlike some other languages, it does not support chaining declarations with the comma operator.
Using let
let
declares a mutable variable, meaning its value can be reassigned.
let x = 10;
x = 20; // Allowed
console.log(x); // 20
Using const
const
declares an immutable variable, meaning its value cannot be reassigned after initialization.
const y = 30;
y = 40; // Error: Cannot reassign a constant variable
const
and Objects
While const
prevents reassignment of the variable itself, it does not make objects immutable. You can modify the properties of a const
object.
const obj = { key: "value" };
obj.key = "new value"; // Allowed
console.log(obj.key); // "new value"
obj = {}; // Error: Cannot reassign a constant variable
const
and Arrays
Similarly, arrays declared with const
cannot be reassigned, but their elements can be modified.
const arr = [1, 2, 3];
arr[0] = 10; // Allowed
console.log(arr); // [10, 2, 3]
arr = [4, 5, 6]; // Error: Cannot reassign a constant variable
Scope
Both let
and const
are block-scoped, meaning they only exist within the block {}
in which they are declared.
{
let a = 5;
console.log(a); // 5
}
console.log(a); // Error: a is not defined