What is scope in JavaScript?
Written by Jatin Thacker, Automation Architect · Updated
{ } block exist only there, while code inside can still read the variables declared around it.This answer is one piece of Chapter 3: Functions.
Scope answers one question: from this line, which variables can I use? Inner code can see outwards; outer code cannot see in.
The example starts with baseUrl at the top of the file. The function orderUrl() uses it freely, because a function can read the variables around it. Inside, orderUrl() declares its own path. Once the function returns, path is gone, and reading it from outside throws ReferenceError: path is not defined.
Blocks create scope too, but only for let, const and class. Inside the if, status is declared with const, so outside it typeof status is undefined. leaked is declared with var, which ignores blocks, so it is still there after the if closes. That is one reason test code uses const and let.
The last part matters most in tests. With let in a for loop, each round gets its own i, so three saved functions return 0, 1 and 2. Write the same loop with var and there is a single i, shared by all three, and they all return 3.
In Playwright files the same rule explains why a variable declared inside one test() is not visible in the next one.
const baseUrl = 'https://practice.learnplayforge.com';
function orderUrl(id) {
const path = `/orders.html?seed=42#${id}`;
return baseUrl + path;
}
console.log(orderUrl('ORD-4100'));
try {
console.log(path);
} catch (err) {
console.log(err.name + ':', err.message);
}
if (true) {
const status = 'packed';
var leaked = 'var ignores the block';
}
console.log(typeof status, '|', leaked);
const later = [];
for (let i = 0; i < 3; i++) later.push(() => i);
console.log(later.map((fn) => fn()));https://practice.learnplayforge.com/orders.html?seed=42#ORD-4100 ReferenceError: path is not defined undefined | var ignores the block [ 0, 1, 2 ]
if block a test declares const total = 5 and var count = 2. After the block closes, which can still be read?Try a real drill. No sign-up.
Related questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free