Skip to content

Instantly share code, notes, and snippets.

@kimmobrunfeldt
Created March 12, 2015 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kimmobrunfeldt/76e40021365daffa9bc9 to your computer and use it in GitHub Desktop.
Save kimmobrunfeldt/76e40021365daffa9bc9 to your computer and use it in GitHub Desktop.
One reason why !! is dangerous
// _.find returns undefined if nothing is found, otherwise returns the found item.
var existsOnCurrentPeriod = _.find(currentValues.operators, function(operatorId) {
return operatorId === operator.usbKeyId;
});
operator.existsOnPeriod = !!existsOnCurrentPeriod;
// This looks correct at first glance, but see below
// The same logic with slight variable name changes
var operatorIds = [0, 1, 2, 3];
var usbKeyId = 0;
var existsOnCurrentPeriod = _.find(operatorIds, function(id) {
return id === usbKeyId;
});
var exists = !!existsOnCurrentPeriod;
console.log(exists);
> false
var operatorIds = [0, 1, 2, 3];
var usbKeyId = 0;
var existsOnCurrentPeriod = _.find(operatorIds, function(id) {
return id === usbKeyId;
});
var exists = !_.isUndefined(existsOnCurrentPeriod);
console.log(exists);
> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment