Animal fun facts logical and question

So the last part of the project gets us to switch the background on and with a variable showBackground = true that is flipped using logical and : ‘&&’.

const showBackground = false;

const animalFacts = (
<h1>{title == "" ? "Click an animal for a fun fact" : title}</h1>
{showBackground && background}
<p id="fact"></p>
<div className="animals">

I don’t get how this works. I have used && in conditionals before and get that it requires both sides to be truthy to evaluate to true. Here I guess it always evaluates to false as the background is either there, or it isn’t, not both. I just don’t get why it’s done this way, you have to change the showBackground variable to true or false to get it to switch, so what is the benefit of doing it this way? Why not just set it to true if you want it and false if you don’t?

Am I missing something?

You’re right that && is commonly used as an operator within if statements as the boolean AND, but it also has another special use known as the “Nullish coalescing operator”, but I just think of it as the “super simple if statement.”

&& is a shortcut used to mean (if X… do Y) - with no alternative, no else, etc. The format is just:

X ?? Y
Meaning if X… do Y.

So say you walk past a person and if you know them, you want to say hi, and if you don’t, you want to do nothing, you could use the code:

personKnown && sayHi

meaning - if person is known, say hello. Otherwise, do nothing.

In other words, it’s a short if statement for a case where you only want to do something if it’s true, otherwise you want to do nothing. The same could also be achieved with a regular if statement too.

1 Like

Still a bit confused why we would go to all this trouble when we could just decide to not have a background, but then, maybe the point was that I learn about the nullish coalescing operator and in that case, it worked :laughing:

Codecademy moves in mysterious ways.

Thanks Samantha