What is a Variable in JavaScript?


1. What is a Variable in JavaScript?

A variable is like a container where you store data (like numbers, text, etc.) so that you can use it later in your program.

Example:


let name = "Robin"; // storing text in a variable let age = 25; // storing number in a variable console.log(name); // prints: Robin console.log(age); // prints: 25

Think of it like a box:

  • You put something inside it (data)
  • You give the box a name (variable name)
  • Later, you can open the box (use the variable)


2. var, let, and const

In JavaScript, you can declare variables using three keywords: var, let, and const. Each has its own rules.


A. var

  • Oldest way to create a variable.
  • Can change value anytime.
  • Has function scope (more about this later).

Example:

var city = "Lucknow";
console.log(city); // Lucknow

city = "Ayodhya";  // changing value
console.log(city); // Ayodhya

⚠️ Important: var is less safe because it can be accidentally overwritten.


B. let

  • Modern way to create a variable.
  • Can change value anytime.
  • Block scoped (safer than var).

Example:

let score = 10;
console.log(score); // 10

score = 20;         // changing value
console.log(score); // 20

✅ Use let when the value can change later.


C. const

  • Constant: cannot change value once set.
  • Also block scoped.

Example:

const pi = 3.14;
console.log(pi); // 3.14

// pi = 3.14159; // ❌ Error! You cannot change a const

✅ Use const when the value should never change (like pi, API keys, etc.).


3. Scope (Simple Beginner Understanding)

  • Block scope: { ... } – variable exists only inside { }
  • Function scope: variable exists inside the function

Example:

{
  let a = 5;
  var b = 10;
  const c = 15;
}

console.log(a); // ❌ Error: a is not defined (let is block scoped)
console.log(b); // 10 (var is function scoped, so it's accessible outside)
console.log(c); // ❌ Error: c is not defined (const is block scoped)

4. Summary Table

KeywordCan Change?ScopeExample Use
varYesFunction ScopeOlder code, rarely now
letYesBlock ScopeMost variables
constNoBlock ScopeConstants, fixed value

5. Quick Tips for Beginners

  • Always use let or const, not var.
  • Use const first. If you need to change it later, switch to let.
  • Give variables meaningful names:
let userName = "Robin"; // Good
let a = "Robin";        // Bad



Post a Comment

2 Comments