DEV Community

Cover image for PHP 8 features I wish also existed in JavaScript
Andreas
Andreas

Posted on • Updated on

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);
//-----^
Enter fullscreen mode Exit fullscreen mode

JavaScript:

foo('test', 42, true, 'bar', 5.5, false);
//--------------------------------^
Enter fullscreen mode Exit fullscreen mode

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.

See RFC: Named Arguments

#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, 200      => "Super Thin",
  300           => "Thin",
  400, 500      => "Normal",
  600, 700, 800 => "Bold",
  900           => "Heavy",
  default       => "Not valid"
};
Enter fullscreen mode Exit fullscreen mode

JavaScript:

let fontWeight = '';
switch (weight) {
  case 100:
  case 200:
    fontWeight = "Super Thin";
    break;
  case 300:
    fontWeight = "Thin";
    break;
  case 400:
  case 500:
    fontWeight = "Normal";
    break;
  case 600:
  case 700:
  case 800:
    fontWeight = "Bold";
    break;
  case 900:
    fontWeight = "Heavy";
    break;
  default:
    fontWeight = "Not valid";
    break;
}
Enter fullscreen mode Exit fullscreen mode

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.

See Docs: match

#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;
Enter fullscreen mode Exit fullscreen mode

JavaScript:

const country =
  session && session.user && session.user.getAddress() && session.user.getAddress()['country']
  ? session.user.getAddress()['country']
  : null;
Enter fullscreen mode Exit fullscreen mode

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.

See RFC: Nullsafe Operator

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.


Edited: 10th of February 2021 (extended match example)
Published: 8th of February 2021

Oldest comments (63)

Collapse
 
valeriavg profile image
Valeria

The first and the last (types arguments and optional chaining) are available with TypeScript. And for the "match" you can simply use object constant:-)
But nice try!

Collapse
 
devmount profile image
Andreas

Thank you for these additions! Can you give examples for #1 and #3 in TypeScript? This article is about native JavaScript since not everyone is using TypeScript in every project.
Of course you can use an object constant, but match is nevertheless a bit more syntactic sugar here and directly assigns the values instead of storing them first πŸ€·πŸ»β€β™‚οΈ

Collapse
 
mirrorbytes profile image
Bob • Edited

The way you'd used named parameters in JavaScript OR TypeScript is through the use of an object:

JavaScript:

function test ({ a, b, c, d }) {
    ...
}

test({ a: 'test', b: 'test', d: 'test' });
Enter fullscreen mode Exit fullscreen mode

TypeScript:

interface testing {
    a: string;
    b: string;
    c?: string;
    d?: string;
}

function test ({ a, b, c, d }: testing) {
    ...
}

test({ a: 'test', b: 'test', d: 'test' });
Enter fullscreen mode Exit fullscreen mode

The way you'd use optional chaining is actually available in ESNext now:

const country =
  session?.user?.getAddress?.()['country']
  ? session.user.getAddress()['country']
  : null;
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
devmount profile image
Andreas

Thank you for giving these examples! As I wrote in the article, I know about using object destructuring for named arguments, but I don't like this approach very much here - just doesn't feels like clean coding style to use an object inside the functions parameter definition. I can't think of a reason, why JavaScript doesn't already provide "real" named arguments already...

optional chaining is actually available in ESNext now

Great, didn't know that! πŸ‘πŸ»

Thread Thread
 
mirrorbytes profile image
Bob

I agree 100%, however, it would drastically hinder performance as it would almost guaranteed be a runtime check in the engine. That's why I'm hoping either Babel or TypeScript will tackle it in the future to essentially be compiled away into positional arguments.

Thread Thread
 
valeriavg profile image
Valeria • Edited

Not sure I follow your thought. Typescript performs type checks on compilation only and strips all the types away, so there's never a runtime check.
Update: Oh you mean for chaining arguments? There's zero to none performance loss

Thread Thread
 
mirrorbytes profile image
Bob

We're discussing named parameters and the performance hit they would be on JavaScript's runtime.

And TypeScript does a whole lot more than type checking nowadays.

Thread Thread
 
shuckster profile image
Conan

I must chime-in with a report from experience.

Some years ago I worked on a fairly large (~700k lines) JavaScript codebase that implemented a 200-line helper that permitted the following:

function get () {
  var opts = defaults(arguments, {
    byId: null,
    theseItems: '*',
  });
  return [opts.byId, opts.theseItems];
}

get();             // [null, '*']
get(2, 'cats');    // [2, 'cats']
get({ byId: 1 });  // [1, '*']
Enter fullscreen mode Exit fullscreen mode

It was used extensively, including in time-critical places such as during render operations. While there was a performance hit that could be measured with dev-tools, it was nothing compared to the usual day-to-day bottlenecks that were encountered.

The point is to say that sure, worry about performance, but perhaps rest/spread/destructuring isn't the first place you need to look these days.

Collapse
 
wearypossum4770 profile image
Stephen Smith • Edited

I don't follow the link between "native javascript" and typescript. TS is compiled to JS. I think you can use a Map to achieve the same results with a php match. EDIT
This is a haphazardly written code complete with as close to replicated functionality you would expect from PHP match

class UnhandledMatchError extends Error {
    constructor(value, ...args) {
        super(...args)
        this.name = "UnhandledMatchError"
        this.message = `Unhandled match value of type ${typeof value}`
        Error.captureStackTrace(this, UnhandledMatchError)
    }
}
const match = item => new Map([
    [100, "Super Thin"],
    [300, "Thin"],
    [400, "Normal"],
    [600, "Bold"],
    [900, "Heavy"]
]).get(item) ?? new UnhandledMatchError(item)

console.log(match(100))
>>> Super Thin
console.log(match(102))
>>> UnhandledMatchError: Unhandled match value of type number
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
devmount profile image
Andreas

As you already said: TS requires a compiler to JS. This article was meant for those writing JS directly.
Cool idea, can you give an example with Map?

Collapse
 
rsa profile image
Ranieri Althoff

Your example of the switch wouldn't work, you are assigning to a constant variable. I consider declaring without defining an issue, and would rather split the switch to a separate function (e.g. getFontWeight) and create the variable with const fontWeight = getFontWeight(value). It's cleaner and better to test.

Thread Thread
 
devmount profile image
Andreas

My bad, thanks for pointing out πŸ‘πŸ» I updated the example code. Totally agree with you about the separate function, nevertheless I just used let to keep things simple.

Collapse
 
dwarni profile image
Andreas We • Edited

You can easily replicate match behavior (actually not, see edited version):

const match = {
  100: () => "SuperThin",
  300: () => "Thin",
  400: () => "Normal",
  600: () => "Bold",
  900: () => "Heavy"
};
const fontweight = match[weight];
Enter fullscreen mode Exit fullscreen mode

Edit

As Stephen pointed out by using the above solution fontweight will contain a function.
For some reason I did not come up with an even simpler solution first:

const match = {
  100: "SuperThin",
  300: "Thin",
  400: "Normal",
  600: "Bold",
  900: "Heavy"
};
const fontweight = match[weight];
Enter fullscreen mode Exit fullscreen mode

You can also do it without having to store the object in "match":

const fontweight = {
  100: "SuperThin",
  300: "Thin",
  400: "Normal",
  600: "Bold",
  900: "Heavy"
}[weight];
Enter fullscreen mode Exit fullscreen mode

And if you need a default value you can achieve it like that:

const fontweight = {
  100: "SuperThin",
  300: "Thin",
  400: "Normal",
  600: "Bold",
  900: "Heavy"
}[weight] || "Normal";
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pris_stratton profile image
pris stratton • Edited

That’s very clever πŸ˜€

It reminds me of the guards expression in Haskell.

Collapse
 
wearypossum4770 profile image
Stephen Smith

The issue I can see with this is now the variable fontweight is a function is it not?

Collapse
 
dwarni profile image
Andreas We • Edited

No it isn't. EDIT: Sorry you are right it is a function, for some reason I was so focused on the Arrow operator on PHP that I wanted to do something similar but did not come up with the even simpler solution.

I will update my post.

Collapse
 
hasnaindev profile image
Muhammad Hasnain

In JavaScript, all of these features are available but the syntax can get dirty as pointed out by others. I really wish if PHP has a strong hinting system for associative arrays.

Collapse
 
groundhogs profile image
Ground Hogs

You could always use something like this for the last one (fairly sure I did something similar in PHP before this was an option):

function get(obj, path=[], fallback=null, separator="."){
  if(path.constructor === String){
    path = path.split(separator);
  }

  return path.reduce(
    (r, k) => r[k] || fallback,
    obj
  );
}
/** 
# Examples

const convolutedObject = {a:1,b:{a:2,b:{a:3,b:{a:4,b:5}}}};
get(convolutedObject, ["b","c"], "wrong"); // "wrong"
get(convolutedObject, "b.b.b.a"); // 4
*/
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dmahely profile image
Doaa Mahely

This post got me excited to use PHP8!

Collapse
 
devmount profile image
Andreas

Awesome, glad to hear that πŸ‘πŸ»

Collapse
 
peerreynders profile image
peerreynders • Edited

#1 Named parameters

just doesn't feels like clean coding style to use an object inside the functions parameter definition.

Everybody's entitled to their opinion - but at this point using an (options) object and destructuring it is an established idiom which means that adding "real named arguments" would add more complexity to the language for very little gain.

just doesn't feels like clean coding style to use an object inside the functions parameter definition.

That's actually pretty common in languages that support pattern matching on the language level (pattern matching is a conditional construct, destructuring is not - example: Elixir).


#2 Match Expression - There is a TC39 Proposal ECMAScript Pattern Matching - as it is only at stage 1 at this point it may never happen.

That said your particular example could be readily implemented with a Map:

const fontWeight = new Map([
  [100, 'Super Thin'],
  [300, 'Thin'],
  [400, 'Normal'],
  [600, 'Bold'],
  [900, 'Heavy'],
]);

console.log(fontWeight.get(600)); // "Bold"
Enter fullscreen mode Exit fullscreen mode

PS: the examples employing objects in this manner overlook that an object's keys have to be either strings or symbols - while a Map's keys can be any value. So using a number on an object as a key will result in it being coerced into a string.

Granted it would be really useful to have something like Rust's match expression or ReScript's switch (i.e. OCaml's match).

However Franceso Cesarini of Erlang Solutions observes that newcomers to Erlang have three hurdles :

  • The first hurdle is pattern matching.
  • The second hurdle is understanding recursion and the whole concept of tail recursion versus non-tail recursion.
  • And the third kind of hurdle is thinking concurrently.

i.e. pattern matching isn't something that people find all that intuitive, at least initially - though from what I've witnessed once they "get it", they can't get enough of it.


#3 Optional Chaining is part of ES2020 (June 2020), Chrome 80 (February 2020), Firefox 74 (March 2020), Node 14.0.0 (April 2020). (caniuse: JavaScript operator: Optional chaining operator (?.))

(Related: Nullish coalescing operator (??) - caniuse: JavaScript operator: Nullish coalescing operator (??))

Collapse
 
devmount profile image
Andreas

Wow, thank you for these detailed insights πŸ˜πŸ‘πŸ» I really like how the discussion explodes here πŸ˜…

Collapse
 
peerreynders profile image
peerreynders

FYI: Often the answer is Use Functions!:

function fontWeight(value) {
  switch (value) {
    case 100:
      return 'Super Thin';
    case 300:
      return 'Thin';
    case 700:
      return 'Bold';
    case 900:
      return 'Heavy';
    default:
      return 'Normal';
  }
}

console.log(fontWeight(700)); // "Bold"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tomaszs2 profile image
Tom Smykowski • Edited

3 - it means for 15% of internet users app or website using optional chaining will break because older browsers does not support it.

Collapse
 
peerreynders profile image
peerreynders

Given that you are supposed to be practicing Differential Serving anyway it's a non-issue.

ESNext is transpiled down to ES2017 to yield smaller bundles for modern browsers while larger bundles transpiled all the way down to ES5 are available for legacy browsers.

A Universal Bundle Loader
Bringing Modern JavaScript to Libraries
Publish, ship, and install modern JavaScript for faster applications

Thread Thread
 
tomaszs2 profile image
Tom Smykowski

Still, the post is a comparison between JavaScript and PHP, and you write about EcmaScript:

  • 15% of users have browsers with JavaScript that does not support optional chaining
  • I have to use transpiler from EcmaScript to JavaScript to be able to use it

= JavaScript does not support optional chaining

Thread Thread
 
peerreynders profile image
peerreynders

JavaScript is nothing more than a trademark of ORACLE America, Inc. which they obtained through their acquisition of Sun Microsystem, Inc.. The trademark was licensed by Sun to Netscape and later to the Mozilla Foundation.

Other than that JavaScript is just a colloquialism to refer to the scripting language features that are used for browser automation. ECMAScript is an effort to standardize that scripting language. As it is, no browser claims to implement any ECMAScript spec in full - they only aspire to do so (and often they implement features beyond the spec).

Back in the day we used jQuery to bridge gap between the variations between different browser vendor implementations. Today we use Babel to bridge the gaps that have emerged over time. The more things change, the more they stay the same - so while the tools have changed, we still have to bridge gaps.

You are free to use whatever dialect you prefer - though I don't envy anyone who may have to help support your work.

But ES2020 includes the Optional chaining (?.) operator so it is now part of what people colloquially refer to as "JavaScript" - MDN lists it under the JavaScript Reference - and it is available to everyone to use via Babel.

Collapse
 
hbgl profile image
hbgl

The one JS feature that I wish existed in any language: async-await.

Collapse
 
devmount profile image
Andreas

100% yes to that! πŸ‘πŸ» async/await makes code so much more readable and clean.

Collapse
 
garretharp profile image
Garret • Edited

1:

function foo ({ a, b, c, d, e, f }) {
    // do stuff
}

foo({ f: false })
Enter fullscreen mode Exit fullscreen mode

2:

const weightList = {
    100: "Super Thin",
    300: "Thin",
    ...
}

const fontWeight = weightList[weight]
Enter fullscreen mode Exit fullscreen mode

3:

(Requires Typescript or ESNext)

const country = session?.user?.getAddress()?.country
Enter fullscreen mode Exit fullscreen mode
Collapse
 
727021 profile image
Andrew Schimelpfening

Thanks for this post. Really interesting discussion in the comments. As someone who primarily works with JS/TS, it’s cool to learn a little more about modern PHP.

Collapse
 
devmount profile image
Andreas

I'm glad this was useful for you! And yes, the discussion here quickly escalated - I like it πŸ˜…

Collapse
 
wearypossum4770 profile image
Stephen Smith

Also I think maybe our termi ology may be different. Parameters are declared with the function definition, what the function is expecting. Arguments are passed to the function when called. So when arguments are destructured in the parameters it doesn't use an object, they are just local scope variables.
developer.mozilla.org/en-US/docs/G...

function foo({
  a=0,  <- parameter
  b=0,  <- parameter
  c=0,  <- parameter
  d=0,  <- parameter
  e=0,  <- parameter
  f=0,   <- parameter
  ...rest
  }){
return d
}

foo({d:9,h:10})  <- arguments
Enter fullscreen mode Exit fullscreen mode

Destructure, assignment, rest, and spread are all JS language specific techniques to make code readable and cleaner. Different languages can feel clustered if you are not use to working with it, but that is why different languages exist because they all are useful for some use case. Like why can PHP use keywords "let, const, var" to declare variables? Or why can all languages do as Python and just have no keyword required for variable declaration?

.

Collapse
 
devmount profile image
Andreas

Thank you for this clarification πŸ‘πŸ» I do love the variety of programming languages, but sometimes you used a feature in one language you really liked and wished it also existed in another, that's all πŸ˜…

Collapse
 
devmount profile image
Andreas

Awesome! Didn't know #3 was already possible in JS πŸ‘πŸ»

Collapse
 
aalphaindia profile image
Pawan Pawar

Thanks for sharing

Collapse
 
devmount profile image
Andreas

My pleasure 😊

Collapse
 
tomaszs2 profile image
Tom Smykowski

Great post. But actually I am disappointed that people try to defend js by writing false info about availability of these features. PHP is a leading language. It is normal it has things earlier

Collapse
 
ogrotten profile image
ogrotten

The reason js doesn't have a couple of these is that the same thing can be accomplished in a similar amount of code with already existing features. Therefore, adding them doesn't truly make things better. Why add a named parameter feature if it's already doable with an object?

Collapse
 
tomaszs2 profile image
Tom Smykowski

It is not the same. Named parameters are enforced. Object params are not

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

You can do all of this (or something damn close) already in JS in almost all modern browsers. You dont even need TypeScript (but that's true as a general statement anyway!)

Collapse
 
oskarcodes profile image
Oskar Codes

For your last point, there is the optional chaining operator that just came to JavaScript in 2020: developer.mozilla.org/en-US/docs/W...

Some comments may only be visible to logged-in visitors. Sign in to view all comments.