Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using underscore.js for null checking

var name = "someName";
if(name !=null) {
   // do something
}
  1. I am right now using http://underscorejs.org/#isNull, how would i do the same using underscore.js
  2. Does it give any slight improvement in terms of performance for such functions.
like image 882
John Cooper Avatar asked May 25 '12 08:05

John Cooper


2 Answers

In underscore, you can use

if(!_.isNull(name)) {}

and in plain Javascript, you should use

if(name !== null) {}

You should avoid the loose inequality operator != because it does type coercion and undefined != null will return false.

Using plain Javascript is slightly faster because it doesn't have to invoke a function, but it will be imperceptible and it should hardly be a consideration.

I don't have a strong preference either way as far as readability goes, but it seems a little excessive and verbose to call a library function for such a simple check.

like image 116
Peter Olson Avatar answered Sep 24 '22 17:09

Peter Olson


In underscore.js you must write this to achieve that functionality.

var name = "someName";
if(!(_.isNull(name ))) {
   // do something
}

In underscore.js function isNull is written like this

_.isNull = function(obj) {
    return obj === null;
  };

So the difference is using == in your code and === in underscore.js.For more details about that difference you can look in this question.

Which equals operator (== vs ===) should be used in JavaScript comparisons?

P.S. I will suggest to write your own condition instead of using any library in such simple place.

var name = "someName";
if(name !== null)) {
   // do something
}
like image 22
Chuck Norris Avatar answered Sep 22 '22 17:09

Chuck Norris