I was looking at some JavaScript recently and came across the following routine. Can anyone explain to me how it works?
function groupConsecutive(numbers, successor) {
successor || ( successor = function(n) { return n + 1; });
var groups = [];
return _.each(numbers, function(number) {
if (groups.length === 0) {
groups.push([number]);
} else {
successor.call(this, _.last(_.last(groups))) === number ? _.last(groups).push(number) : groups.push([number]);
}
}, this), groups;
}
Specifically I’m trying to understand the successor || { bit. If I use “use strict” here it throws an “Expected an assignment or function call and instead saw an expression” error, and so I believe it should because successor is never defined prior to the function being called. So to my way of thinking whenever the routine starts up, the successor function is undefined. This routine is using the underscore.js library.
The expression uses a side effect of the
||operator. As the operator uses short circuit evaluation, the second operand is only evaluated if the first evaluates to false.So, this line:
does the same thing as:
The strict mode does right in throwing an error, as the line contains an expression that is evaluated but then the result is discarded. Normally that means that you forgot to do something with the result.
You can use the
||operator in strict mode if you use this form: