When learning JavaScript, one of the very first things you need to understand is variables. A variable is simply a way to store information in your program so you can use it later. Think of it like a box with a label: you can put something inside the box, give it a name, and then open it again whenever you need it.
🟢 What is a Variable?
A variable is a container for data. It can hold a number, some text, or even more complex data like a list.
Example:
let age = 25;
let city = "Calgary";
Here,
ageis a variable holding the number25.cityis a variable holding the text"Calgary".
🟡 Declaring Variables in JavaScript
In modern JavaScript, you usually use let or const to create variables:
let score = 10; // can be updated later
const pi = 3.14159; // cannot be changed once set
- Use
letwhen the value might change. - Use
constwhen the value should stay the same.
⚠️ There’s also var, but it’s older and has quirks. Beginners should stick with let and const.
🔢 Common Data Types for Variables
Variables can hold different types of data. Some of the most common are:
- Number →
let price = 99; - String (text) →
let name = "Alice"; - Boolean (true/false) →
let isOnline = true; - Undefined → a variable with no value yet
- Null → an empty or “nothing” value
Example:
let temperature = -5; // Number
let greeting = "Hello"; // String
let isHappy = false; // Boolean
let nextStep; // Undefined
let emptyBox = null; // Null
✍️ Changing Variable Values
If you use let, you can change the value later:
let score = 0;
score = 5;
console.log(score); // 5
But if you used const, this won’t work:
const pi = 3.14;
pi = 3.14159; // ❌ Error! You cannot reassign a const
🖥️ Where to Run This Code
The easiest way is in your browser:
- Open Chrome (or another browser).
- Right-click anywhere → Inspect → Console tab.
- Type in the examples above and press Enter.
You’ll see the results immediately!
✨ Key Takeaways
- Variables store data so you can reuse it.
- Use
letfor values that change,constfor values that don’t. - Variables can hold numbers, text, true/false values, and more.
- Practice in your browser console to build confidence.
💡 Bonus: ECMAScript and TypeScript
- JavaScript follows a standard called ECMAScript (often shortened to ES5, ES6, ES2020, etc.). Each version adds new features. For example,
letandconstcame from ES6. - TypeScript is like a superset of JavaScript, created by Microsoft. It adds types (e.g., saying a variable must always be a number). This makes big projects easier to manage.
- Don’t worry if this sounds new — for now, just focus on plain JavaScript. Once you’re comfortable, learning TypeScript will be much easier.