Why if-else block works but not ternary?

Why if-else block works but not ternary?
0

#1

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

//ternary doesn't work
      .style("color",(d) => {
      (d < 20) ? "red" : "green" })
 
//if-else block works
      .style("color", (d) => {
        if(d < 20){
          return "red";
        }else{
          return "green";   }
      } )

// Add your code above this line

Link to the challenge https://learn.freecodecamp.org/data-visualization/data-visualization-with-d3/change-styles-based-on-data


#3

You miss the return statement in ternary


#5

They’re an expression, and the syntax youve chosen requires that you return a value

() => // implicit return
() => {
  // explicit return
}

Note the curly brackets: you’re telling JS that that is a block statement, and you need to return from it to get anything out.


#6

They’re an expression, and the syntax you’ve chosen requires that you return a value

what do you mean by this? I’ve returned the color prop


#7

You haven’t returned any value:

.style("color", d => { (d < 20) ? "red" : "green" })

The arrow function will return that block, but that’s it, not the stuff inside the block, it won’t bother evaluating it.

It’s effectively the same as

.style("color", function(d) { (d < 20) ? "red" : "green" })

There’s no return statement for the ternary, so the function returns undefined.

The only time you can avoid the return statement is if you remove the curly braces, then it isn’t the block being returned, it’s the actual value the ternary evaluates to. So either

.style("color", d => (d < 20) ? "red" : "green")

Or

.style("color", d => {
  return (d < 20) ? "red" : "green"
})

#8

A good way to spot that the ternary will be a suitable replacement for an if/else statement is when the return keyword is used multiple times and is the only expression inside of the if block.

var func1 = function( .. ) {
  if (condition1) { return value1 }
  else { return value2 }
}

var func2 = function( .. ) {
  return condition1 ? value1 : value2
}