Scope
You'll learn where a variable can be used, and why JavaScript sometimes says a variable "is not defined".
Watch & read
Start with the required ones. The others are there when you need them.
See it step by step
See which variables each line can use.
Explanation
You make a variable inside a function, then try to use it outside, and JavaScript says
ReferenceError: delivery is not defined. The variable exists, so why can't it be found?
Every variable lives in a certain area of the code, called its scope. With let and const, that
area is the nearest pair of curly braces { } around it, called a block. A function body, an if
block and a loop body are all blocks.
Think of a house. Inside your room, you can see your own things and everything in the shared hallway. From the hallway, you can't see into the rooms.
const shop = "Dhaka Mart"; // hallway: everyone can see itfunction checkout(price) {const delivery = 60; // inside the room onlyconsole.log(shop); // fine: looking outwardreturn price + delivery;}console.log(delivery); // ReferenceError
Code can look outward, never inward. checkout can read shop, which is outside it. The last line
can't read delivery, because delivery only lives inside checkout. When the function ends, its
variables are gone.
Two variables in different blocks can even have the same name. The inner one hides the outer one while you are inside its block. This is called shadowing. It is legal, but it confuses readers, so try to avoid it.
People often make a variable inside a loop or an if, then try to use it after the closing }. If you
need it after the block, make it before the block.
When you see "is not defined", find where the variable was made. Then check: is the line that uses it
inside the same { }, or inside one of its inner blocks?
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1let total = 0;2const paid = true;3if (paid) {4 let total = 50;5}6console.log(total);
cartTotal should add up every price in the cart. Right now it says total is not defined. Fix it so both checks pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3
const year = 2;is made at the top of the file. Can a function below readyear? - 2 / 3
function pay() { const fee = 5; }What happens if you writeconsole.log(fee)after the function? - 3 / 3
const name = "Rafi"; function hi() { const name = "Nusrat"; return name; }What doeshi()return?