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)
Related
I want to check if a object is defined or not..
content of the Object:
so I'll do:
if (e.model.item.state != "undefined"){
var stateID = e.model.item.state.id;
....
}
else{
}
Then e.model.item.state is undefined but it does enter the if clause and stops here:
var stateID = e.model.item.state.id;
because of undefined..!
I tried also:
!== "undefined"
!=== "undefined"
Better use this to avoid unnecessary undefined error:-
if (e && e.model && e.model.item & e.model.item.state) {
// e.model.item.state is NOT `undefined`, `null`, `false` or `0`
}
In JS, you can check whether a variable is either undefined, null, false or 0 by just simply doing,
if (e.model.item.state) {
// e.model.item.state is NOT `undefined`, `null`, `false` or `0`
}
else {
// e.model.item.state is either `undefined`, `null`, `false` or `0`
}
"undefined" is not the same as undefined. The first one is a string with the word 'undefined' in it, the other is a reserved js term for undefined var.
Doing something == "undefined" is comparing it to a string. You should remove the quotes.
You check for undefined in one of following ways:
var a;
if( a === undefined )
OR
if( typeof a === "undefined" )
"undefined" is not equal to undefined. So, if you compare directly for equality, use it without quotes. If you are using typeof operator, you need to use quotes because typeof always returns a string value.
I got recently such legacy code:
if (typeof value != "undefined" && value.someOperation()) { }
I understand that its preventing undefined object issue, however isn't simple to do such thing:
if (value && value.someOperation()) { }
Is somewhere in deep javascript a hack or some situation that it would not work at all? There is no possible to get 0 or false instead of that object here. I wonder if I can change the first expression to the second one and I wouldn't break anything.
In this line
if (typeof value != "undefined" && value.someOperation()) { }
typeof value != "undefined" is evaluated to false if and only if value is either null or undefined. However, if the value is either 0 or false then it will evaluate to true, and hence move on to second condition value.someOperation().
There is no possible to get 0 or false instead of that object here.
If the value of value cannot be 0 or false, even then you might want to check value.someOperation before checking value.someOperation() since value.someOperation() it may give following error
TypeError: undefined is not a function
In fact, in both cases you might want to check if value.someOperation first before value.someOperation() i.e.
if (value && value.someOperation && value.someOperation()) { }
or
if (typeof value != "undefined" && value.someOperation && value.someOperation()) { }
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);
I don't recollect exactly what its called but php checks and exists as soon as it finds one false value in a function, like so :
// php
if(isset(a["hi"]) && isset(a["hi"]["hello"])) {
}
here if a["hi"] is not set, it will not bother to check the next a["hi"]["hello"].
to check something like this in javascript you'd need to nest
// js
if(typeof(a["hi"]) != "undefined") {
if(typeof(a["hi"]["hello"]) != "undefined") {
}
}
Can we do php style lazy checking in javascript?
(I may not be using the best method to check if an element exists in a multi-dimentional array, if there is a succinct way of doing this, would love to know.)
thanks!
You could use in to check property existence.
if(a && ('hi' in a) && ('hello' in a['hi'])) {
}
if(a.hi === undefined && a.hi.hello === undefined) {
if you know that a.hi can never be a falsey value (null / false / 0) you can do
if(!a.hi && !a.hi.hello) {
Checking the typeof a variable for the string "undefined" is equivalent to using === to check whether the variable is the same data type as the undefined keyword. You can therefore reduce the nested if statements to a single statement:
if(a.hi !== undefined && a.hi.hello !== undefined) {
// do something with a.hi.hello
}
It's worth noting that the statement above assumes that a is not null when the if statement takes place which could cause errors. It also holds true that if you require a.hi.hello to be present for the if statement to evaluate, then you can use falsy checking for a and a.hi as they would need to be object types for (which are non-falsy):
if(!!a && a.hi && a.hi.hello !== undefined) {
// do something with a.hi.hello
}
I have a string like this:
var TheDate = "6.14.2012";
and I have an object MyObject that has properties that may match that string. However, when I write this:
if (MyObject[TheDate] === null || MyObject[TheDate] === 'undefined') { .... }
the conditions never seem to evaluate to true even though I know the property doesn't exist.
What am I missing??
Thanks.
Existence of Own Property
If you want to check for the existence of a property use .hasownProperty()...
if (MyObject.hasOwnProperty(TheDate)) {
Existence of Own Or Inherited Property
If the property may be inherited, to test for existence use the in operator...
if (TheDate in MyObject) {
null or undefined value test for Own Or Inherited Property
If it's not existence, but rather a value test, and you want to test for null or undefined, then use this...
if (MyObject[TheDate] == null) {
This will check for both null and undefined.
The problem is with the quotes around undefined ;)
Change
if (MyObject[TheDate] === null || MyObject[TheDate] === 'undefined') { .... }
to
if (MyObject[TheDate] === null || MyObject[TheDate] === undefined) { .... }
It should work :)
If you want to use the string "undefined" rather than the undefined object, the way to do this is to check the "typeof", which returns a string. In this case, if you're looking to test if it's set to "undefined":
if ( MyObject[TheDate] === null || typeof MyObject[TheDate] === 'undefined' ) { .... }
Try the following
if ( (MyObject[TheDate] === null) || (typeof MyObject[TheDate] === 'undefined') {
....
}
You were checking whether your property contains the String 'undefined' and not whether its value is currently undefined.