How to check if javascript variable exist, empty, array, (array but empty), undefined, object and so on
As mentioned in the title, I need a general overview how to check javascript variables in several cases without returning any error causing the browser to stop processing the pageload.
(now I have several issues in this topic.
For example IE stops with error in case _os is undefined, other browsers doesnt:
var _os = fbuser.orders;
var o =0;
var _ret = false;
for (var i = 0; i < _os.length; i++){
...
Furthermore i also need a guide of the proper using operators like == , ===.
To check whether or not variables is there, you can simply use
typeof:The
typeofwill also help you avoidvar undefinederror when checking that way.Both are equality operators. First one does loose comparison to check for values while latter not only checks value but also type of operands being compared.
Here is an example:
With
==javascript does type cohersion automatically. When you are sure about type and value of both operands, always use strict equality operator eg===.Generally, using
typeofis problematic, you should ONLY use it to check whether or not a variables is present.Read More at MDN: