Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.

Translate PHP snippets to JavaScript before you paste into a file

These drills recap chapter 1. Read the PHP habit, predict the JavaScript, then run the equivalent in the sandbox to confirm.

Drill 1: variables

PHP habit:

<?php
$name = 'Stuart';
$name = 'Alex';
define('MAX', 100);

JavaScript equivalent:

let name = 'Stuart';
name = 'Alex';
const MAX = 100;
// const name = 'Stuart'; name = 'x'; // TypeError

Drill 2: string and number

PHP habit:

<?php
$label = "Hello, $name";
$total = (int) '42px';

JavaScript equivalent:

const label = `Hello, ${name}`;
const total = parseInt('42px', 10);

Watch '5' + 2 in JS — that is '52', not 7. Use Number() when adding.

Drill 3: condition and loop

PHP habit:

<?php
$status = 'draft';
$label = $count === 1 ? 'item' : 'items';

foreach ($items as $item) {
    echo $item;
}

JavaScript equivalent:

const status = 'draft';
const label = count === 1 ? 'item' : 'items';

for (const item of items) {
  console.log(item);
}

Drill 4: array and object

PHP habit:

<?php
$tags = ['php', 'js'];
$tags[] = 'api';

$user = ['name' => 'Alice', 'role' => 'admin'];
echo $user['name'];

JavaScript equivalent:

const tags = ['php', 'js'];
tags.push('api');

const user = { name: 'Alice', role: 'admin' };
console.log(user.name);

Drill 5: function and safe access

PHP habit:

<?php
function greet(string $name = 'Guest'): string {
    return "Hello, $name";
}

$city = $user?->address?->city ?? 'Unknown';

JavaScript equivalent:

function greet(name = 'Guest') {
  return `Hello, ${name}`;
}

const city = user?.address?.city ?? 'Unknown';

Score yourself

Drill You got it if…
1 You used let for reassignment and const for constants
2 You used template literals and parseInt with radix 10
3 You used ===, ternary, and for...of
4 You used push and object dot/bracket access
5 You used default params, ?., and ??

Try it

Use the amber Try it panel below. Click Run.

const drills = [
  { php: '$tags[] = "api"', js: () => { const t = ['php']; t.push('api'); return t; } },
  { php: "'5' + 2 in PHP is 7", js: () => Number('5') + 2 },
  { php: 'foreach as $item', js: () => { const a = [1, 2]; let s = 0; for (const n of a) s += n; return s; } },
  { php: '$user["name"]', js: () => ({ name: 'Alice' }).name },
];

for (const { php, js } of drills) {
  console.log(php, '→', js());
}

If any line surprises you, revisit that lesson before the chapter project.

From PHP to JavaScript — JavaScript Syntax Foundations for PHP Devs