Skip to content
jshacks.dev
Fundamentals

JavaScript for PHP Developers a Practical Comparison

A guide for PHP developers learning JavaScript: concatenation, truthiness, arrays versus objects, string length, equality and a server that keeps state.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, PHP and Vite logos.

A PHP developer has an advantage when learning JavaScript that is easy to underestimate: both languages are dynamically typed, forgiving about types, and born in the web. The syntax is close enough that a loop, a function and a class can be written in either, and many tasks translate line by line. The differences that cost time are not in the syntax. They are in what the two languages do with the same-looking operators, in how arrays and dictionaries are split, and above all in how a program runs: a PHP script starts and dies with each request, and a Node.js server stays alive and keeps its variables. This post goes through the differences with the output of each snippet, in the order that most often bites, and ends with habits to build. The JavaScript runs on Node.js 24, and the PHP is PHP 8.4, with outputs written from the language rules.

The vocabulary map

PHPJavaScriptNotes
$namenameNo sigil; declare with const or let
. concatenation+ or template literal+ adds and concatenates
-> and ::.One operator for properties and static members
array (list)Arraypush() instead of $a[] = $x
array (associative)Object or MapTwo types for one PHP type
count($a)a.lengthA property
strlen($s)s.lengthCounts UTF-16 units, not bytes
isset($a['k'])a.k !== undefined, or "k" in a
$a ?? 'x'a ?? "x"The same operator
fn($x) => $x * 2(x) => x * 2Arrow functions
echoconsole.log()
requireimportES modules

Plus and dot

PHP uses . to join strings and + only for numbers. JavaScript uses + for both.

PHP
var_dump("5" + 3);
var_dump("5" . 3);
var_dump("5" - 3);
Text
int(8)
string(2) "53"
int(2)
JavaScript
console.log("5" + 3, typeof ("5" + 3));
console.log("5" - 3, typeof ("5" - 3));
console.log(5 + 3 + "px", "px" + 5 + 3);
console.log(`${5 + 3}px`);
Text
53 string
2 number
8px px53
8px

In JavaScript, if either operand of + is a string, the result is a string, so "5" + 3 is "53", where PHP adds them and gives 8. Subtraction has no string meaning, so both languages convert to numbers. The order matters: 5 + 3 + "px" adds first, and "px" + 5 + 3 joins first, giving px53. Template literals avoid the whole problem, and they are the replacement for PHP's double-quoted interpolation. Convert with Number() before arithmetic on input.

Truthiness

The two languages disagree on three values.

PHP
foreach (["0", "", "0.0", [], "false", 0.0] as $value) {
    echo json_encode($value), " ", var_export((bool) $value, true), "\n";
}
Text
"0" false
"" false
"0.0" true
[] false
"false" true
0.0 false
JavaScript
for (const value of ["0", "", "0.0", [], "false", 0]) {
  console.log(JSON.stringify(value), Boolean(value));
}
Text
"0" true
"" false
"0.0" true
[] true
"false" true
0 false

The string "0" is falsy in PHP and truthy in JavaScript, and an empty array is falsy in PHP and truthy in JavaScript. if ($items) is a valid emptiness check in PHP, and if (items) in JavaScript is always true for an array: write items.length > 0. The falsy values in JavaScript are false, 0, -0, 0n, "", null, undefined and NaN, and everything else is truthy.

Arrays and objects are separate

A PHP array is an ordered map that serves as a list and as a dictionary. JavaScript splits the two.

PHP
$list = [10, 20, 30];
$map = ["name" => "Ada", "age" => 36];
$list[] = 40;
$map["city"] = "London";

echo count($list), " ", count($map), "\n";
echo implode(",", array_keys($map)), "\n";
Text
4 3
name,age,city
JavaScript
const list = [10, 20, 30];
const map = { name: "Ada", age: 36 };
list.push(40);
map.city = "London";

console.log(list.length, Object.keys(map).length);
console.log(Object.keys(map).join(","));

const lookup = { b: 1, 2: "two", a: 3, 1: "one" };
console.log(Object.keys(lookup));
console.log(new Map([[1, "x"], ["1", "y"]]).size);
Text
4 3
name,age,city
[ '1', '2', 'b', 'a' ]
2

Use an Array for ordered lists and an Object for records with known string keys. For a dictionary with arbitrary or non-string keys, use a Map. Object keys that look like integers are sorted first in ascending order, so insertion order is not fully kept for them, which PHP's arrays do keep. A Map keeps both the key types and the order. Counting is a property, length for arrays and size for maps, and an object has neither, so Object.keys(map).length is the count of its keys.

isset, empty and the null family

PHP
$user = ["name" => "Ada", "email" => null];

var_dump(isset($user["email"]), isset($user["name"]), isset($user["missing"]));
var_dump($user["email"] ?? "none", $user["missing"] ?? "none");
Text
bool(false)
bool(true)
bool(false)
string(4) "none"
string(4) "none"
JavaScript
const user = { name: "Ada", email: null };

console.log(user.email !== undefined, "email" in user, "missing" in user);
console.log(user.email ?? "none", user.missing ?? "none");
console.log(user.profile?.avatar ?? "none");

function show(value = "default") {
  return value;
}

console.log(show(undefined), show(null), show(""));
Text
true true false
none none
none
default null 

PHP has one "no value" value, null, and isset() treats it as unset. JavaScript has two: undefined, the default for anything not assigned, and null, which code assigns on purpose. A missing key is undefined, there is no warning for reading it, and the in operator tells a key that exists with null from one that does not exist. The ?? operator works as in PHP, for both values, and ?. stops a chain at a missing link, like PHP's ?-> for objects, and for any property. Note the last line: a default parameter applies only for undefined, so show(null) returns null, and an empty string stays empty.

String length and encoding

PHP
echo strlen("héllo"), " ", mb_strlen("héllo"), " ", strlen("😀"), " ", mb_strlen("😀"), "\n";
Text
6 5 4 1
JavaScript
console.log("héllo".length, "😀".length, [..."😀"].length);
console.log("héllo".toUpperCase(), "héllo".padEnd(8, "*"), "a-b-c".replaceAll("-", "+"));
console.log("Ada Lovelace".split(" ").map((p) => p[0]).join(""));
Text
5 2 1
HÉLLO héllo*** a+b+c
AL

strlen() counts bytes, which is why é takes 2 and the emoji takes 4, and mb_strlen() counts characters. JavaScript strings are UTF-16, and length counts code units: é is 1, and the emoji is 2, because it needs a surrogate pair. There is no mb_ family: methods on a string already handle Unicode text for case and search, and [...text] or Intl.Segmenter count what a reader sees. String functions are methods on the string, not global functions with the string as the first argument.

Equality

PHP 8 changed its comparison rules, and the two languages still differ.

PHP
var_dump("1" == "01", "10" == "1e1", 100 == "1e2", "abc" == 0, null == false, [] == false);
Text
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
JavaScript
console.log("1" == "01", "10" == "1e1", 100 == "1e2", "abc" == 0, null == false, [] == false);
console.log("1" === "01", 1 === 1, [1] === [1]);
Text
false false true false false true
false true false

PHP compares two numeric strings as numbers, so "1" == "01" and "10" == "1e1" are true, and JavaScript compares two strings as text, so they are false. In PHP, null == false is true and in JavaScript it is false. Use === in JavaScript, as you would in PHP, which never converts types. Note that arrays compare by identity: [1] === [1] is false, where PHP compares arrays by value.

A server that keeps its state

This is the difference that changes how you design programs. A PHP request starts with nothing and ends by discarding everything. A Node.js server is one long-running process, and module-level variables persist across requests and are shared by all users.

JavaScript
let hits = 0;
const sessions = new Map();

function handleRequest(userId) {
  hits += 1;
  const count = (sessions.get(userId) ?? 0) + 1;
  sessions.set(userId, count);
  return `hit ${hits} overall, ${count} for ${userId}`;
}

console.log(handleRequest("ada"));
console.log(handleRequest("grace"));
console.log(handleRequest("ada"));
Text
hit 1 overall, 1 for ada
hit 2 overall, 1 for grace
hit 3 overall, 2 for ada

Each call is a separate request, and the variables accumulate. That is useful for caches and connection pools, which are created once and reused, and it is dangerous for per-user data stored in a global, which leaks between users and grows without end. In PHP, "global" means one request. In Node.js, it means the life of the process. Keep request data in local variables or on a request object, and treat module state as shared and permanent.

Asynchronous work

PHP
$data = file_get_contents("data.json");
$decoded = json_decode($data, true);
echo count($decoded), "\n";
JavaScript
import { readFile } from "node:fs/promises";

const text = await readFile(new URL("./data.json", import.meta.url), "utf8");
const decoded = JSON.parse(text);
console.log(Object.keys(decoded).length);

PHP calls block until the work is done, and that is fine because each request has its own process. A Node.js server shares one thread, and blocking it blocks every user, so I/O is asynchronous: the function returns a promise and await pauses the current function only. The synchronous versions, such as readFileSync, exist for scripts and start-up code. The model is covered in the event loop question.

Classes and methods

JavaScript
class Cart {
  static taxRate = 0.2;
  #items = [];

  add(name, price) {
    this.#items.push({ name, price });
    return this;
  }

  total() {
    const sum = this.#items.reduce((acc, item) => acc + item.price, 0);
    return Math.round(sum * (1 + Cart.taxRate) * 100) / 100;
  }
}

const cart = new Cart().add("pen", 2).add("book", 10);
console.log(cart.total(), Cart.taxRate);
Text
14.4 0.2

A class looks like PHP's: static for class members, private fields with #, and method chaining by returning this. Properties and methods are reached with a single dot, where PHP uses -> for instances and :: for static members. There are no magic methods such as __get, no visibility keywords other than the # prefix, and no interfaces, though Proxy and getters cover some of the same needs.

Habits to build

Use const and let. Use === and !==. Test emptiness with .length. Use ?. and ?? as the replacement for isset. Use template literals for strings. Use array methods in place of the array_* functions. Await every promise, and never block the thread. Keep per-request data out of module variables. And run a linter, since many of these differences are caught before the code runs.

Where the PHP comparison stops

The ecosystems differ as much as the languages: Composer and Packagist versus npm, a framework request lifecycle versus a long-running server with its own routing, and PHP's tight link with the web server versus a runtime that is a general-purpose platform. The language gaps, such as the new keyword rules and this, are in the interview questions in this library. The reference is in the MDN JavaScript guide and the PHP manual.

Taggedphp
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.