J

JavaScript Tutorial

Clean • Professional

JS Variables

2 minute

JavaScript Variables

In JavaScript, variables are like containers that store information — such as numbers, text, or any kind of data.

They let your program store, use, and update values dynamically.

Example:

let name = "Ajay";
const age = 25;
var city = "Lucknow";

Types of Variables in JavaScript

Variables are declared using three keywordsvar, let, and const.

Each behaves differently in terms of scope, redeclaration, and reassignment.

learn code with durgesh images

1. var

  • Introduced in early versions of JavaScript.
  • Function-scoped or globally scoped.
  • Can be redeclared and reassigned.
  • Is hoisted, meaning it’s moved to the top of its scope during execution.
  • Can cause unexpected bugs due to its loose scoping behavior.

Example:

var x = 10;
var x = 20; // Redeclaration allowed
x = 30; // Reassignment allowed
console.log(x); // 30

2. let

  • Introduced in ES6 (2015).
  • Block-scoped (only accessible within { } where it’s declared).
  • Can be reassigned, but not redeclared in the same scope.
  • Not hoisted in a usable way (accessing before declaration causes an error).

Example:

let y = 15;
y = 25; // Reassignment allowed
// let y = 35;  Error: Cannot redeclare 'y'
console.log(y); // 25

3. const

  • Also introduced in ES6.
  • Block-scoped, just like let.
  • Must be initialized immediately.
  • Cannot be reassigned or redeclared.
  • Note: If the variable holds an object or array, the reference is fixed, but the contents can still change.

Example:

const z = 100;
// z = 200;  Error: Assignment to constant variable

const obj = { a: 1 };
obj.a = 2; // Allowed — property change, not reassignment
console.log(obj.a); // 2

Comparison of var, let, and const

Featurevarletconst
ScopeFunction or global scopeBlock scopeBlock scope
ReassignmentAllowedAllowedNot allowed
RedeclarationAllowed in same scopeNot allowed in same scopeNot allowed in same scope
InitializationOptional (defaults to undefined)OptionalRequired at declaration
HoistingHoisted, initialized as undefinedHoisted, not initialized (TDZ)Hoisted, not initialized (TDZ)
Use CaseLegacy code, loose scopingReassignable variables, loopsConstants, immutable references


Article 0 of 0