Detecting an undefined object property
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`");
}
How to check if all properties in object are undefined
Object.values(filters).every(el => el === undefined)
You are actually looking for the objects values, not its keys.
How can i check if an object is undefined (javascript)?
You must check for each potentially defined property before using it:
function checkUnexistingObject(myUnexistingObject) {
if (myUnexistingObject !== undefined) {
if (myUnexistingObject.otherObject !== undefined) {
console.log("All is well");
}
}
}
checkUnexistingObject({});
checkUnexistingObject({otherObject: "hey"});
Undefined property on an object
Your issue comes from dataObj
being potentially undefined. In this case, you can use optional chaining + null coalescing operator:
let limit = dataObj?.pageLimit ?? 1000;
Getting undefined for object properties and unable to get count
user
is the key, not the value. Furthermore, you need to increment the count
each time the online property is true.
for (let user in usersObj) {
console.log(usersObj[user]);
console.log(userObjs[user].online);
if(userObjs[user].online)
++count;
}
Live Example:
function countOnline(usersObj) {
let count = 0;
for (let user in usersObj) {
console.log(usersObj[user]);
console.log(usersObj[user].online);
if(usersObj[user].online) ++count;
}
return count;
}
const users = {
Alan: {
online: false
},
Jeff: {
online: true
},
Sarah: {
online: false
}
}
console.log(countOnline(users));
Typescript: Object property returns undefined
Solved. I realised that userData
is getting result from MySQL query using the "mysql2": "^2.3.3"
package and the result is a RowDataPacket
object.
This way, I can access the userData
values by index.
For example:
console.log(userData[0].email); //returns the actual value
property value cannot be undefined in javascript
You're right that you can assign the value undefined
to a property, and even define a literal with the undefined
property; however, the resulting object is very easily confused with the similar object written without that property.
For example, in Node:
> x = {a: 1, b: undefined}
{ a: 1, b: undefined }
> y = {a: 1}
{ a: 1 }
> x.a
1
> y.a
1
> x.b
undefined
> y.b
undefined
> Object.keys(x)
[ 'a', 'b' ]
> Object.keys(y)
[ 'a' ]
> JSON.stringify(x)
'{"a":1}'
> JSON.stringify(y)
'{"a":1}'
It appears the author is saying that if you want to write good, responsible code, you should not use undefined
as a property value, because you could asking for confusion.
But semantically, that undefined
is really there, so if you interpret what the author is saying literally, it's technically incorrect. But if you follow best practices, I can see what he's trying to get across. It's very Crockford-esque.
By the way, the right way to remove properties is with delete
but that's perhaps for a different question.
ADDENDUM
In response to a question in the comments from @prsvr, I looked up the old ECMAScript 3 Specification and found the following:
ECMAScript is object-based: basic language and host facilities are provided by objects, and an ECMAScript program is a cluster of communicating objects. An ECMAScript object is an unordered collection of properties each with zero or more attributes that determine how each property can be used—for example, when the ReadOnly attribute for a property is set to true, any attempt by executed ECMAScript code to change the value of the property has no effect. Properties are containers that hold other objects, primitive values, or methods. A ECMAScript Language primitive value is a member of one of the following built-in types: Undefined, Null, Boolean, Number, and String; an object is a member of one of the following built-in types: Undefined, Null, Boolean, Number, and String; an object is a member of the remaining built-in type Object; and a method is a function associated with an object via a property.
There is no mention of undefined
being disallowed as property values in the spec. (https://www-archive.mozilla.org/js/language/E262-3.pdf).
There were changes to undefined during the evolution of JavaScript; for example you used to be able to reassign the value of the identifier undefined
to some value other than undefined, hence the idiom typeof(x) === "undefined"
(among others).
Related Topics
Preview an Image Before It Is Uploaded
How to Interpolate Variables in Strings in JavaScript, Without Concatenation
Usage of the Backtick Character (') in JavaScript
How to Check That a Number Is Nan in JavaScript
How to Use JavaScript Variables in Jquery Selectors
Reactjs Component Names Must Begin With Capital Letters
Best Way to Manage Chat Channels in Firebase
Can You Bind 'This' in an Arrow Function
Programmatically Navigate Using React-Router
Download a File by Jquery.Ajax
How to Access the Matched Groups in a JavaScript Regular Expression
When Should I Use a Return Statement in Es6 Arrow Functions
Is It Safe to Expose Firebase APIkey to the Public
Web-Scraping JavaScript Page With Python
Recursive Function Returns Undefined
JavaScript Check If Variable Exists (Is Defined/Initialized)
How to Get the Full Object in Node.Js'S Console.Log(), Rather Than '[Object]'