Search code examples
javascriptfunctionconditional-statementsternarytruthy

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.

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 || "";