-1

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 == , ===.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
zsitro
  • 1,812
  • 3
  • 24
  • 34

2 Answers2

3

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.

To check whether or not variables is there, you can simply use typeof:

if (typeof _os != 'undefined'){
  // your code
}

The typeof will also help you avoid var undefined error when checking that way.


Furthermore i also need a guide of the proper using operators like == , ===.

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:

4 == "4" // true
4 === "4" // false because types are different eg number and string

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 typeof is problematic, you should ONLY use it to check whether or not a variables is present.

Read More at MDN:

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
1

The typeof operator is very helpful here:

typeof asdf
// "undefined"

Perhaps you want something like this in your case:

// Handle cases where `fbuser.orders` is not an array:
var _os = fbuser.orders || []
davidchambers
  • 23,918
  • 16
  • 76
  • 105