PHP 8 features I wish also existed in JavaScript
I know there is still a lot of hatred for PHP out there, but in my opinion with version 7 at the latest (which is already over 5 years old!), PHP evolved to a great language that is fun and even type-safe to use. Next to Just-In-Time compilation, which may give a big performance boost to PHP applications, version 8 brings a lot of useful features.
I want to present three of them I really wish I could use in JavaScript as well. I hope that comes in handy especially for those, who didn’t take a look at PHP 8 yet. Let’s go!
#1 Named arguments
Let’s assume, you have a function foo
with 6 parameters a
to f
having different default values and now you want to call that function passing the argument false
for the last parameter only.
PHP 8:
foo(f: false);
JavaScript:
foo('test', 42, true, 'bar', 5.5, false);
In JavaScript passing arguments to a function is solely based on the parameter position, unfortunately. I know that named arguments can be simulated by using objects and destructuring, but a native feature would be much more convenient here.
#2 Match expression
The new match
expression of PHP is very similar to the switch
statement, except it is an expression and can be used to directly assign values to a variable or return values. This comes in very handy, if you have more than two possible values for assignment.
PHP 8:
$fontWeight = match ($weight) {
100 => "Super Thin",
300 => "Thin",
400 => "Normal",
600 => "Bold",
900 => "Heavy"
};
JavaScript:
const fontWeight = '';
switch (weight) {
case 100:
fontWeight = "Super Thin";
break;
case 300:
fontWeight = "Thin";
break;
case 400:
fontWeight = "Normal";
break;
case 600:
fontWeight = "Bold";
break;
case 900:
fontWeight = "Heavy";
break;
}
The match
expression may be simulated by a JavaScript object, but that would require an additional variable (thus more reserved memory) and will fail for cases, where the checked values aren't allowed to be used as object keys.
#3 Optional Chaining
Chaining only if the needed property exists is a very elegant way to query objects. In PHP you can do this now with the nullsafe operator.
PHP 8:
$country = $session?->user?->getAddress()?->country;
JavaScript:
const country =
session && session.user && session.user.getAddress() && session.user.getAddress()['country']
? session.user.getAddress()['country']
: null;
In JavaScript you still have to check step by step, if the corresponding property exists. There is a corresponding TC39 proposal which is in stage 4 by now and I’m really looking forward to this being part of the ECMAScript Specs.
Wrap it up
So we saw a small selection of the new PHP 8 features that would also be a great addition to JavaScript. Maybe you have other PHP features in mind that are missing in JavaScript or you know a better JavaScript counterpart to the above problems than me? Great! Let’s discuss it in the comments.
Originally published: 8th of February 2021 on dev.to