How do I check if an object property in JavaScript is undefined?
How do I check if an object property in JavaScript is undefined?
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 to 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:
if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
Note: this last method is the only way to refer to an undeclared identifier without an early error, which is different from having a value of undefined.
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`");
}
In JavaScript there is null and there is undefined. They have different meanings.
Marijn Haverbeke states, in his free, online book "Eloquent JavaScript" (emphasis mine):
There is also a similar value, null, whose meaning is 'this value is defined, but it does not have a value'. The difference in meaning between undefined and null is mostly academic, and usually not very interesting. In practical programs, it is often necessary to check whether something 'has a value'. In these cases, the expression something == undefined may be used, because, even though they are not exactly the same value, null == undefined will produce true.
So, I guess the best way to check if something was undefined would be:
if (something == undefined)
Object properties should work the same way.
var person = {
name: "John",
age: 28,
sex: "male"
};
alert(person.name); // "John"
alert(person.fakeVariable); // undefined
ECMAScript 10 introduced a new feature - optional chaining which you can use to use a property of an object only when an object is defined like this:
const userPhone = user?.contactDetails?.phone;
It will reference to the phone property only when user and contactDetails are defined.
Ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
The solution is incorrect. In JavaScript,
null == undefined
will return true, because they both are "casted" to a boolean and are false. The correct way would be to check
if (something === undefined)
which is the identity operator...
I provide three ways here for those who expect weird answers:
function isUndefined1(val) {
try {
val.a;
} catch (e) {
return /undefined/.test(e.message);
}
return false;
}
function isUndefined2(val) {
return !val && val+'' === 'undefined';
}
function isUndefined3(val) {
const defaultVal = {};
return ((input = defaultVal) => input === defaultVal)(val);
}
function test(func){
console.group(`test start :`+func.name);
console.log(func(undefined));
console.log(func(null));
console.log(func(1));
console.log(func("1"));
console.log(func(0));
console.log(func({}));
console.log(func(function () { }));
console.groupEnd();
}
test(isUndefined1);
test(isUndefined2);
test(isUndefined3);
Try to get a property of the input value, and check the error message if it exists. If the input value is undefined, the error message would be Uncaught TypeError: Cannot read property 'b' of undefined.
Convert the input value to a string to compare with "undefined" and ensure it's a negative value.
In JavaScript, an optional parameter works when the input value is exactly undefined.
There is a very easy and simple way.
You can use optional chaining:
x = {prop:{name:"sajad"}}
console.log(x.prop?.name) // Output is: "sajad"
console.log(x.prop?.lastName) // Output is: undefined
or
if(x.prop?.lastName) // The result of this 'if' statement is false and is not throwing an error
You can use optional chaining even for functions or arrays.
As of mid-2020 this is not universally implemented. Check the documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
In recent JavaScript release there is new chaining operator introduced, which is most probably best way to check if property exists else it will give you undefined
see example below
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined
console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined
We can replace this old syntax
if (response && response.data && response.data.someData && response.data.someData.someMoreData) {}
with this neater syntax
if( response?.data?.someData?.someMoreData) {}
This syntax is not supported in IE, Opera, safari & samsund android
for more detail you can check this URL
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
A simple way to check if a key exists is to use in:
if (key in obj) {
// Do something
} else {
// Create key
}
const obj = {
0: 'abc',
1: 'def'
}
const hasZero = 0 in obj
console.log(hasZero) // true
We at ES6 can with !! Convert all values to Boolean.
Using this, all falsy values become false.
First solution
if (!(!!variable)) {
// Code
}
Second solution
if (!variable) {
// Code
}
Introduced in ECMAScript 6, we can now deal with undefined in a new way using Proxies. It can be used to set a default value to any properties which doesn't exist so that we don't have to check each time whether it actually exists.
var handler = {
get: function(target, name) {
return name in target ? target[name] : 'N/A';
}
};
var p = new Proxy({}, handler);
p.name = 'Kevin';
console.log('Name: ' +p.name, ', Age: '+p.age, ', Gender: '+p.gender)
Will output the below text without getting any undefined.
Name: Kevin , Age: N/A , Gender: N/A
Version for the use of dynamic variables Did you know?
var boo ='lala';
function check(){
if(this['foo']){
console.log('foo is here');}
else{
console.log('have no foo');
}
if(this['boo']){
console.log('boo is here');}
else{
console.log('have no boo');
}
}
check();
I found this article, 7 Tips to Handle undefined in JavaScript, which is showing really interesting things about undefined
like:
The existence of undefined is a consequence of JavaScript’s permissive nature that allows the usage of:
In JavaScript, there are truthy and falsy expressions. If you want to check if the property is undefined or not, there is a straight way of using an if condition as given,
if(!ob.someProp){
console.log('someProp is falsy')
}
However, there are several more approaches to check the object has property or not, but it seems long to me. Here are those.
=== undefined check in if conditionif(ob.someProp === undefined){
console.log('someProp is undefined')
}
typeoftypeof acts as a combined check for the value undefined and for whether a variable exists.
if(typeof ob.someProp === 'undefined'){
console.log('someProp is undefined')
}
hasOwnProperty methodThe JavaScript object has built in the hasOwnProperty function in the object prototype.
if(!ob.hasOwnProperty('someProp')){
console.log('someProp is undefined')
}
Not going in deep, but the 1st way looks shortened and good to me. Here are the details on truthy/falsy values in JavaScript and undefined is the falsy value listed in there. So the if condition behaves normally without any glitch. Apart from the undefined, values NaN, false (Obviously), '' (empty string) and number 0 are also the falsy values.
Warning: Make sure the property value does not contain any falsy value, otherwise the
ifcondition will return false. For such a case, you can use thehasOwnPropertymethod
A lot of the given answers give a wrong result because they do not distinguish between the case when an object property does not exist and the case when a property has value undefined. Here is proof for most popular solutions:
let obj = {
a: 666,
u: undefined // The 'u' property has value 'undefined'
// The 'x' property does not exist
}
console.log('>>> good results:');
console.log('A', "u" in obj, "x" in obj);
console.log('B', obj.hasOwnProperty("u"), obj.hasOwnProperty("x"));
console.log('\n>>> bad results:');
console.log('C', obj.u === undefined, obj.x === undefined);
console.log('D', obj.u == undefined, obj.x == undefined);
console.log('E', obj["u"] === undefined, obj["x"] === undefined);
console.log('F', obj["u"] == undefined, obj["x"] == undefined);
console.log('G', !obj.u, !obj.x);
console.log('H', typeof obj.u === 'undefined', typeof obj.x === 'undefined');
handle undefined
function isUndefined(variable,defaultvalue=''){
if (variable == undefined ) return defaultvalue;
return variable;
}
var obj={
und:undefined,
notundefined:'hi i am not undefined'
}
function isUndefined(variable,defaultvalue=''){
if (variable == undefined )
{
return defaultvalue;
}
return variable
}
console.log(isUndefined(obj.und,'i am print'))
console.log(isUndefined(obj.notundefined,'i am print'))
if (somevariable == undefined) {
alert('the variable is not defined!');
}
You can also make it into a function, as shown here:
function isset(varname){
return(typeof(window[varname]) != 'undefined');
}