This guide presents a syntax comparison between PHP (5.4 minimum) and JavaScript (ES6/ES2015 minimum).
You'll find other guides and a general explanation here.
Data declarations
In JavaScript, variables must be declared first. Since ES6, use only the let
keyword.
/* PHP */ $myData = 'php';
/* JavaScript */ let myData = 'js';
ES6 introduced constants in JavaScript. Complex values can be used and therefore manipulated.
/* PHP */ const MY_DATA = 'php'; const MY_USER = new User(); // Error
/* JavaScript */ const MY_DATA = 'js'; const MY_USER = new User(); // OK MY_USER.name = 'New name';
Simple data types
Integers and decimal numbers share the same type in JavaScript.
/* PHP */ $userMan = true; $userAge = 81; $userAverage = 10.5; $userName = 'Henri Bergson';
/* JavaScript */ let userMan = true; let userAge = 81; let userAverage = 10.5; let userName = 'Henri Bergson';
In addition to null
, JavaScript has the undefined
type,
and NaN
(Not a Number). They are errors, so do not use them.
String details
In JavaScript, line breaks are not allowed in simple or double quotes.
/* PHP */ $userFirstName = 'Henri'; $userLastName = 'Bergson';
/* JavaScript */ let userFirstName = 'Henri'; let userLastName = "Bergson";
ES6 introduced template literals : new backtick quotes for variable interpolation and allowing line breaks. Be careful with the brackets position and role : in PHP, they are here to isolate the variable to avoid confusion ; in JavaScript, they are here to allow an expression.
/* PHP */ $userFullName = "{$userFirstName} {$userLastName}";
/* JavaScript */ let userFullName = `${userFirstName} ${userLastName}`;
Also useful to manage simple and double quotes in the same string.
/* PHP */ $standardSQL = <<<"HEREDOC" SELECT "firstName" FROM "users" WHERE "lastName" = 'Bergson'; HEREDOC;
/* JavaScript */ let HTMLTemplate = `<p class="content">I'm Henri !</p>`;
Prefer the backticks syntax over concatenation, as it's confusing with additions.
/* PHP */ $userFirstName . ' ' . $userLastName;
/* JavaScript */ userFirstName + ' ' + userLastName;
Data lists
Arrays are only for numerically indexed lists in JavaScript. When copied, they are passed by reference.
/* PHP */ $userBooks = ['Book 1', 'Book 2']; $userBooks[0]; count($userBooks); $userBooks[] = 'Book 3';
/* JavaScript */ let userBooks = ['Book 1', 'Book 2']; userBooks[0]; userBooks.length; userBooks.push('Book 3');
Associative arrays are called objects in JavaScript.
/* PHP */ $user = [ 'firstName' => 'Henri', 'lastName' => 'Bergson' ]; $user['firstName'];
/* JavaScript */ let user = { firstName: 'Henri', lastName: 'Bergson' }; user.firstName;
Blocks
Space is required in else if
in JavaScript.
/* PHP */ if ($userAge > 18) {} elseif ($userAge > 21) {}
/* JavaScript */ if (userAge > 18) {} else if (userAge > 21) {}
Like in PHP, be careful with falsy values.
/* PHP */ $myData = $myData ?: 'default';
/* JavaScript */ let myData = myData || 'default';
In JavaScript, switch
cases are strict comparisons.
Since ES6, thanks to let
,
variables are block-scoped.
/* PHP */ for ($i = 0; $i < 10; $i++) {} $i; // 10, error prone
/* JavaScript */ for (let i = 0; i < 10; i++) {} i; // undefined
Iteration is simplified since ES6.
/* PHP */ foreach ($userBooks as $value) {}
/* JavaScript */ for (let value of userBooks) {}
Another option for complex iterations (only for arrays).
/* PHP */ foreach ($userBooks as $key => $value) {}
/* JavaScript */ userBooks.foreach(function (value, index) {});
Functions
In JavaScript, you can access parent scopes directly.
/* PHP */ $myData = 'php'; function myMethod() { $myData; // null }
/* JavaScript */ let myData = 'js'; function myMethod() { myData; // 'js' }
In JavaScript, parameters are always optional. ES6 introduced default values.
/* PHP */ function myMethod ($required, $optional = 'default') {} myMethod(); // Error
/* JavaScript */ function myMethod (optional1, optional2 = 'default') {} myMethod(); // OK
You must check manually for required arguments.
Non-strict comparison to null
is essential,
as the value can also be undefined
.
/* PHP */ function myMethod($required) {}
/* JavaScript */ function myMethod(required) { if (required == null) { return; } }
ES6 introduced a shorter anonymous functions syntax, named arrow functions.
/* PHP */ array_map(function ($value) { return $value * 2; }, $numbersList);
/* JavaScript */ numbersList.map(value => value * 2);
Built-in functions
All functions are methods in JavaScript, and so are called from an object.
/* PHP */ mb_strpos($myEmail, '@'); str_replace('@', '[at]', $myEmail); mb_substr($myEmail, 0, 5); mb_strlen($myEmail); (int) '10'; array_key_exists('name', $user); in_array('Book 1', $userBooks); time(); var_dump($varToDebug); json_encode($user); json_decode('{}');
/* JavaScript */ myEmail.indexOf('@'); myEmail.replace('@', '[at]'); myEmail.substr(0, 5); myEmail.length; parseInt('10'); 'name' in user; userBooks.includes('Book 1'); Date.now(); console.log(varToDebug); JSON.stringify(user); try { JSON.parse('{}'); } catch (error) {}
When a function seems to be called directly, like parseInt()
,
it's because the global object is implicit : window.parseInt()
.
Do use the shorthand, as the global object is not always window
.
Classes
ES6 introduced classes syntax, to simplify object oriented programming in JavaScript. Properties are directly created in the constructor. Pre-declared properties may appear in future JavaScript versions.
/* PHP */ class User { public $firstName; public function __construct($firstName) { $this->firstName = $firstName; } public function sayHello() {} } $myUser = new User('Henri'); $myUser->firstName; $myUser->sayHello();
/* JavaScript */ class User { constructor(firstName) { this.firstName = firstName; } sayHello() {} } let myUser = new User('Henri'); myUser.firstName; myUser.sayHello();
In JavaScript inheritance, parent call is required in the child constructor.
/* PHP */ class Editor extends User { public function __construct($firstName) { parent::__construct($firstName); } public function sayHello() { parent::sayHello(); } }
/* JavaScript */ class Editor extends User { constructor(firstName) { super(firstName); } sayHello() { super.sayHello(); } }
Getters and setters have a special syntax in JavaScript (but you can do classic accessors too).
/* PHP */ class User { private $firstName; public function getFirstName() { return $this->firstName; } public function setFirstName($newFirstName) { $this->firstName = $newFirstName; } } $myUser = new User('Henri'); $myUser->getFirstName(); $myUser->setFirstName('New name');
/* JavaScript */ class User { get firstName() { return this._firstName; } set firstName(newFirstName) { this._firstName = newFirstName; } } myUser = new User('Henri'); myUser.firstName; myUser.firstName = 'New name';
No specific syntax in JavaScript for static methods access.
/* PHP */ class Utilities { public static function filter() {} } Utilities::filter();
/* JavaScript */ class Utilities { static filter() {} } Utilities.filter();
For now, there is no visibility modifiers, no interfaces and no abstract classes in ES7. It may appear in future JavaScript versions. But you can have them now with TypeScript.
Namespaces
Namespacing is directly managed by the loading system since ES6 :
if there is the export
keyword or
import
keyword,
then you are not anymore in the global scope.
/* PHP */ // module.php namespace Symfony\Accounts; class User {} // script.php use Symfony\User\User; $myUser = new User();
/* JavaScript */ // module.js export class User {} // script.js import { User } from './module.js'; let myUser = new User();