I have three pages utilizing the same code and on one of the pages this variable doesn't exist, on the other two the variable ticketType has a value of 1 or 2. I need to first check if ticketType exists and isn't undefined and secondly, need to determine if it's one or 2.
This if statement generates an error:
if(typeof ticketType != undefined && ticketType == 1){}
It's saying ticketType isn't defined
. I tried nesting the if statements to check if it was defined first thinking it wouldn't go and try the inner if statement but firebug still generates an error.
Any ideas? There has to be a way to do this...
In JavaScript, strict equality comparison (===) Operator is used to check whether two entities are of not only equal values but also of equal type. The typeof operator returns a string which indicates the type of the unevaluated operand. Both of these operators provide a Boolean result.
Use the typeof Operator to Check if Variable Exists in JavaScript: The typeof operator checks if a variable is defined/null, but it does not throw a ReferenceError if used with an undeclared variable.
$ is simply a valid JavaScript identifier. JavaScript allows upper and lower letters, numbers, and $ and _ . The $ was intended to be used for machine-generated variables (such as $0001 ). Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function).
Method 1: Using the typeof operator The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.
'undefined'
needs to have quotes around it when used with typeof
if(typeof ticketType != 'undefined' && ticketType == 1){}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With