JavaScript, inside out · Chapter 2 of 51
Variables
By the end of this chapter you can choose between let, const and var, and say where a name can be used and what it holds before the line that declares it runs. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: First day at Tapri
- 5 tasks
- JavaScript
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
Meera wants the paper token machine in the app: every customer gets the next number. Anjali needs to add an item to the menu without breaking the other screens that show it, and her price tag shows a regular's discounted price to everyone in the queue.
In chapter 1 you kept values with const, and that is how Ravi wrote the token count. But a const can never be given a new value, so his machine stops with an error before handing out a single token. To fix these bugs you need to know what each kind of variable allows.
The lesson
let changes, const stays
A variable is a name for a value. let makes one you can reassign, with = or a shortcut like +=:
let cupsSold = 0;
cupsSold = cupsSold + 1;
cupsSold += 2;
console.log(cupsSold);
3
const makes a name that always points at the same value. Giving it a new one stops the program with an error: that is what happens to Ravi's token machine (press Check on the starter and read task 1's message). Start with const, and switch to let only when the value really has to change, like a counter.
A name can be declared only once in the same place. Declare it twice and the file does not even start:
SyntaxError: Identifier 'shift' has already been declared
Changing is not reassigning
const locks the name, not what is inside. A const array can still get new items: push adds one to the end of the same array (chapter 10 has more on arrays):
const riders = ['Imran', 'Sunita'];
riders.push('Arjun');
console.log(riders, riders.length);
[ 'Imran', 'Sunita', 'Arjun' ] 3
Changing the inside of an array or object is mutation. Pointing the name at a different array with = is reassignment. const forbids only the second, and code holding on to the array sees every push, because it is still the same array.
Blocks
A block is the code between { and }, like the body of an if. A let or const declared inside a block exists only inside it. A block may even declare its own name that hides one outside with the same name:
let rider = 'Imran';
{
let rider = 'Sunita';
console.log('inside:', rider);
}
console.log('outside:', rider);
inside: Sunita
outside: Imran
var is the old way, and it ignores blocks. A var belongs to the whole function around it (or the whole file), so a var inside a block is the same variable as any var of that name around it, and outlives the block. Modern code uses let and const.
Before the declaration
Before a scope runs, JavaScript reads it and sets up every name declared in it. This is called hoisting. A var is set up holding undefined. A let or const is set up locked, and stays locked until its own line runs: that stretch is the temporal dead zone (TDZ). Touching a locked name stops the program with an error. That is on purpose: an error is easier to spot than a quiet undefined.
var area = 'Domlur';
let bike = 'KA 01 4521';
console.log(area, bike);
Domlur KA 01 4521
typeof gives the name of a value's type as text (chapter 3 is all about it):
console.log(typeof 40, typeof true);
number boolean
Your turn
Your five tasks are at the top, all in exercise.js. The first three are bugs to fix. Tasks 4 and 5 ask what each snippet prints, or the name of the error it throws. Task 5 is a classic interview question: can typeof look at a name never declared, or one in its dead zone?
What you build: 5 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
nextToken: fix the token machine
nextToken() is broken now: its first call stops with an error. Fix it so it hands out the next token number on every call: 1 on the first call, then 2, then 3.
The count is kept outside the function, in lastToken, which starts at 0 because nobody has had a token yet.
- Task 2
addToMenu: add to the same menu
addToMenu(item) is broken now: it stops with an error. Fix it so it adds the item to the end of menu and returns how many items menu has now: addToMenu('Parle-G') gives 4, and then addToMenu('filter coffee') gives 5.
Other screens hold on to the menu array, so it must stay the very same array, with the new items at its end in the order they were added. Making menu a let and building a new array stops the error but fails, because the screens still hold the old array.
- Task 3
priceTag: fix the regular's price tag
priceTag(item, isRegular) is broken now: a regular sees their own price as the menu price too, like Masala chai: ₹35 (you pay ₹35). Fix it so the menu price is always the item's price, and a regular also sees their price, which is ₹5 less.
For Masala chai at 40, someone who is not a regular gets Masala chai: ₹40, and a regular gets Masala chai: ₹40 (you pay ₹35). For Cutting chai at 25, a regular gets Cutting chai: ₹25 (you pay ₹20).
- Task 4
scopePredictions: which lines work and which throw
Export scopePredictions, an object with the keys a, b, c and d, one for each snippet in the comment above it. For each, write as a string exactly what console.log prints (a printed 12 would be the string '12'), or, if the snippet throws, the error's name: 'ReferenceError' or 'TypeError'.
The check runs the same snippets and compares.
- Task 5 · interview question
Interview: hoistingPredictions, reading a name before its line
Export hoistingPredictions, an object with the keys a, b, c and d, one for each snippet in the comment above it. Same rules as task 4: as a string, exactly what console.log prints, or the error's name, 'ReferenceError' or 'TypeError', if the snippet throws.
The check runs the same snippets and compares.
What you will learn
- let and const: a name you can point at a new value, and one you cannot.
- Changing is not reassigning: why a const array can still grow.
- Blocks: where a let or const can be used, and why var ignores the braces.
- Hoisting: what a name holds before its own line runs.
More in First day at Tapri
Build "Variables" yourself
Tapri, a chai brand going online, needs its menu, orders and kitchen in code. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.