1

In my opinion Javascript has quite a few weird quirks. Here is one of them

var a;
!a //true, a is not set
a = null
!a //true, a is not set
a = 1
!a //false, a is set!
a = 0
!a//true, a is not set!

All of these values i find to be quite reasonable, except for the case where a = 0, this is just plain wrong to me. Is there any reasonable way of circumventing this issue without having to add to bulk to my code?

netbrain
  • 9,194
  • 6
  • 42
  • 68
  • 1
    [`undefined`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/undefined) ? – Touki Apr 16 '13 at 06:46

2 Answers2

1

check it using typeof

if(typeof(a) != "undefined") {
     //code goes here
}

Here are some related questions.

How can I check whether a variable is defined in JavaScript?

Test if a variable is defined in javascript?

Community
  • 1
  • 1
Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101
0
if (typeof a !="undefined")
{
 //write your code here
}
Vijendra Singh
  • 628
  • 3
  • 13