JavaScript : Check if variable exists and if equal to value

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

if(typeof ticketType != 'undefined' && ticketType == 1){}

undefined should be within quotes...

if (typeof ticketType !== "undefined" && ticketType == 1)
{
}

EDIT

Here we are not talking about global.undefined which doesn't have to be enclosed within quotes. We are talking about the return type of typeof operator which is a string. Incidentally for undefined variable, the typeof returns "undefined" and thus we need to enclose it within string.

// ticketType is not defined yet

(typeof ticketType !== undefined) // This is true
(typeof ticketType === undefined) // This is false
(typeof ticketType !== "undefined") // This is false
(typeof ticketType === "undefined") // This is true

var ticketType = "someValue"; // ticketType is defined

(typeof ticketType !== undefined) // This is still true
(typeof ticketType === undefined) // This is still false
(typeof ticketType !== "undefined") // This is true
(typeof ticketType === "undefined") // This is false

So the correct check is against "undefined" not against global.undefined.

Tags:

Javascript