Variables
A variable is a named box that stores a value. Create one with let if the value may change, or const if it should stay the same.
Programs need to remember things: the score in a game, the items in a cart, the user's name. A variable gives a value a name, so you can use it again and change it later. Think of it as a labelled box on a shelf.
The choice between let and const is about protection. With const, JavaScript stops you from accidentally replacing the value. A good habit: use const by default, and switch to let only when you really need to change the value - like a counter or a running total.
Example
let score = 0; // can change later
const shopName = "Terixto"; // cannot be reassigned
score = score + 10;Names are case-sensitive: price and Price are different. Use clear names such as totalPrice, written in "camelCase".
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
const item = "Notebook";
let quantity = 3;
const price = 45;
let total = quantity * price;
document.getElementById("out").textContent =
quantity + " x " + item + " = Rs " + total;
</script>
</body>
</html>▶ Try it yourselfYou may see the older keyword
var in old code. Prefer let and const; they behave more predictably.Key points
constfor values that won't be reassigned,letfor ones that will.- Names are case-sensitive; use clear camelCase names.
- Avoid the old
var.
📝 Test yourself
1. Which keyword creates a value that should not be reassigned?
2. Are price and Price the same variable?
3. Fill in the keyword for a variable that can change:
count = 1;
