JavaScript : Check if variable exists and if equal to value - 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...

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

Wrap it in parenthesis.
if (typeof(ticketType) !== 'undefined' && ticketType === 1)

The error message is pretty clear. Try with this:
var ticketType;
if(typeof ticketType != undefined && ticketType == 1){}
You cannot just reference a variable that does not exist. You can only do this when assigning:
ticketType = 1;
The browser complaints because ticketType is an unknown identifier. However if we first declare it (even without assigning it any value) it becomes known but with undefined value.

if(typeof ticketType != 'undefined' && ticketType == 1){}
I think you need the quotes around the undefined word. At least I always do it that way.

you're incorrectly checking for an undefined variable, but if you're planning on using it, why not just make sure that it gets defined?
ticketType = ticketType || 1;
if (ticketType === 1) {
//do stuff
}
As everyone else has shown, the standard way of checking for undefined values in JS is:
typeof somevar === 'undefined'

The correct syntax is:
if (typeof ticketType !== 'undefined' && ticketType === 1) { }
The result of the typeof operator is always a string. See here: http://www.javascriptkit.com/javatutors/determinevar2.shtml

simlpe using console.log(someVar);

Related

If (myVar != "undefined")

I wanted to check whether an item in localWebstorage was not yet given a value. I tried doing this by:
//Change localStorage.intervalSetting from 'Undefined' to 'Never'
function initialIntervalSetting() {
var getValue = localStorage.intervalSetting;
if (typeof getValue === undefined) {
localStorage.intervalSetting = "option1";
alert("Changed the localWebstorage item from undefined to "option1");
}
else {
alert("JavaScript thinks that the item is not undefined");
}
}
This does not work, HOWEVER.. The question was asked here:
How to check for "undefined" in JavaScript? and someone answered:
if (typeof getValue != "undefined") {
localStorage.intervalSetting = "option1";
}
They suggested replacing === with !=
For some reason, this works- How???
Shouldn't (getValue != "undefined") return false because != means NOT EQUAL??
In your code you compared typeof getValue with the literal type undefined. Since typeof actually gives you a string, you should compare this value to the string "undefined".
Either
if (typeof getValue !== "undefined")
Or
if (getValue !== undefined)
will do the trick.
I recommend using a "truthy" check. This will check if the object is null or undefined. You can do this by just checking your getValue.
if(getValue) {
// not undefined
}
Another SO post for reference: Understanding JavaScript Truthy and Falsy

How to easily check if undefined in javascript object?

Assuming I have a javascript object "myobject" that just contains an empty object "{}".
I ideally in my code I want to do the following:
if (theobject[keyvar][subkeyvar]) {
// do something
}
The issue now is that because keyvar and subkeyvar do not actually exist within the object, it fails and comains that the properties are undefined. What is the simplest/least lines of code/best way to be able to do have it just "know it is undefined" and continue to execute the //do something or not without crashing?
I dont want to get too carried away with checking like:
if( keyvar in theobject ) {
if(subkeyvar in theobject) {
if.....
}
}
if (typeof theobject[keyvar] !== "undefined" && typeof theobject[keyvar][subkeyvar] !== "undefined") {
// keyvar and subkeyvar defined
}
first we check if keyvar typeof is undefined and then if subkeyvar is undefined and if they are both defined typeof theobject[keyvar] !== "undefined" && typeof theobject[keyvar][subkeyvar] !== "undefined" is true.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
you can try this :
if (theobject[keyvar] && theobject[keyvar][subkeyvar]) {
// do something
}
If they both can possibly be undefined, you have to test one, then the other.
if (theobject[keyvar] && theobject[keyvar][subkeyvar]) {
This will of course fail on a key containing 0 or "" (or several other falsey but not undefined values) so you may want to use typeof on the second test.
Try:
if (theobject[keyvar] !== undefined && theobject[keyvar][subkeyvar] !== undefined) {
// do something
}
Since the && operator is used, the if will not check the second value if the first value is falsey, so you will never get the 'properties are undefined` error
theObject.hasOwnProperty(keyvar) && theObject.hasOwnProperty[keyvar].hasOwnProperty(subkeyvar)

Coffeescript and variable check

I have the following code:
if variablename?
alert "YES!"
l = []
if l[3]?
alert "YES!"
It's translated into this:
var l;
if (typeof variablename !== "undefined" && variablename !== null) {
alert("YESSS!");
}
l = [];
if (l[3] != null) {
alert("YESSS!");
}
In Coffeescript, how would I express l[3] !== "undefined" ?
Just add typeof operator, like this:
if typeof l[3] != 'undefined'
alert 'Yes!'
Beware that l[3] !== "undefined" is asking whether l[3] is different from the string that says "undefined", not if its value isn't undefined. The comparison that CoffeeScript generates for l[3]? -> l[3] != null will verify when l[3] is some value different from undefined or null, which is what you want to ask most of the time :)

comparing against undefined

Is it unsafe to compare a variable against undefined?
if(foo == undefined)
vs
if(foo == 'undefined')
Is the first example sufficient? Or should it be something like
if('undefined' in window){
//compare against undefined
} else {
//compare against 'undefined'
}
since undefined exists on the window object? Will it exist in all browsers? Or should I simply compare to == 'undefined'? I've found some similar questions on SO, but no answers regarding the existance of the undefined property on the window object.
I think you're getting mixed up between foo == undefined and typeof foo == "undefined".
Both will yield the same result unless the variable undefined has been set to something else in the current scope. In this case, foo == undefined will compare against that, where-as typeof foo == "undefined" will still resolve correctly.
var undefined = 4;
var reallyUndefined;
reallyUndefined == undefined; // false
typeof reallyUndefined == undefined; // true
Whether it's a real world scenario that undefined will ever be set to something else is debatable, and I'd question the validity of the library/ code that does that... Because of this however, it's deemed good practise to always use typeof foo === "undefined".
I'd also be wary about using foo == undefined against foo === undefined (note the triple equals, which does not use type-coercian, compared to == which does).
Using ==, you run the risk of things like null == undefined; // true, where-as null === undefined; // false. This is a good example of why you should always use ===.
tl;dr: typeof foo === "undefined";
I'd suggest you to use typeof instead:
if (typeof foo == "undefined") {
// ...
}
Note, that typeof returns a string, so you should always compare it with string value.
if (foo === undefined)
Is safe
There are several ways to do this, but the easiest I've found is this:
if(foo === undefined){
//do stuff
}
If you have complete control of all the code and you know you won't have to worry about someone mucking about with undefined then it is safe to compare against it.
alert(window.foo === undefined);
On the other hand, if you want to be a bit more paranoid, you can do a typeof check which can't be affect by the outside word
alert(typeof window.foo == 'undefined')
The third option is to have your own, local, undefined variable.
function testme(a, undefined) {
alert(a === undefined); // Will be false.
}
testme(10);

Checking undefined value not working?

I have the following javascript code:
var currentIds = localStorage.getItem('currentPairsIds');
if ((typeof currentIds === "undefined") ||
(currentIds == null))
$.myNameSpace.currentIDs = new Array(3);
else
$.myNameSpace.currentIDs = currentIds.Split(',');
I'm debugging with Firebug and although currentIds hasn't got any value it always executes else statement.
UPDATE: I'm getting this value from HTML5 storage.
What am I doing wrong?
This is how I have solved my problem:
var currentIds = localStorage.getItem('currentPairsIds');
if ((currentIds === undefined) ||
(currentIds == null) || (currentIds == "undefined"))
$.myNameSpace.currentIDs = new Array(3);
else
$.myNameSpace.currentIDs = currentIds.split(',');
localStorage.getItem('currentPairsIds'); returns the string "undefined".
There is another error in Split() function. The right version is without any capital letter.
I would use a direct comparison instead of the notoriously odd "typeof" operator:
if ((currentIds === undefined) || (currentIds === null)) {
//...
It's not working because localStorage.getItem returns null if the item is not defined, it does not return undefined http://dev.w3.org/html5/webstorage/#dom-storage-getitem
Example: http://jsfiddle.net/mendesjuan/Rsu8N/1/
var notStored = localStorage.getItem('ffff');
alert(notStored); // null
alert(typeof notStored); // object, yes, null is an object.
Therefore you should just be testing
alert(notStored === null);
I think you have to make checking for undefined comparing with == instead of ===.
Example:
typeof currentIds == "undefined"
This will make sure, the variable is really undefined or not.
[Edit Edit Edit Edit :P]
currentIds = "undefined"
implies
typeof currentIds == "String"
Also see, Detecting Undefined, === isn't necessary for string comparison.
In my case LocalStorage.getItem() was converting it to "undefined" as string.
I also needed to check if it s "undefined" as a string.
var myItem = LocalStorage.getItem('myItem');
if(myItem != "undefined" && myItem != undefined && myItem != null){
...
}
if( typeof(varName) != "undefined" && varName !== null )
be sure, you use ( " " ) quotes when checking with typeof()

Categories

Resources