// Note: only this code example is quoted from the book var middle = stooge["middle-name"] || "(none)"; var status = flight.status || "unknown";
|| (or) operator to do null coalescing. Basically, as long as the first value is not null or undefined it’s returned, otherwise the second value is returned. This really simplifies the process of getting object property values when you need to use a default value if it’s not set yet, and keeps you from needing to use an if statement.
Below is an example of what I used to do Previous to learning this trick:
var middle = (stooge["middle-name"] != null ? stoog["middle-name"] : "(none)"); var status = (flight.status != null ? flight.status : "unknown");
This new trick makes the code much easier to read, and checks for undefined *also so I no longer need to worry about the value being equal to *undefined in some rare circumstance.
- 01 Jul 2020
- 06 Apr 2020
- 02 Jan 2020
Recent on Build5Nines.com
- 08 Aug 2022
- 07 Aug 2022
- 05 Aug 2022
- 05 Aug 2022
- 04 Aug 2022
This site is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com. We also participates in affiliate programs with Udemy, and other sites. This site is compensated for referring traffic and business to these companies.