Tuesday, 13 June 2017

JavaScript - shorthand if statement (sans else)

I'm all in favour of shorthand statements and I often visit this Sitepoint page. I'm also keen on ES6 destructuring as I seem to spend a lot of time thinking about the shape and patterns of data anyway.

One shorthand I've always like is the if using &&:

Given these constants:

const thing  = "fred";

const helloWorld = () => {
    console.log("hello");
    console.log("world");
};

We can do this:

thing === "fred" ? helloWorld() : null;  // hello\nworld

thing === "Fred" ? helloWorld() : null;  // nowt

We can also do this:

thing === "fred" && helloWorld(); // hello\nworld

thing === "Fred" && helloWorld(); // nowt

But, even better, we can do this:

thing === "fred" && (() => {
    console.log("hello");
    console.log("world");
})();  // hello\nworld

thing === "Fred" && (() => {
    console.log("hello");
    console.log("world");
})();  // nowt

How cool is that? JSFiddle here.

No comments:

Post a Comment