Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.
let and const stay inside the block where you declare them
In PHP, a variable declared inside an if or for is still visible in the rest of the function. JavaScript let and const stop at the closing }.
PHP habit
<?php
function firstItem(array $items): ?string {
if (count($items) > 0) {
$first = $items[0];
}
return $first ?? null;
}
JavaScript equivalent
function firstItem(items) {
let first = null;
if (items.length > 0) {
const candidate = items[0];
first = candidate;
}
return first;
}
| Situation | PHP | JavaScript (let/const) |
|---|---|---|
Variable inside if |
Visible after the block | Not visible outside |
Loop counter with let |
N/A | New binding each iteration |
Legacy var in JS |
Leaks like PHP | Avoid in new code |
Declare outside when you need the value later
function process(items) {
let status = 'empty';
if (items.length > 0) {
status = 'ok';
}
return status;
}
Same pattern as initialising $status before an if in PHP.
Loops and closures
const fns = [];
for (let i = 0; i < 3; i++) {
fns.push(() => i);
}
console.log(fns.map((fn) => fn())); // [0, 1, 2]
// with var — all closures share one i → [3, 3, 3]
Use let in loops when callbacks capture the index — covered again with closures next lesson.
Try it
Use the amber Try it panel below. Click Run.
function blockDemo() {
const outer = 'outside';
if (true) {
const inner = 'inside block';
console.log(outer, inner);
}
console.log('after block:', outer);
// console.log(inner); // ReferenceError
}
blockDemo();
You should see two lines inside the block and one after — no access to inner outside.
From PHP to JavaScript — Control Flow, Functions, and Scope