var name = "someName";
if(name !=null) {
// do something
}
- I am right now using http://underscorejs.org/#isNull, how would i do
the same using
underscore.js
- Does it give any slight improvement in terms of performance for such functions.
var name = "someName";
if(name !=null) {
// do something
}
underscore.js
Well your original code is flawed because if
name
is an empty string,false
, the number0
or any other falsy value then it will be considerednull
as far as your test is concerned.As a general rule, calling ANY function is an overhead that should be avoided if possible. In this case, calling a function just to test if a value is null, when you could very easily just write
if( name === null)
, is just stupid, IMO...In underscore, you can use
and in plain Javascript, you should use
You should avoid the loose inequality operator
!=
because it does type coercion andundefined != null
will returnfalse
.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.
In underscore.js you must write this to achieve that functionality.
In underscore.js function
isNull
is written like thisSo 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.