DEV Community

Discussion on: Operators/Conditional statements: if (youUnderstand) {'Great!'} else {'Read on'}

Collapse
 
vonheikemen profile image
Heiker

I want to share a tiny bit of trivia I learned last year. Here I go: It turns out there is nothing special about the combination of else if.

If you write an if or an else statement without curly braces it will only "apply" to the next statement. So this is valid.

if(1 > 1) 
  console.log('What?');
else 
  console.log('Duh!');

So is this.

if(1 > 1) console.log('What?');
else console.log('duh!');

When we do this.

if(1 > 1) {
  console.log('What?');
} else if(1 == 1) {
  console.log('Of course');
}

In here it just so happens that the else is followed by an if, which (I think) is technically only one statement.

We could do this (but we shouldn't).

let lesson = 'cool';

if(lesson == 'learned') {
  console.log('I deserve a break');
} else while(lesson == 'cool') {
  console.log('Ooohhh');
  lesson = 'learned';
}

We could also have: else switch, else for, etc...

Again, don't do this at home, or work, or in side projects or anywhere. It's just a funny thing javascript can do.