Let’s dive into Variables in JavaScript step by step.


πŸ“¦ Variables in JavaScript

A variable is a container for storing data (values).
πŸ‘‰ Think of it as a labeled box where you can keep information.


1️⃣ Declaring Variables

In JavaScript, you can declare variables using var, let, and const.

πŸ”Ή var (Old way)

  • Function-scoped (not block-scoped).
  • Can be redeclared and updated.
  • Not recommended in modern JS.
var name = "Raj";
var name = "Kumar"; // Redeclaration allowed
console.log(name);  // Kumar

πŸ”Ή let (Modern way)

  • Block-scoped (exists only inside { }).
  • Can be updated, but not redeclared in the same scope.
let age = 20;
age = 21;       // βœ… allowed
// let age = 22; // ❌ Error: cannot redeclare
console.log(age); 

πŸ”Ή const (Constant)

  • Block-scoped.
  • Cannot be redeclared or reassigned.
  • Must be assigned at the time of declaration.
const PI = 3.14;
// PI = 3.15; ❌ Error (cannot reassign)
console.log(PI);

2️⃣ Rules for Naming Variables (Identifiers)

βœ… Allowed:

  • Letters, digits, _, $
  • Must start with a letter, _, or $ (not a number)
  • Case-sensitive (myVar β‰  myvar)

❌ Not allowed:

let 1name = "Raj";   // ❌ Invalid
let my-name = "Raj"; // ❌ Invalid
let myName = "Raj";  // βœ… Valid (camelCase recommended)

3️⃣ Types of Values Variables Can Hold

JavaScript variables can store different data types:

let str = "Hello";      // string
let num = 42;           // number
let isActive = true;    // boolean
let x;                  // undefined
let y = null;           // null
let arr = [1, 2, 3];    // array (object)
let obj = {name: "Raj"}; // object

4️⃣ Variable Scope

  • Global Scope β†’ Accessible everywhere.
  • Local/Function Scope β†’ Accessible only inside the function.
  • Block Scope (let & const) β†’ Accessible only inside { }.
{
  let a = 10;
  var b = 20;
}
console.log(b); // βœ… Works (var is function-scoped)
// console.log(a); ❌ Error (let is block-scoped)

5️⃣ Hoisting (Important)

  • var is hoisted (moved to the top) but initialized as undefined.
  • let and const are also hoisted but in a β€œtemporal dead zone” (not accessible before declaration).
console.log(x); // undefined (hoisted)
var x = 5;

console.log(y); // ❌ Error (cannot access before initialization)
let y = 10;

βœ… Summary

  • var β†’ old, function-scoped, can redeclare.
  • let β†’ modern, block-scoped, can update but not redeclare.
  • const β†’ modern, block-scoped, cannot redeclare or reassign.
  • Variables can store any type (string, number, object, etc.).
  • Variable names are case-sensitive and must follow rules.

Perfect πŸ‘ Here’s a clear comparison table of var, let, and const in JavaScript:


πŸ“Š Difference Between var, let, and const

Featurevarletconst
ScopeFunction-scopedBlock-scoped ({ })Block-scoped ({ })
Redeclarationβœ… Allowed❌ Not allowed❌ Not allowed
Reassignmentβœ… Allowedβœ… Allowed❌ Not allowed
Default Initializationundefined❌ Not initialized (TDZ error)❌ Not initialized (TDZ error)
Hoistingβœ… Hoisted (initialized as undefined)βœ… Hoisted (but in Temporal Dead Zone)βœ… Hoisted (but in Temporal Dead Zone)
Use in LoopsNot safe (because no block scope)SafeSafe
Best Use CaseLegacy code, older browsersGeneral-purpose variables that may changeConstants that should never change

πŸ”Ή Examples

var

var x = 10;
var x = 20;  // βœ… Redeclaration allowed
console.log(x); // 20

let

let y = 30;
// let y = 40; // ❌ Error: redeclaration not allowed
y = 40;       // βœ… Reassignment allowed
console.log(y); // 40

const

const PI = 3.14;
// PI = 3.1415; // ❌ Error: cannot reassign
console.log(PI); // 3.14

βœ… In modern JavaScript:

  • Use let for variables that can change.
  • Use const for constants or values that shouldn’t change.
  • Avoid var (only for legacy/old code).

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *