What is a block statement in JavaScript?
Written by Jatin Thacker, Automation Architect · Updated
let or const exist only inside the block; var ignores the block and leaks out.This answer is one piece of Chapter 2: Decisions and Loops.
You write blocks all the time: the body of an if, a for loop and a function are all blocks. A block can also stand on its own, as in the example.
The part that catches people is scope. let and const are block-scoped, so the inner count is a new variable and the outer one is untouched. var is not block-scoped, so the inner var total is the same variable as the outer one, and the change survives the block. That difference is why modern test code uses let and const and avoids var.
var total = 1;
let count = 1;
{
var total = 2;
let count = 2;
}
console.log(total);
console.log(count);2 1
if block, you write let total = 10; var tax = 2;. After the block ends, which variable can you access?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