JavaScript Variables

1. What is a Variable?

Think of a variable as a labeled box where you can store information. In JavaScript, variables are containers for storing data values like numbers, strings, objects, etc.

To use a variable, you must first declare it using one of the keywords: var, let, or const.

2. Variable Declarations

A. The `var` Keyword

var was the original way to declare variables. It is function-scoped (or globally scoped if declared outside a function). It can be re-declared and updated.

var x = 10;
var x = 20; // Re-declaration allowed
x = 30;     // Update allowed
console.log("Value of x:", x);
        
Output will appear here...

B. The `let` Keyword

let was introduced in ES6 (2015). It is block-scoped (only exists within the {} it is declared in). It cannot be re-declared in the same scope, but it can be updated.

let y = 10;
// let y = 20; // Error: Identifier 'y' has already been declared
y = 20;     // Update allowed

if (true) {
    let y = 50; // This is a different 'y' inside this block
    console.log("Inside block:", y);
}
console.log("Outside block:", y);
        
Output will appear here...

C. The `const` Keyword

const is also block-scoped. However, variables declared with const cannot be reassigned. You must initialize it with a value when you declare it.

const country = "India";
// country = "USA"; // Error: Assignment to constant variable

console.log("Country:", country);

// Note: Objects declared with const can still be mutated
const person = { name: "Ragini" };
person.name = "Ravi"; // This is allowed!
console.log("Person Name:", person.name);
        
Output will appear here...

3. Scope Explained

Scope determines the visibility of variables.

4. Comparison Table

Feature var let const
Scope Function Scope Block Scope Block Scope
Re-declare ✅ Yes ❌ No ❌ No
Re-assign ✅ Yes ✅ Yes ❌ No
Hoisting Yes (initialized as undefined) Yes (but in Temporal Dead Zone) Yes (but in Temporal Dead Zone)

Practice Questions

Test your understanding of JavaScript Variables.

Easy

Q1: Store student name, roll number, and course. Print all details.

Easy

Q2: Store a product name, price, and quantity in variables. Store the total cost directly in a new variable.

Medium

Q3: Store an initial bank balance and a deposit amount in variables. Store the final balance directly in a third variable.

Medium

Q4: Store a person's name, age, and city in variables. Combine them to store a full sentence in one single variable.

Hard

Q5: Create a program to print a full report card using variables.

  • Store: Student Name, Roll Number, Class
  • Store: 5 Subject Names, 5 Subject Marks
  • Store: Total Marks & Percentage (calculate manually and assign directly)
  • Store: Final Result sentence in one variable

Answer

Code: