Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I check truthy when using Ternary Operator

I am having issues with using the ternary operator and checking if a value is truthy or not. I have a feeling that my syntax is incorrect. Below is the instructions on what I need to do to pass this step, and the two lines of code with the comments "here" is what I wrote for the solution. Please help me.

"Use a ternary operator to check if currentTitle evaluates to a truthy value. If it does, set playingSong.textContent to currentTitle. Otherwise, set it to an empty string.
Then below that, use a ternary operator to check if currentArtist is truthy. If so, set songArtist.textContent to currentArtist. Otherwise, set it to empty string."

const setPlayerDisplay = () => {
  const playingSong = document.getElementById("player-song-title");
  const songArtist = document.getElementById("player-song-artist");
  const currentTitle = userData?.currentSong?.title;
  const currentArtist = userData?.currentSong?.artist;
  currentTitle ? playingSong.textContent = currentTitle : playingSong.textContent = ""; //here
  currentArtist ? songArtist.textContent = currentArtist : songArtist.textContent = ""; //here
};

I tried writing it differently, but I still am getting an error. Here is my other attempt.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

currentTitle = currentTitle ?  playingSong.textContent = currentTitle : playingSong.textContent = "";
currentArtist = currentArtist ? songArtist.textContent = currentArtist : songArtist.textContent = "";

>Solution :

You are putting 2 separate assignments inside the ternary operator, like this:

condition ? a = x : a = y;

You should instead write a single assignment that uses a ternary expression, and let the ternary operator decide on what value to use, like this:

a = condition ? x : y;

For the above it doesn’t matter if condition is boolean (true/false) or if it is truthy/falsy.

Applied to your code, this is what you should use:

playingSong.textContent = currentTitle ? currentTitle : "";
songArtist.textContent = currentArtist ? currentArtist : "";

Finally if using the ternary operator is not an actual requirement, then this can be shortened even further:

playingSong.textContent = currentTitle || "";
songArtist.textContent = currentArtist || "";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading