1

What is wrong with this code? if I call this function without any arguments, the expected output is "critical" instead "medium" is returned.

let labelBlock = (label="") =>{
        label = label.toLowerCase();
        const txt = label == "high" ? "High" : "medium" ? "Medium" : "Critical";
        return `<span class="${txt.toLowerCase()}">${txt}</span>`;
      }
0

4 Answers 4

3

label is empty at the start. The first condition label == "high" is false and in the second condition you have "medium", which, in Js, is truthy value hence "Medium" is set.

You can change that line to the following to get Critical. See change (label == "medium")

const txt = label == "high" ? "High" : label == "medium" ? "Medium" : "Critical";
Sign up to request clarification or add additional context in comments.

Comments

3

You need to replace "medium" with "label == 'medium'".

let labelBlock = (label="") =>{
    label = label.toLowerCase();
    const txt = label == "high" ? "High" : label == "medium" ? "Medium" : "Critical";
    return `<span class="${txt.toLowerCase()}">${txt}</span>`;
}

"medium" expression in the second part is always "true" in your code. So the second ternary operator always returns the first value ("Medium").

Comments

1

There is no condition which is evaluated at the second part "medium" ? "Medium" : "Critical";

Hope this works for you

        const txt = label == "high" ? "High" : label == "medium" ? "Medium" : "Critical";

Comments

1

Your ternary operation meaning is below. As you can see the problem is you are checking if ("medium").

  var txt;
  if (label == "high") {
    txt = "High";
  } else {
    if ("medium") {
      text = "Medium";
    } else {
      text = "Critical";
    }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.