The usual way to check if the value of a property is the special value undefined
, is:
if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
To check if an object does not actually have such a property, and will therefore return undefined
by default when you try and access it:
if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
To check if the value associated with an identifier is the special value undefined
, or if that identifier has not been declared. Note: this method is the only way of referring to an undeclared (note: different from having a value of undefined
) identifier without an early error:
if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check foo === undefined
might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.
However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.
If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined
value itself:
if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
response[0]
is not defined, check if it is defined and then check for its property title.
if(typeof response[0] !== 'undefined' && typeof response[0].title !== 'undefined'){
//Do something
}
Best Answer
You get the error because
order[1]
isundefined
.That error message means that somewhere in your code, an attempt is being made to access a property with some name (here it's "push"), but instead of an object, the base for the reference is actually
undefined
. Thus, to find the problem, you'd look for code that refers to that property name ("push"), and see what's to the left of it. In this case, the code iswhich means that the code expects
order[1]
to be an array. It is, however, not an array; it'sundefined
, so you get the error. Why is itundefined
? Well, your code doesn't do anything to make it anything else, based on what's in your question.Now, if you just want to place
a[i]
in a particular property of the object, then there's no need to call.push()
at all: