10. Ternary Operator - Doesn't let me pass even though my code is fine


#1

<PLEASE USE THIS TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-javascript-control-flow/lessons/control-flow/exercises/ternary-operator?action=lesson_resume

<Below this line, in what way does your code behave incorrectly? Include ALL error messages.>
Third instruction doesn’t complete. Code is fine and it’s been logging to the console fine.

```

let isLocked = false;

/*
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.’);
}
*/

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;

/*
if (isCorrect) {
console.log(‘Correct!’);
} else {
console.log(‘Incorrect!’);
}
*/

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

let favoritePhrase = ‘Love That!’;

/*
if (favoritePhrase === ‘Love That!’) {
console.log(‘I love that!’);
} else {
console.log(“I don’t love that!”);
}
*/

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

<do not remove the three backticks above>

#2

Did you finally get this to work? If not, try removing all the commented code and Run. If still not, refresh the page and it may correct itself.


Extra practice that goes beyond this lesson to refactor some more…

Since console.log() can take any expression, we can pass the ternary expression directly to the method…

let a = ! Math.floor(Math.random() * 2);

console.log(a ? +a : a);

The above will output 1 or false.

Let’s explore one of your examples a little further…

let isLocked = ! Math.floor(Math.random() * 2);

console.log("You will" + (isLocked ? '' : ' not') + " need a key to open the door.");

The parens are critical.


#3

I got it to work. It’s a bug. The issue was with the quotes. Can’t use double quotes on the third if/else, only single.

Thanks for the help and thanks for the extra practice. Though I didn’t understand exactly why it evaluates to false, I did understand your main point. I would have incorporated your example at least into one of the course’s exercises.


#4

Good to know. Perhaps at some point this issue can be addressed in the SCT to accept both forms of string.

It returns false if a is 0. This is because ! doesn’t just negate, it coerces to a boolean. In the true branch I apply the unary operator to value of a which converts true to 1. If the second branch of the ternary was also +a it would have logged a 0. There are a couple of hidden lessons in that example.

Good suggestion. I have invited the Community Manager to this topic so he can pass your suggestion up the line to the course team.


#5

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