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

Branching syntax you already know from PHP

if, ternary, and switch look almost the same in JavaScript. The differences are small: else if is two words, and switch still needs break to avoid fall-through.

PHP habit: if and ternary

<?php
$score = 85;

if ($score >= 90) {
    echo 'A';
} elseif ($score >= 70) {
    echo 'B';
} else {
    echo 'C';
}

$label = $score >= 70 ? 'Pass' : 'Fail';

JavaScript equivalent

const score = 85;

if (score >= 90) {
  console.log('A');
} else if (score >= 70) {   // two words: else if
  console.log('B');
} else {
  console.log('C');
}

const label = score >= 70 ? 'Pass' : 'Fail';
PHP JavaScript
elseif else if
$score >= 90 score >= 90 (no $)
Ternary ? : Same shape

PHP habit: switch

<?php
$status = 'draft';

switch ($status) {
    case 'published':
        echo 'Live';
        break;
    case 'draft':
        echo 'Work in progress';
        break;
    default:
        echo 'Unknown';
}

JavaScript equivalent

const status = 'draft';

switch (status) {
  case 'published':
    console.log('Live');
    break;
  case 'draft':
    console.log('Work in progress');
    break;
  default:
    console.log('Unknown');
}

Fall-through without break is still a footgun in both languages. Use break unless you intentionally want the next case to run.

When to reach for if vs switch

Use switch for one variable against many known constants (status codes, action names). Use if for ranges and compound conditions (score >= 70 && score < 90).

Try it

Use the amber Try it panel below. Click Run.

function grade(score) {
  if (score >= 90) return 'A';
  if (score >= 70) return 'B';
  return 'C';
}

function statusLabel(code) {
  switch (code) {
    case 'ok': return 'OK';
    case 'warn': return 'Warning';
    default: return 'Unknown';
  }
}

console.log(grade(85), statusLabel('warn'));

Same control flow you would write in a PHP controller or service, without the sigils.

From PHP to JavaScript — JavaScript Syntax Foundations for PHP Devs