There are two ways I can check to see if a variable or property exists.
The first asserts that no falsy values are returned.
1.
var testVar;
if(!testVar){
//use testVar becuase it exists
}
The second asserts the two conditions explicitly.
2.
var testVar;
if(testVar !== undefined && testVar !== null){
//use testVar becuase it exists
}
With the goal of checking if the object/string/number/array exists, is there any difference between the two ?
They are different. If you try to put
… into
{}or1ortrueor"nyan cat"testVar, then it returnsfalsefor!testVar:A better way to check if a variable exist:
PS
This actually does not check if it exists. Try