FAQ: Conditional Statements - Ternary Operator

This community-built FAQ covers the "Ternary Operator " exercise from the lesson “Conditional Statements”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise _Ternary Operator _

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

So in the exercise it said this was the correct answer

let favoritePhrase = ‘Love That!’;

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

how come it still goes through when the favoritePhrase equals something different then what the console has in it. The only difference is the ‘I’. How come it still goes through when the favoritePhrase doesn’t equal whats in the console?

The string literal in the condition does not have any relation to the string literals in the logged values. Those are outcomes relating to do or don't.

The solution is presented as below in this exercise:

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

Because we are asked to refactor the if...else block to use a ternary operator, shouldn’t there be only a ? instead of === ‘Love That!’ just like in the two previous steps?

The ternary operator needs a conditional expression to precede it, hence, ?

'is this true' ? 'yes' : 'no'

console.log(a === 42 ? "The meaning of life" : "Nope!");

Notice that the entire expression can be written as an argument to a function or method?

The lesson solution follows this pattern…

conditional ? action if truthy : action if falsy

The ‘action’ is itself a statement. In my example the ternary is what gets passed to the action.

Thanks, mtf. Maybe I should have shared more of the code here to make my question clearer:

let favoritePhrase = ‘Love That!’;

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

I guess my question is… can we not simply write favoritePhrase ? instead of favoritePhrase === ‘Love That!’ ? as the value has already been assigned to the variable earlier?

2 Likes

We need the complete expression since we are testing whether the variable was set, or not, to the correct value. Think of a dynamic state where the program doesn’t know this.

a = Math.floor(Math.random() * 42) + 1
console.log(a === 42 ? "The meaning of life" : "Nope!");
// Nope!

The test doesn’t know the value of a but insists that it is 42 in order to follow the truthy branch.

conditional ? truthy branch : falsy branch

A conditional can also be a state.

r = Math.floor(Math.random() * 2);    // 0 or 1
console.log(r ? 'set' : 'not set');   // not set on 0
1 Like

Thanks again, mtf. I believe we didn’t need to test it (whether the variable was set, or not, to the correct value) with the following code (that was written earlier in the same exercise) as in those cases the variables were already assigned to true or false. Did I get right?

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!’);

Keep in mind, it is you who knows the value that is set, not the computer. We write it in the code so we must know it. The computer does not. Remember, computers are dumb. Since it is the computer running our program it falls to us to be sure there is correct information in the pike. That takes testing (conditionals).

Variables that are set have state; those that are not are undefined. There are lots of ways to consider state, so don’t carve it in stone.

let z
console.log(z)    // undefined
console.log(z ? 'state is truthy' : 'state is falsy')   // state is falsy
z = 0
console.log(z ? 'state is truthy' : 'state is falsy')   // state is falsy
1 Like

Hello, It’s about the assignment about ternary operators. but it actually involves many assignments.
No 1st, 2nd or 3rd if…else block appears on my screen, so I can not make the assignment because there is nothing to change by using ternary operators. I have this problem with almost all predefined commands that I have to edit. When I ask for a solution, I do not get a solution, but all assignments are approved while I have not yet executed them. Gladly because I can not continue working like this! Or do I have to pick up the assignments somewhere?
With best regards

Jeffrey Goei

The escape character is first introduced when the user fails to use it in the solution. It should be introduced to the student before their statement (which was written by the program and not the student) is determined to be wrong.

The definition of Ternary Operator is not clearly outlined in the lesson and must be referenced in a third-party program. The definition of the object we are learning to use should be in the opening of the lesson where its use is discussed.
In the final portion of the lesson where conditionals are reviewed, this sentence appears: “The ternary operator is shorthand to simplify concise if...else statements.” However the operator ? does not appear on the page. It should be added to the definition just as <, >, ||, etc also appear on the page.

Is there a reason why I can’t see the sample code for the exercises? Is it because I’m using the FREE version? Example, the ternary operator’s 3 exercises refer to sample code to reference to create the ternary line of code. I can’t see these …. am I missing something or do I have to 'Go Pro? I kinda noticed this in earlier exercises but I schlepped through it.
Thanks!

1 Like

I cannot see the sample code for this either. It still has my code for the previous exercise and when I delete that and refresh the exercise it keeps restoring the code for the previous exercise. Looks like it is supposed to include some code that mentions favoritePhrase? I can’t see this. Could anyone help out please?

Thanks

The sample code is in the lesson narrative.

let isNightTime = true;

if (isNightTime) {
  console.log('Turn on the lights!');
} else {
  console.log('Turn off the lights!');
}

We can use a ternary operator to perform the same functionality:

isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');

The code from the previous lesson is meant to be carried over. Each step asks us to refactor one of the code segments.

Hi,

Thanks for your reply. So I should be Refactoring or editing this code just to be clear?

let tool = ‘marker’;

// Use short circuit evaluation to assign writingUtensil variable below:
let writingUtensil = tool || “pen”

console.log(The ${writingUtensil} is mightier than the sword.);

There’s definitely an error in this section as when I clicked solution the main.js doesn’t show anything. I’ve moved on to the next section which says “In main.js there is already an if...else statement in place” However my main.js shows nothing, there’s no if else statement there?

Yes, edit the code directly to refactor it into a ternary statement.

It is very-very important to note that : Can we use multiple actions in truthy/falsy part?

eg. if (condition)
{
action-1;
action-2;

}
else
{
action-n; //n th action
action-(n+1); // n+1 th action

}

in ternary form???

Yes, we can, but with one proviso… There is no block demarcation so that action should be simple, else it would be better to abstract it away in a function and call the function from the ternary.

Something we commonly see is console.log() as an action in each branch…

a % 2 === 0 ? console.log(`${a} is even.`) : console.log(`${a} is odd.`);

These are both simple actions that call the same function. Now let’s consider a couple things:

  • a ternary is an expression
  • console.log() accepts any expression and parses it as text characters to the console as best it can.

That means we don’t have to call the method in each branch, we can pass the entire ternary as the argument.

console.log(a % 2 === 0 ? `${a} is even.` : `${a} is odd.`);

All expressions boil down to one value. It’s that value that will be logged in this instance. The point here is that ternary expressions should be simple if they are to be easy to read and comprehend. They are not a de facto replacement for if..else, only a convenience to lighten the code.

Above I mentioned that ternaries have no block demarcation. Well, that’s not entirely true since JS recognizes ALL blocks, even if they have no keyword or identifier associated.

a % 2 === 0 ? {
    console.log(`${a} is even.`)
} : {
    console.log(`${a} is odd.`)
};

Now the reader can see the blocks and if they contain a few lines of code it will still be clear which branch of the ternary they are in. I rather doubt many teachers would go along with this, though.

Bottom line, keep your ternary expressions simple and well defined. The moment they get complicated, the reader could get muddled. That could make for some heady maintenance work that might otherwise go smoothly.

const doubleX = x => x * 2;
const halfX = x => x / 2;

const messingAround = a => a % 2 === 0 ? halfX(a) : doubleX(a);

See how the functions help abstract away the maths?

2 Likes

Addendum

We can return a function reference without invoking it, effectively giving the caller an object that can be called multiple times in the ensuing session.

const callbackChooser = a => a % 2 === 0 ? halfX : doubleX;

https://repl.it/@mtf/callbackChooser