Variables declaration in JavaScript¶
var, let and const¶
In JavaScript, you can declare variables using var, let, and const. Here’s a brief explanation of each:
- var: This is the oldest way to declare variables. It is function-scoped, which means a variable declared with
varis available within the function it’s declared in. If it’s not declared inside any function, it’s globally scoped. One peculiar behavior ofvaris hoisting, where variable and function declarations are moved to the top of their containing scope.
var x = 5; // Declare a variable
- let: Introduced in ES6 (ECMAScript 2015),
letallows you to declare block-scoped local variables. The variable is limited in scope to the block, statement, or expression in which it is declared. This is more intuitive and less error-prone thanvar.
let y = 10; // Declare a variable
- const: Also introduced in ES6,
constis used to declare variables whose values are never intended to change. It’s block-scoped likelet. The value of a constant cannot change through reassignment, and a constant cannot be redeclared.
const z = 15; // Declare a constant
Remember, while const means that the identifier can’t be reassigned, it doesn’t mean that the value it holds is immutable. If you assign an object or an array to a const variable, the contents of the object or array can still be modified.
Multiple inline assignments¶
let a = 1, b = "hello", c = true; // Declaring and assigning different types
let x, y, z; // Declaring multiple variables without initial assignment
// Destructuring assignment (arrays)
let [first, second, third] = [10, 20, 30];
// Destructuring assignment (objects)
const { name, age } = { name: "Alice", age: 25 };
//You can also use var or const instead of let.
var d = 4, e = 5;
const f = 6, g = 7;