Variables are containers used for storing data values. Modern JavaScript (ES6+) primarily uses let and const. The var keyword is older and generally discouraged due to scoping issues.
Declaring Variables
A variable declaration creates a named memory space that can store a value. You can declare a variable and optionally assign a value to it at the same time.
let name; // undefinedNote: Variables are case-sensitive, and most developers prefer camelCase for naming variables.
Assigning Variables
You can assign a value to a variable using the assignment operator =.
let name = "Jagan"; // Jaganvar is the oldest way to declare variables in JavaScript. It has function scope and can be re-declared and reassigned, which may lead to unexpected behavior.
var city = "Chennai";
var city = "Bangalore"; // allowed
console.log(city); // BangaloreNote:
varis generally discouraged in modern JavaScript due to scoping and hoisting issues.
let was introduced in ES6 and is block-scoped. It allows reassignment but does not allow redeclaration in the same scope.
let age = 25;
age = 26; // allowed
console.log(age); // 26const is also block-scoped and is used to declare variables whose values should not be reassigned. A value must be assigned at the time of declaration.
const country = "India";
/*
country = "Singapore"; // Not allowed
*/
console.log(country); // IndiaNote:
constdoes not make objects or arrays immutable — only the reference is constant.