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.
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.
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
}
Well your original code is flawed because if name is an empty string, false, the number 0 or any other falsy value then it will be considered null 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...
if ((!(_.isUndefined(data)) || _.isEmpty(data))) {
//Valid Data
}else {//Not Valid}
Related
First a little bit of context (you can skip this part if you prefer to focus on code).
I joined a new project that will be integrated in a nodeJS's platform. Our team does have experience with JEE enterprise Web Apps. That sets up our background. This new project will consume REST APIs, aggregate some data, implement some business logic and pass these data to front-end consumer. Sort of lightweight microservice architecture.
Some co-workers started to work on the project and I found it that in the source code we do have a lot of code snippet like if (foo != null && foo.property != null) {return foo.property.value;}
Foo being supposed to be an object passed as an argument to a function which would implement that kind of test.
A snippet example will talk more.
Let's pretend that's the response of an API i am consuming. I want to write a small function which would return statusValue if the object does exist, if it's not null or undefined, not empty and the property does exist and isn't blank or empty for instance.
var response = {
"services":[],
"metadata": {
"status": "statusValue"
}
};
That's how it is as for now :
function getStatusValue(response) {
if (response != null && response.metadata != null) {
return response.metadata.status;
}
};
What would be considered as a best JS practise to implement that (we are also using lodash so maybe it's a better option to use lodash internals for that). I am just fearing we are transposing our Java habbits.
Basically i would like to know how to check for null, undefined, empty, blank safely (if that makes sense). What would be the JS best practice for that in 2016 with libraries such as lodash and stuff.
When checking for properties of an object, checking for loose equality to null is not enough.
Loose equality (==) employs type hinting in JavaScript, which attempts converting the members to a common type that can then be used for determining whether they are equal or not.
As such, best practices for JavaScript dictate that strict equality (===) is always to be used, in order to avoid edge-case scenarios or unknown behavior when checking for values or types.
You can find more info about loose vs strict equality here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Equality_comparisons_and_sameness
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
While this is not a must-have in your function, it is a good practice to follow and develop as a habit, so that on later code the implications of loose equality (==) could be avoided (e.g. avoiding '3' == 3, when a number or string type is expected).
Although considered a downside of the language by some, using null is similar in intent as checking for undefined, but is actually meant to express in the code that the coder is expecting an object (or lack of) to be provided, instead of a primitive type (number, string, boolean, function). This differs from Java, or any other typed language, where null is used for Object type defined variables; but in JavaScript there's no constraining a variable to given type.
You can find out more details about null at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
In practice, and especially when dealing with values that come outside of a unit - which is the case of any API - is considered a best practice to actually check for the type being an object, in order to make sure it has properties.
While your code is not incorrect, it does show that there's not much attention to best practices, which eventually will lead to writing buggy code.
My suggestion for your code, following best practices and independent of any library, is:
function getStatusValue(response) {
// must be of type `object`, to have properties.
if (typeof response === 'object' &&
// any variable of type `object` might be `null`, so exclude that.
response !== null &&
// `metadata` property must be of type `object`, to have properties.
typeof response.metadata !== 'object' &&
// `metadata` is of type `object`, check for not being `null`.
response.metadata !== null) {
// `status` property is expected to be a string, given by the API spec
if (typeof response.metadata.status === 'string' &&
// on strings, we can access the `length` property to check if empty string (0 chars).
response.metadata.status.length > 0) {
// all good, return `status` property.
return response.metadata.status;
} else {
// `status` property is either not a string, or an empty string ('').
}
} else {
// invalid `response` object.
}
}
Also, it might be easier to create or use from any libraries you integrate, a function to check for a valid object; something like _.isObject or this:
function isObject(o) {
return (typeof o === 'object' && o !== null);
}
which you could later be used in the above snipped like so:
function getStatusValue(response) {
if (isObject(response) && isObject(response.metadata)) {
if (typeof response.metadata.status === 'string' &&
response.metadata.status.length > 0) {
return response.metadata.status;
} else {
// `status` property is either not a string, or an empty string ('').
}
} else {
// invalid `response` object.
}
}
As a final thought, as it is clearly visible, following best practices does increase the size of your code, but the benefit is that the resulting code is much safer, with less chances of throwing exceptions (root of many app crashes), easier to collaborate on, and easier to build tests/coverage for.
Using Lodash, you can use the _.isNil(response) function documented here.
In general, I would check a variable like this:
if (typeof x !== 'undefined' && x !== null) {
// x has some value
}
You should not check whether x === undefined because if x is undefined, you'll get a dereference error.
I would implement this using the following function:
var response = {
"services":[],
"metadata": {
"status": "statusValue"
}
};
function getStatusValue(res) {
if (res && res.metadata)
return res.metadata.status || 'not found';
else
return 'not found';
}
console.log(getStatusValue(response));
The if statement will return false if res or res.metadata are undefined and if they both exist, it will return res.metadata.status only if it's defined or 0, otherwise it'll return 'not found'.
Here is a (more concise) way to do such a thing with just JS:
var obj = ...;
var val = obj && obj.prop && obj.prop.val;
val will be undefined/null if either obj or obj.prop are; otherwise it will be obj.prop.val.
This works because of the short-circuit evaluation of &&. It's literal behavior is this: if the first operand is falsey, it evaluates to the first operand. Otherwise, it evaluates to the second. This works as expected for booleans, but as you can see, it can be useful with objects.
|| has similar behavior. For example, you can use it to get a value, or a default if the value is falsey (e.g. null):
var val2 = val || "not found";
Note that this would evaluate to "not found" if val is anything falsey, including 0 or "".
In JavaScript code I want to replace the double-equals structure of the following if-statement:
if( name == null ) {
//do stuff
}
The double equals fail for the jshint rule "eqeqeq", where it's recommended to replace double equals with triple equals. For a moment, let's imagine the above code changed from == null to === null like this:
if( name === null ) {
//do stuff
}
This would work for a variable explicitly defined having the value null, but unfortunately would fail for any unset variables like this.
var a = null; // works correctly
var b; // will fail in comparison
Previously when the triple-equals rule was important to me I would do the following
if( name === null ||| typeof(name) === 'undefined' )
but I find this extremely bloated.
The best alternative I can come up with now is to use the nature of the if-statement and let it evaluate to a false-ish expression like here where I negate the expression and simply remove the == null part:
if( !name ) {
//do stuff
}
For me, this is much simpler, easy to read, and completely avoids explicit equals comparison. However, I am uncertain if there are any edge causes I am missing out here?
So the question is, can I generally replace == null with the negated expression if statements? If so, what are the pitfalls and exceptions where it wouldn't work? Does it work for general array items, strings, object properties?
My criteria for picking a solution will be
clean code
easy to read and quickly understand
validates jshint rules
works in modern browsers (as of writing January 2015)
I am aware of other slightly related questions for discussing difference in the equality operators == vs ===, but this is merely for a discussion of the evaluation compared to null-ish inside the if-statement.
So the question is, can I generally replace == null with the negated expression if statements?
Probably not universally, no, but perhaps in some places.
If so, what are the pitfalls and exceptions where it wouldn't work? Does it work for general array items, strings, object properties?
The !value check will be true for all of the falsey values, not just null and undefined. The full list is: null, undefined, 0, "", NaN, and of course, false.
So if you have name = "" then
if (!name) {
// ...
}
...will evaluate true and go into the block, where your previous
if (name == null) {
// ...
}
...would not. So just doing it everywhere is likely to introduce problems.
But for situations where you know that you do want to branch on any falsey value, the !value thing is very handy. For instance, if a variable is meant to be undefined (or null) or an object reference, I'll use if (!obj) to test that, because any falsey value is good enough for me there.
If you want to keep using JSHint's === rule, you could give yourself a utility function:
function isNullish(value) {
return value === null || typeof value === "undefined";
}
The overhead of a function call is nothing to be remotely worried about (more), and any decent JavaScript engine will inline it anyway if it's in a hotspot.
Hey anyone out there that uses JavaScript in a professional environment. I wanted to know the standard when comparing values using == and === operators. I was watching a video the explained that if you compared a sting with a value of '5' and an int with a value of 5 it returns true using the == operator. They then suggested to use the === for everything. I know this is wrong because what if you wanted to compare some value nested in some polymorphic objects with different type defs say one being a student and the other being an instructor the === would always return false.
After much thought I came to the conclusion that it might be best to use === whenever possible and the == when only necessary.
Can you give me some insight on what the rule of thumb is in a professional environment?
The rule is simple:
Always use === and !== unless you explicitly WANT a type conversion to be allowed and have thought through the consequences of that type conversion. In otherwords, you should be using === and !== nearly all the time.
Your exception for polymorphic objects does not apply because == and === both require two objects to be the exact same object when comparing two objects. There are no type conversions in that case. If you were comparing two properties of polymorphic objects, then only the type of the property is looked at, not the type of the containing object.
For detailed rules on type conversions with ==, see this http://es5.github.com/#x11.9.3. There are some odd ones like this:
var x; // x is undefined
alert(x == null); // alerts true
Check out http://jshint.com which helps enforce these best practices. They (and everyone else pretty much) recommend using ===.
I can rarely think of a reason to use == over ===.
Here's a fancy example of using === even when == might feel easier.
var person = {
name: "Cody",
age: "44"
}
var targetAge = 40;
// explicit type conversion, no wonder what's happening
if (parseInt(person.age, 10) === targetAge) {
alert("You won!")
} else {
alert("Sorry You Lost!");
}
See Also: JavaScript: The Good Parts and Maintainable JavaScript, which also recommend the practice.
it's commonly used in this type of statements:
var x = 0;
if(x == false) {
// this will be executed
}
if(x === false) {
// this not
}
if(false == '') {
// this will be executed
}
if(false === '') {
// this not
}
another example - function which is returning FALSE on error or string on success
function foo(bar) {
// magic
return ''; // this is SUCCESS
}
var result = foo(123);
if(result === false) {
// omg error!!
}else{
// some string returned, event empty one is OK
}
to be honest it's really rare to use === in statements
In PHP you could write this:
if(false !== ($value = someFunctionCall())) {
// use $value
}
How would you write an equivalent of this in JavaScript without defining
var value;
before this comparison?
You'd write
if (value = someFunction()) {
I don't trust my knowledge of PHP that heavily, but I suspect that explicit comparisons to false in if statements aren't necessary, as the expression is implicitly boolean. (edit — sometimes, if a function can return either an explicit boolean or some "good" value that evaluates to "falsy", then yes you do need the explicit comparison to boolean.)
edit — if you're squeamish about the ages-old confusion (or potential thereof) between = and ==, then I'd advise avoiding the construct entirely. There's nothing wrong with it, other than the fact that sometimes you want an equality comparison and sometimes you want an assignment.
edit oh also this presumes that "value" has been declared with var somewhere — if the question is about how you do the declaration in the context of an if statement, then the answer is that you cannot do that.
final edit I kind-of promise — to sum it up:
Assuming that "value" is declared:
var value;
somewhere, then:
if (false !== (value = someFunction())) { ... }
has pretty much the same semantics as the PHP original.
You can just have it assign when it's executed and JavaScript will automatically add the var declaration:
function foo(){
return (Math.random() * 0.5) > 0;
}
if (false !== (f = foo())){
alert('True!');
}
alert('f=' + f.toString());
jsFiddle Example
However, this is very bad practice. You should always declare your variables when and where you need them first. Just because PHP and JS accept this syntax doesn't mean it's good practice. The proper style would be as follows:
var f = false;
if (false !== (f = foo())){
alert('True!');
}
alert('f=' + f.toString());
That would be very bad practice in JavaScript,
You would be best to do
if(!(var value = someFunctionCall())) { // use value //}
Personally i would say define it before. Your call though. If you worried about memory then define it and null it after use.
Does jQuery provide a way to to that test in a more concise way?
Update
I should have left jQuery out of this. It is just an issue of JavaScript. It's been so long for me! I am testing to see is something externally-defined module was loaded or not. It appears that I can just use this instead:
if (window.someVar)
Please correct me if this is a bad practice. In my case, if someVar is defined, it will be an object. It will not be defined to false.
This answer must be at least 30 characters and the answer is: No.
If it is acceptable in your code to consider null and undefined to be equal, you could avoid the typeof by doing an == test on null, which will also be true for undefined.
if( someVar == null ) {
// it was either null or undefined
}
(function(params, undefined) {
// ...
if (someVar === undefined) {
...
}
...
window.SomethingGlobal = SomethingGlobal;
}(params));
You can set declare undefined as a variable in your function. If that paramater is not passed in then you can garantuee it has the value of undefined.
It is always best to use closures like this to create a unique scope. If you need to hoist anything to global scope set it on the window manually.
Alternatively this will work:
if (someVar = void 0) {
...
}
void is a funny command. It expects an expression, It runs the expression and always returns undefined rather then the return value of the expression.
There's no real way to make that more concise. Since that code tests if the variable someVar is declared, the only safe use of the name someVar is as the operand to typeof (all other uses will raise an error if the variable is not declared).
I guess you could make the rest of the expression somewhat shorter by using a function:
function isUndefined(type)
{
return type === 'undefined';
}
if (isUndefined(typeof someVar)) {
// ...
}
But that's probably not worth the trouble.
As long as the 'big varity' of typeof includes such 'genius'*ionically* thing like object you may consider about this cheat:
typeof someVar >= 'u'ndefine
that will quicken stringcompare but decreases readability and cleanness of your code.
However short is beautify and maybe it's good to remind by that there is such a thing like the >=and =<-operator for strings that is often forgotten and so not used. ;)