Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on • Edited 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 toJust-In-Time compilation, which may give a big performance boost to PHP applications, version 8 bringsa 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 functionfoo with 6 parametersa tof having different default values and now you want to call that function passing the argumentfalse for the last parameter only.

PHP 8:

foo(f:false);//-----^
Enter fullscreen modeExit fullscreen mode

#"http://www.w3.org/2000/svg" width="20px" height="20px" viewbox="0 0 24 24">Enter fullscreen modeExit 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.

SeeRFC: Named Arguments

#2 Match expression

The newmatch expression of PHP is very similar to theswitch 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 modeExit fullscreen mode

#"Super Thin";break;case300:fontWeight="Thin";break;case400:case500:fontWeight="Normal";break;case600:case700:case800:fontWeight="Bold";break;case900:fontWeight="Heavy";break;default:fontWeight="Not valid";break;}

Enter fullscreen modeExit fullscreen mode

Thematch 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.

SeeDocs: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 modeExit fullscreen mode

#"http://www.w3.org/2000/svg" width="20px" height="20px" viewbox="0 0 24 24">Enter fullscreen modeExit fullscreen mode

In JavaScript you still have to check step by step, if the corresponding property exists. There is a correspondingTC39 proposal which is in stage 4 by now and I'm really looking forward to this being part of the ECMAScript Specs.

SeeRFC: 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 (extendedmatch example)
Published: 8th of February 2021

Top comments(66)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
valeriavg profile image
Valeria
Re-inventor extraordinaire, optimisation addict and open web advocate.
  • Email
  • Location
    Stockholm, Sweden
  • Pronouns
    she/her
  • Work
    Engineering Manager at Strawberry
  • Joined

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!

CollapseExpand
 
devmount profile image
Andreas
freelancing software engineer.javascript. php. python. css.husband. dad². guitarero. climber. retrogamer.
  • Location
    Berlin, Germany
  • Education
    M.Sc. Computer Engineering
  • Pronouns
    he/him/his
  • Work
    Freelancing Software Engineer
  • Joined

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, butmatch is nevertheless a bit more syntactic sugar here and directly assigns the values instead of storing them first 🤷🏻‍♂️

CollapseExpand
 
mirrorbytes profile image
Bob
  • Work
    sysadmin
  • Joined
• Edited on• Edited

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

#"http://www.w3.org/2000/svg" width="20px" height="20px" viewbox="0 0 24 24">Enter fullscreen modeExit fullscreen mode

TypeScript:

interfacetesting{a:string;b:string;c?:string;d?:string;}functiontest({a,b,c,d}:testing){...}test({a:'test',b:'test',d:'test'});
Enter fullscreen modeExit fullscreen mode

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

constcountry=session?.user?.getAddress?.()['country']?session.user.getAddress()['country']:null;
Enter fullscreen modeExit fullscreen mode
Thread Thread
 
devmount profile image
Andreas
freelancing software engineer.javascript. php. python. css.husband. dad². guitarero. climber. retrogamer.
  • Location
    Berlin, Germany
  • Education
    M.Sc. Computer Engineering
  • Pronouns
    he/him/his
  • Work
    Freelancing Software Engineer
  • Joined

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
  • Work
    sysadmin
  • Joined

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
Re-inventor extraordinaire, optimisation addict and open web advocate.
  • Email
  • Location
    Stockholm, Sweden
  • Pronouns
    she/her
  • Work
    Engineering Manager at Strawberry
  • Joined
• Edited on• 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
  • Work
    sysadmin
  • Joined

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
JavaScript tinkerer.
  • Joined

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:

functionget(){varopts=defaults(arguments,{byId:null,theseItems:'*',});return[opts.byId,opts.theseItems];}get();// [null, '*']get(2,'cats');// [2, 'cats']get({byId:1});// [1, '*']
Enter fullscreen modeExit 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.

CollapseExpand
 
wearypossum4770 profile image
Stephen Smith
  • Joined

Sorry another thing to add on would be that almost everything in JavaScript is an Object. In the example in this thread there was the example below. But in JavaScript/TypeScript you will normally have a variable that is being passed around. so you're not going to normally pass an Object literal to every function call. Python has both Named Parameters and "Unpacking" (Object Destructing) using thefilename, *args, **kwargs. This is also why I do not like usingtypeof operator to determine the data type i am being passed. Because if you are passed aMap and are using bracket/dot-notation you are not using theMap correctly.

interface testing {    a: string;    b: string;    c?: string;    d?: string;}function test ({ a, b, c, d }: testing) {    ...}const obj = { a: 'test', b: 'test', d: 'test' }test(obj);
Enter fullscreen modeExit fullscreen mode
Thread Thread
 
devmount profile image
Andreas
freelancing software engineer.javascript. php. python. css.husband. dad². guitarero. climber. retrogamer.
  • Location
    Berlin, Germany
  • Education
    M.Sc. Computer Engineering
  • Pronouns
    he/him/his
  • Work
    Freelancing Software Engineer
  • Joined

Valuable addition! Thanks for that.

CollapseExpand
 
rsa profile image
Ranieri Althoff
I make things run fast
  • Work
    Engineer at Volvo Cars
  • Joined

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 withconst fontWeight = getFontWeight(value). It's cleaner and better to test.

Thread Thread
 
devmount profile image
Andreas
freelancing software engineer.javascript. php. python. css.husband. dad². guitarero. climber. retrogamer.
  • Location
    Berlin, Germany
  • Education
    M.Sc. Computer Engineering
  • Pronouns
    he/him/his
  • Work
    Freelancing Software Engineer
  • Joined

My bad, thanks for pointing out 👏🏻 I updated the example code. Totally agree with you about the separate function, nevertheless I just usedlet to keep things simple.

CollapseExpand
 
wearypossum4770 profile image
Stephen Smith
  • Joined
• Edited on• 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 Thinconsole.log(match(102))>>> UnhandledMatchError: Unhandled match value of type number
Enter fullscreen modeExit fullscreen mode
Thread Thread
 
devmount profile image
Andreas
freelancing software engineer.javascript. php. python. css.husband. dad². guitarero. climber. retrogamer.
  • Location
    Berlin, Germany
  • Education
    M.Sc. Computer Engineering
  • Pronouns
    he/him/his
  • Work
    Freelancing Software Engineer
  • Joined

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?

CollapseExpand
 
dwarni profile image
Andreas We
  • Joined
• Edited on• Edited

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

constmatch={100:()=>"SuperThin",300:()=>"Thin",400:()=>"Normal",600:()=>"Bold",900:()=>"Heavy"};constfontweight=match[weight];
Enter fullscreen modeExit 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:

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

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

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

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

constfontweight={100:"SuperThin",300:"Thin",400:"Normal",600:"Bold",900:"Heavy"}[weight]||"Normal";
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
pris_stratton profile image
pris stratton
I love learning coding languages and paradigms, mainly for the sake of it
  • Joined
• Edited on• Edited

That’s very clever 😀

It reminds me of the guards expression in Haskell.

CollapseExpand
 
wearypossum4770 profile image
Stephen Smith
  • Joined

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

CollapseExpand
 
dwarni profile image
Andreas We
  • Joined
• Edited on• 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.

Thread Thread
 
devmount profile image
Andreas
freelancing software engineer.javascript. php. python. css.husband. dad². guitarero. climber. retrogamer.
  • Location
    Berlin, Germany
  • Education
    M.Sc. Computer Engineering
  • Pronouns
    he/him/his
  • Work
    Freelancing Software Engineer
  • Joined

This is a great addition, thank you!

CollapseExpand
 
peerreynders profile image
peerreynders
  • Joined
• Edited on• Edited

#1Named 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 anddestructuring 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 ProposalECMAScript 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 aMap:

constfontWeight=newMap([[100,'Super Thin'],[300,'Thin'],[400,'Normal'],[600,'Bold'],[900,'Heavy'],]);console.log(fontWeight.get(600));// "Bold"
Enter fullscreen modeExit fullscreen mode

PS: the examples employing objects in this manner overlook that anobject's keys have to be either strings or symbols - while aMap's keys can be any value. So using anumber 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'smatch expression or ReScript'sswitch (i.e. OCaml'smatch).

However Franceso Cesarini of Erlang Solutionsobserves 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.


#3Optional 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 (??))

CollapseExpand
 
devmount profile image
Andreas
freelancing software engineer.javascript. php. python. css.husband. dad². guitarero. climber. retrogamer.
  • Location
    Berlin, Germany
  • Education
    M.Sc. Computer Engineering
  • Pronouns
    he/him/his
  • Work
    Freelancing Software Engineer
  • Joined

Wow, thank you for these detailed insights 😍👏🏻 I really like how the discussion explodes here 😅

CollapseExpand
 
peerreynders profile image
peerreynders
  • Joined

FYI: Often the answer isUse Functions!:

functionfontWeight(value){switch(value){case100:return'Super Thin';case300:return'Thin';case700:return'Bold';case900:return'Heavy';default:return'Normal';}}console.log(fontWeight(700));// "Bold"
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
tomaszs2 profile image
Tom Smykowski
I build stunning, scalable MVPs fast with AI and deep frontend expertise
  • Location
    Poland
  • Education
    Engineer
  • Work
    Senior Software Development Consultant
  • Joined
• Edited on• Edited

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

CollapseExpand
 
peerreynders profile image
peerreynders
  • Joined

Given that you are supposed to be practicingDifferential 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
I build stunning, scalable MVPs fast with AI and deep frontend expertise
  • Location
    Poland
  • Education
    Engineer
  • Work
    Senior Software Development Consultant
  • Joined

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
  • Joined

JavaScript is nothing more than atrademark of ORACLE America, Inc. which they obtained through their acquisition ofSun 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 theOptional chaining (?.) operator so it is now part of what people colloquially refer to as "JavaScript" - MDN lists it under theJavaScript Reference - and it is available to everyone to use viaBabel.

CollapseExpand
 
shuckster profile image
Conan
JavaScript tinkerer.
  • Joined
• Edited on• Edited

Didn't realise PHP had such nice language features these days!

Here's a JS solution for #2 just for fun:

// Helpers//constmemoize=(fn,cache=newMap())=>x=>cache.has(x)?cache.get(x):cache.set(x,fn(x)).get(x)constmatchMaker=lookFor=>haystack=>needle=>lookFor(needle,haystack)constmatch=matchMaker((needle,haystack)=>{constfound=haystack.filter(x=>Array.isArray(x[0])).find(x=>x[0].includes(needle))returnfound!==undefined?found[1]:haystack.find(x=>x.length===1)[0]})// Implementation//constfontSize=memoize(match([[[100,200],"Super Thin"],[[300],"Thin"],[[400,500],"Normal"],[[600,700,800],"Bold"],[[900],"Heavy"],[/* default */"Not valid"],]));[100,200,300,400,500,600,700,800,900,901].forEach(size=>{console.log(`${size} = `,fontSize(size))})// 100 =  Super Thin// 200 =  Super Thin// 300 =  Thin// 400 =  Normal// 500 =  Normal// 600 =  Bold// 700 =  Bold// 800 =  Bold// 900 =  Heavy// 901 =  Not valid
Enter fullscreen modeExit fullscreen mode

I included a memoizer just so that it would (with usage) have the "lookup-iness" ofswitch, but obviously it's not quite as elegant as PHP'smatch!

CollapseExpand
 
devmount profile image
Andreas
freelancing software engineer.javascript. php. python. css.husband. dad². guitarero. climber. retrogamer.
  • Location
    Berlin, Germany
  • Education
    M.Sc. Computer Engineering
  • Pronouns
    he/him/his
  • Work
    Freelancing Software Engineer
  • Joined

Awesome, thank you for this addition 😍👏🏻

CollapseExpand
 
shuckster profile image
Conan
JavaScript tinkerer.
  • Joined
• Edited on• Edited

To follow this up, I've since learned about an upcomingTC39 spec on adding pattern-matching to JavaScript.

It's Stage 1 -- so a long way off -- but there aremany libraries available that offer it, now includingmy own.

I even reused yourfont-size example in the README. :)

CollapseExpand
 
shuckster profile image
Conan
JavaScript tinkerer.
  • Joined

No worries! Nice article. 👍

CollapseExpand
 
wearypossum4770 profile image
Stephen Smith
  • Joined

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 modeExit 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?

.

CollapseExpand
 
devmount profile image
Andreas
freelancing software engineer.javascript. php. python. css.husband. dad². guitarero. climber. retrogamer.
  • Location
    Berlin, Germany
  • Education
    M.Sc. Computer Engineering
  • Pronouns
    he/him/his
  • Work
    Freelancing Software Engineer
  • Joined

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 😅

CollapseExpand
 
garretharp profile image
Garret
Web developer & Software engineer with a focus in building tools for content creators
  • Location
    Texas
  • Work
    Full-Stack Engineer at Shotcall
  • Joined
• Edited on• Edited

1:

functionfoo({a,b,c,d,e,f}){// do stuff}foo({f:false})
Enter fullscreen modeExit fullscreen mode

2:

constweightList={100:"Super Thin",300:"Thin",...}constfontWeight=weightList[weight]
Enter fullscreen modeExit fullscreen mode

3:

(Requires Typescript or ESNext)

constcountry=session?.user?.getAddress()?.country
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
groundhogs profile image
Ground Hogs
sr frontender, pragmatist, with a phobia to unnecessary anal retentiveness. On a crusade against professional yak shavin
  • Location
    Montevideo, Uruguay
  • Work
    Sr Frontend Developer
  • Joined

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

functionget(obj,path=[],fallback=null,separator="."){if(path.constructor===String){path=path.split(separator);}returnpath.reduce((r,k)=>r[k]||fallback,obj);}/** # Examplesconst 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 modeExit fullscreen mode
CollapseExpand
 
devdufutur profile image
Rudy Nappée
French freelance dev
  • Location
    France
  • Work
    Lead dev at Niort
  • Joined
• Edited on• Edited


$fontWeight = match ($weight) {
100 => "Super Thin",
300 => "Thin",
400 => "Normal",
600 => "Bold",
900 => "Heavy"
};

Error prone code... What's the value of $fontWeight if $weight = 101 ? Is there an error ?

Safe "Switch expressions" constructs should assert there is always a default clause (i'm looking at you rust 😍)

CollapseExpand
 
devmount profile image
Andreas
freelancing software engineer.javascript. php. python. css.husband. dad². guitarero. climber. retrogamer.
  • Location
    Berlin, Germany
  • Education
    M.Sc. Computer Engineering
  • Pronouns
    he/him/his
  • Work
    Freelancing Software Engineer
  • Joined
• Edited on• Edited

match has a default case too. Also, you can comma-separate multiple values:

$fontWeight=match($weight){100,200=>"Super Thin",300=>"Thin",400,500=>"Normal",600,700,800=>"Bold",900=>"Heavy",default=>"Not valid"};
Enter fullscreen modeExit fullscreen mode

Edited the example in the article accordingly.

CollapseExpand
 
bramus profile image
Bramus!
Chrome DevRel Engineer at Google. CSSWG member. PADI Divemaster. Blogs at bram.us.
  • Location
    Belgium
  • Work
    Web Tinkerer
  • Joined
CollapseExpand
 
devmount profile image
Andreas
freelancing software engineer.javascript. php. python. css.husband. dad². guitarero. climber. retrogamer.
  • Location
    Berlin, Germany
  • Education
    M.Sc. Computer Engineering
  • Pronouns
    he/him/his
  • Work
    Freelancing Software Engineer
  • Joined
  • What if you want to check for values, that aren't allowed as object key? Also an object would require additional (unnecessary) memory and handling of multiple values with the same assignment isn't very elegant either.
  • Thank you for this information 👏🏻
  • That's awesome, I've already read that in other comments.
CollapseExpand
 
ogrotten profile image
ogrotten
  • Joined
• Edited on• Edited

darn near anything is allowable as an object key. Besides that, that's ahigh corner case.

const x = {
["\$&n"]: 12
}

x["\$&n"]
12

I tried to paste this here in a code block, but it wouldn't show.

CollapseExpand
 
hbgl profile image
hbgl
  • Joined

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

CollapseExpand
 
devmount profile image
Andreas
freelancing software engineer.javascript. php. python. css.husband. dad². guitarero. climber. retrogamer.
  • Location
    Berlin, Germany
  • Education
    M.Sc. Computer Engineering
  • Pronouns
    he/him/his
  • Work
    Freelancing Software Engineer
  • Joined

100% yes to that! 👏🏻 async/await makes code so much more readable and clean.

View full discussion (66 comments)

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Andreas
freelancing software engineer.javascript. php. python. css.husband. dad². guitarero. climber. retrogamer.
  • Location
    Berlin, Germany
  • Education
    M.Sc. Computer Engineering
  • Pronouns
    he/him/his
  • Work
    Freelancing Software Engineer
  • Joined

More fromAndreas

JavaScript Array Methods Explained with Emojis
#javascript#webdev#beginners#emojis
ThirdStats — Beautifully Visualized Email Account Stats
#showdev#hacktoberfest#vue#javascript
Automatic Deployment via good ol' FTP
#actionshackathon#javascript#vue#git
DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp