Control Flow: Ternary Operator


#1

could someone explain it to me why is not working this way? thanks in advance

https://www.codecademy.com/courses/learn-javascript-control-flow/lessons/control-flow/exercises/ternary-operator?action=lesson_resume&course_redirect=introduction-to-javascript

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 = 'I love that!';

favoritePhrase?
  console.log('I love that!') : 
  console.log("I don't love that!");

#2

The conditional in the ternary is binary (boolean) which means any non-empty string will be truthy so your return will always be the true branch. In this case we will need to actually examine the input string.

favoritePhrase === 'I love that!' ?

Extra study

Something that isn’t very obvious (yet) is that we can write the ternary expression right inside the console.log argument…

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

#3

Thanks a lot for your response but still not working this way

let favoritePhrase = ‘I love that!’;

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


#4
let favoritePhrase = 'Love That!';

favoritePhrase === 'Love That!' ?

#5

Still not working

let favoritePhrase = ‘Love that!’;

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


#6

Seems okay. No problem on my end. Try a refresh, perhaps?

Is it just step 3 that is giving a problem?


#7

Thanks a lot anyway, it seems like it doesn’t want to work. Yes, just the 3rd.


#8

Maybe try it on one line?

let favoritePhrase = 'Love That!';

favoritePhrase === 'Love That!' ? console.log('I love that!') : console.log("I don't love that!");

#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.