Skip to contentPlayForge

What is a block statement in JavaScript?

Written by Jatin Thacker, Automation Architect · Updated

A block statement is a pair of curly braces that groups zero or more statements into one. Variables declared inside it with let or const exist only inside the block; var ignores the block and leaks out.

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.

block.mjs(node)
var total = 1; let count = 1; { var total = 2; let count = 2; } console.log(total); console.log(count);
Output
2
1
Test yourself
Inside an if block, you write let total = 10; var tax = 2;. After the block ends, which variable can you access?

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

← All questions

Training a team? Talk to us.