// Note: only this code example is quoted from the book var middle = stooge["middle-name"] || "(none)"; var status = flight.status || "unknown";
true when your looking at a variable that is not set to
undefined, you can use the
|| (or) operator to do null coalescing. Basically, as long as the first value is not
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.