Friday, November 25, 2011

=== allows you to determine if a JavaScript variable is undefined as opposed to null

I need to find if a variable exists yet or not in JavaScript/jQuery and I found this online offering this suggested approach:

if (window.x === undefined) alert("x is undefined/undeclared");

else if (x === false) alert("x is false");

else if (x === true) alert("x is true");

else alert("x is " + x);

   

I'm going to try it out. It means I'll be losing my triple equals virginity and making a strict comparison. This offers the following bullets on what the strict comparison operators (=== and !==) do:

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
  • Two Boolean operands are strictly equal if both are true or both are false.
  • Two objects are strictly equal if they refer to the same Object.
  • Null and Undefined types are == (but not ===).

   

The last bullet really matters for what I want to do as what I want to do is:

if (window.x === undefined) alert("x is undefined/undeclared");

   

...and I do not want to match on null, only on undefined.

Why do I want to do this? I have a partial (the shuffle list control) that may be summoned numerous times over in a view. The partial has a blob of JavaScript in it declaring a variable. The last partial will sabotage all partials before it if the variable being declared is not unique so I need a means to make sure I am not using a variable I have used already.

No comments:

Post a Comment