JavaScript Variables

🌐 JavaScript Variables




🟢 What is a Variable?

A variable is like a box where we can store information (data) and use it later in our program.

👉 Example in real life:
Think about a water bottle. You can fill it with water, drink it, and refill it again. Similarly, a variable can hold a value, and we can change or update that value later.


🟢 How to Declare a Variable in JavaScript?

We use keywords like var, let, and const to declare (create) variables.

1. var

Older way of creating variables.

var name = "Adib"; console.log(name); // Output: Adib

2. let

Modern and commonly used way to declare variables.

let age = 23; console.log(age); // Output: 23

3. const

Used when the value should not change.

const country = "Bangladesh"; console.log(country); // Output: Bangladesh

🟢 Variable Naming Rules

When naming a variable, remember these rules:

✔ Must start with a letter, _ (underscore), or $ (dollar sign).
✔ Cannot start with a number.
✔ No spaces are allowed.
✔ JavaScript is case-sensitive (Name and name are different).

✅ Examples:

let firstName = "John"; // valid let _score = 95; // valid let $price = 120; // valid

❌ Invalid examples:

let 1name = "Alex"; // ❌ cannot start with number let first name = "Tom"; // ❌ no spaces

🟢 Updating Variables

let city = "Dhaka"; console.log(city); // Dhaka city = "Chittagong"; console.log(city); // Chittagong

🟢 Why are Variables Important?

  • They help store information.

  • They make code reusable and flexible.

  • They make programs easy to understand.


💡 Quick Summary:

  • Use let for normal variables.

  • Use const for values that should not change.

  • Use var only if working with older code.

Comments