Data Visualization with D3 - Change Styles Based on Data

Hey everyone, this challenge is quite simple and I passed it using if-else statement. But I cannot find out why I cant use the ternary operator like below. Please help me

My code so far

<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

    d3.select("body").selectAll("h2")
      .data(dataset)
      .enter()
      .append("h2")
      .text((d) => (d + " USD"))
      // Add your code below this line
      .style("color", (d) => {
        if (d < 20) {
          (d < 20) ? return "red" : return "green";
      });
      // Add your code above this line
  </script>
</body>

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

Challenge: Data Visualization with D3 - Change Styles Based on Data

Link to the challenge:

Since you’re wrapping the ternary operation with an if-statement, nothing happens when d >= 20. Also, you are missing a closing bracket in the callback function.

Furthermore, you can’t have return in a ternary because they evaluate to an expression. If you wanted to return the result of a ternary, you could write it like this:

return isTrue ? true : false;

And you could put that in a callback function:

(d) => {
  return d ? "d is true" : "d is false"
}

Hope this helps.

1 Like

Omg thank you a lot <3

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.