// 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.
This blog post is licensed under the Creative Commons Attribution 3.0 United States License, unless explicitly stated otherwise within the blog post content. All other content on this website is not licensed under Creative Commons licensing.