Variables and data types
A variable is a named box that stores a value so you can use it later. Programs use variables to remember things: a user's name, the score in a game, the items in a cart.
Creating variables: let and const
letcreates a variable whose value can change.constcreates a variable that cannot be reassigned.
Try adding playerName = 'Rahul'; at the end and run it. You'll get an error, because const protects the value.
Rule of thumb: use
constby default. Switch toletonly when you need to reassign. You may seevarin older code. It behaves differently, so avoid it in new code.
Naming rules
- Names can contain letters, digits,
_and$, but can't start with a digit. - They are case-sensitive:
ageandAgeare different. - Use camelCase for multi-word names:
totalPrice,isLoggedIn.
Data types
Every value has a type. You can check it with typeof.
| Type | Example | Used for |
|---|---|---|
number |
42, -7, 3.14 |
Counting and maths |
string |
'hi', "hi", `hi` |
Text |
boolean |
true, false |
Yes/no decisions |
undefined |
undefined |
"No value assigned yet" |
null |
null |
"Intentionally empty" |
object |
{ name: 'Asha' }, [1, 2] |
Groups of values |
Strings and template literals
Backticks (`) let you put variables directly inside text with ${...}. These are called template literals.
Converting between types
Practice
Create variables for a product: name, price and inStock (a boolean). Then print a sentence like Laptop costs $899 — in stock: true using a template literal.
1.Which keyword should you use for a value that never gets reassigned?
2.What is '5' + 3?