Reputation: 2470
I'm doing some work with D3.js and am looking at tweaking a version of one of the built-in mapping projections. I'm looking through the source code and have found the function definition below which uses a syntax I'm not familiar with:
function albersUsa(coordinates) {
var x = coordinates[0], y = coordinates[1];
point = null;
(lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y);
return point;
}
Specifically, how is (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y);
evaluated?
If you need more context, this example occurs at line 3257 of the D3 source, which can be found here: https://github.com/mbostock/d3/blob/master/d3.js
Upvotes: 1
Views: 98
Reputation: 20073
||
in JavaScript is the fallback operator. A simple example is:
var a = true || 1; // evaluates to true
var a = false || 1; // evaluates to 1
var a = 'x' || 1; // evaluates to true
If the left side evaluates to a truthy value, the result is the left side and the right side is not evaluated. You can extend it further as they did here by passing in a list of arguments in parenthesis. In this case, if each item on the left evaluates to truthy, the right side will not be evaluated. And as you can see, you can chain as many of these statements together as you like.
Upvotes: 2
Reputation: 413757
That's shorthand for
lower48point(x, y);
if (!point) {
alaskaPoint(x, y);
if (!point) {
hawaiiPoint(x, y);
}
}
The three functions must alter the value of the relatively-global variable "point". The ||
version uses comma operators to carry out two expressions and exploits the side-effects.
Personally I would not feel good about myself for writing that code.
Upvotes: 2