Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript : Check if variable exists and if equal to value

Tags:

javascript

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

like image 522
hokeyplyr48 Avatar asked Nov 17 '11 21:11

hokeyplyr48


People also ask

How do you check if a variable is equal to a value in JavaScript?

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.

How do you check if a variable already exists JavaScript?

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.

What is '$' in JavaScript?

$ 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).

How do you check object is exists or not in JavaScript?

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”.


1 Answers

'undefined' needs to have quotes around it when used with typeof

if(typeof ticketType != 'undefined' && ticketType == 1){}
like image 166
locrizak Avatar answered Nov 10 '22 03:11

locrizak