A variable in JavaScript is a container for storing data values.Variables allow you to store, update, and reuse data in your programs.

1. Declaring Variables in JavaScript

JavaScript provides three keywords to declare variables:

var
let
const

2. var – Function Scoped (Old Way)

var name = "John";
console.log(name);

Characteristics:

  • Function scoped
  • Can be redeclared
  • Can be reassigned
  • Hoisted (initialized as undefined)

Example:

var x = 10;
var x = 20; // allowed
x = 30;     // allowed

❌ Not recommended in modern JavaScript

3. let – Block Scoped (Modern)

let age = 25;
age = 26; // allowed

Characteristics:

  • Block scoped { }
  • Cannot be redeclared in the same scope
  • Can be reassigned
  • Hoisted but not initialized (Temporal Dead Zone)

Example:

if (true) {
let city = "Dhaka";
console.log(city);
}
// console.log(city); ❌ Error

4. const – Constant Variables

const country = "Bangladesh";

Characteristics:

  • Block scoped
  • Cannot be redeclared
  • Cannot be reassigned
  • Must be initialized at declaration

Example:

const PI = 3.1416;
// PI = 3.14 ❌ Error

5. const with Objects and Arrays

You can modify properties, but cannot reassign the variable.

const user = { name: "John", age: 25 };
user.age = 26; // allowed// user = {} ❌ Error

const fruits = ["Apple", "Banana"];
fruits.push("Mango"); // allowed

6. Variable Naming Rules

✅ Allowed:

let firstName;
let _count;
let $price;

❌ Not Allowed:

let 1name;   // cannot start with number
let full name; // no spaces
let let;     // reserved keyword

7. JavaScript is Case Sensitive

let value = 10;
let Value = 20;console.log(value); // 10
console.log(Value); // 20

8. Variable Hoisting

var Hoisting

console.log(x); // undefined
var x = 5;

let and const Hoisting (TDZ)

console.log(y); // ❌ ReferenceError
let y = 10;

9. Scope of Variables

Global Scope

let message = "Hello";

function greet() {
console.log(message);
}

Local (Function) Scope

function test() {
let x = 10;
console.log(x);
}
// x ❌ Error

Block Scope

if (true) {
let y = 20;
}
// y ❌ Error

Categorized in:

Javascript,