Boris K
Boris K

Reputation: 3580

D3: setting style conditionally with immediately invoked arrow function and ternary

I'm going through the FreeCodeCamp beta curriculum for D3, and am trying to set color conditionally.

This attempt at setting it with an immediately invoked arrow function and ternary is not working.

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

Any idea why?

Upvotes: 0

Views: 484

Answers (1)

M. Davis
M. Davis

Reputation: 719

As @altocumulus said, the easiest way to do this is to pass d3's style setter a function:

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

D3 will solve this function given the value of d any time this line is called. If the data changes, and this style setter is called again, the color will update.

If that's not what you intended, you could use the anonymous closure as you do, with the following changes:

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

One reason you may want to do this is if the color depended on some dynamic variable which is not included in the data you passed to this selection, such as the current Date. You can pass this variable in by name in the place of someVariable.

The main issue with your current arrow function is that you do not pass it a variable inside the parentheses, so d will be undefined. The rest is just syntax:

  1. In arrow functions, if the body of the function is a one-liner, the return statement is implied.
  2. The ternary operator has it's own sort of "return"-ability. Think of it as a micro-function:

    var foo = (a ? b : c);
    

is essentially:

var foo = (function (a) {
    if (a) return b;
    else return c;
})(a);

Upvotes: 2

Related Questions