Skip to content

Latest commit

 

History

History
61 lines (38 loc) · 1.65 KB

File metadata and controls

61 lines (38 loc) · 1.65 KB

02 Variables

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; // undefined

Note: 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"; // Jagan

02.1 var

var 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); // Bangalore

Note: var is generally discouraged in modern JavaScript due to scoping and hoisting issues.

02.2 let

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); // 26

02.3 const

const 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); // India

Note: const does not make objects or arrays immutable — only the reference is constant.