LEARN JS. CONTROL FLOW ( Ternary Operator )


#1

Hey guys!

I’m just getting deeply into JS and faced a problem with section 10 of Control Flow chapter (Ternary Operator Assignment). If there any other relevant topic pardon me please…

There is some kind of awkward situation for me but if someone could explain me more detailed remarkable difference between * ? * and * === * operators. If I understood it correctly === compares something while ? just do exact command ??? It’s getting confusing. If you can provide real situations in which one or another will be beneficial or just explain it more briefly I would appreciate it.

EXAMPLE:

let isLocked = false;

isLocked ? console.log(‘You will need a key to open the door.’) : console.log(‘You will not need a key to open the door.’);

let isCorrect = true;

isCorrect ? console.log(‘Correct!’) : console.log(‘Incorrect!’);

let favoritePhrase = ‘Love That!’;

favoritePhrase === ‘Love That!’ ? console.log(‘I love that!’) : console.log(“I don’t love that!”);


#2

this:

isLocked ? console.log(‘You will need a key to open the door.’) : console.log(‘You will not need a key to open the door.’);

is just a shorter way of writing:

if ( isLocked ){
   console.log(‘You will need a key to open the door.’);
} else {
  console.log(‘You will not need a key to open the door.’);
}

the ? and : used is just part of syntax to achieve this shorthand.