o9s
is a microblog
home archives search feed blogroll


The Lie That Is Else If

JavaScript doesn’t actually have an else if construct. It’s an if inside an else.

The code -

if (false) {
  console.log("no");
} else if (true) {
  console.log("yes");
}

- is actually -

if (false) {
  console.log("no");
} else {
  if (true) {
    console.log("yes");
  }
}

Knowing this, you can get fancy with else. You can use loops in an else statement!

if (false) {
  console.log("no");
} else for (let i = 0; i < 5; i++) {
  console.log(i);
}

let i = 0;

if (false) {
  console.log("no");
} else while (i < 5) {
  console.log(i);
}

You shouldn’t use those. It’s not common practice and it will confuse programmers who read your code.

Posted on 2018-02-06   #javascript     #node  






← Next post    ·    Previous post →