I don't think you can make that any simpler, but you could certainly refactor that logic into a function:
function isRealValue(obj)
{
return obj && obj !== 'null' && obj !== 'undefined';
}
Then, at least your code becomes:
if (isRealValue(yourObject))
{
doSomething();
}
Answer from aquinas on Stack OverflowI don't think you can make that any simpler, but you could certainly refactor that logic into a function:
function isRealValue(obj)
{
return obj && obj !== 'null' && obj !== 'undefined';
}
Then, at least your code becomes:
if (isRealValue(yourObject))
{
doSomething();
}
If you have jQuery, you could use $.isEmptyObject().
$.isEmptyObject(null)
$.isEmptyObject(undefined)
var obj = {}
$.isEmptyObject(obj)
All these calls will return true. Hope it helps
Videos
Is null false in JavaScript?
What is a null check?
What is a strict null check?
To determine whether the target reference contains a member with a null value, you'll have to write your own function as none exist out of the box to do this for you. One simple approach would be:
function hasNull(target) {
for (var member in target) {
if (target[member] == null)
return true;
}
return false;
}
Needless to say, this only goes one level deep, so if one of the members on target contains another object with a null value, this will still return false. As an exmaple of usage:
var o = { a: 'a', b: false, c: null };
document.write('Contains null: ' + hasNull(o));
Will print out:
Contains null: true
In contrast, the following will print out false:
var o = { a: 'a', b: false, c: {} };
document.write('Contains null: ' + hasNull(o));
This is just for your reference. Do not upvote.
var jso;
document.writeln(typeof(jso)); // 'undefined'
document.writeln(jso); // value of jso = 'undefined'
jso = null;
document.writeln(typeof(jso)); // null is an 'object'
document.writeln(jso); // value of jso = 'null'
document.writeln(jso == null); // true
document.writeln(jso === null); // true
document.writeln(jso == "null"); // false
http://jsfiddle.net/3JZfT/3/
So I'm usually more of a server side developer, but lately I've been working with more of the client code at work. I understand what undefined and null are in JavaScript, but I find myself always checking for both of them. In fact, when checking if a String property exists, I end up writing this:
if(value !== undefined && value !== null && value !== '')
I figure there is a better way than this, and it's probably because I'm not 100% clear of when to check for what. So if someone could help fill me in here on the rules of when to check for undefined vs null, that would be great.
TL;DR: Use value != null. It checks for both null and undefined in one step.
In my mind, there are different levels of checking whether something exists:
0) 'property' in object - Returns true if the property exists at all, even if it's undefined or null.
-
object.property !== undefined- Returns true if the property exists and is not undefined. Null values still pass. -
object.property != null- Return true if the property exists and is not undefined or null. Empty strings and 0's still pass. -
!!object.property- Returns true if the property exists and is "truthy", so even 0 and empty strings are considered false.
From my experience, level 2 is usually the sweet spot. Oftentimes, things like empty strings or 0 will be valid values, so level 3 is too strict. On the other hand, levels 0 and 1 are usually too loose (you don't want nulls or undefineds in your program). Notice that level 1 uses strict equality (!==), while level 2 uses loose equality (!=).
I would just say
if (value) {
// do stuff
}
because
'' || false
// false
null || false
// false
undefined || false
//false
Edit:
Based on this statement
I end up writing this: if(value !== undefined && value !== null && value !== '')
I initially assumed that what OP was really looking for was a better way to ask "is there a value?", but...
if someone could help fill me in here on the rules of when to check for undefined vs null, that would be great.
If you're looking to see if something is "truthy":
if (foo.bar) {
alert(foo.bar)
}
This won't alert if value is '', 0, false, null, or undefined
If you want to make sure something is a String so you can use string methods:
if (typeof foo.bar === 'string') {
alert(foo.bar.charAt(0))
}
This won't alert unless value is of type 'string'.
So.. "when to check for undefined vs null"? I would just say, whenever you know that you specifically need to check for them. If you know that you want to do something different when a value is null vs when a value is undefined, then you can check for the difference. But if you're just looking for "truthy" then you don't need to.
Check all values with Object.values. It returns an array with the values, which you can check with Array.prototype.every or Array.prototype.some:
const isEmpty = Object.values(object).every(x => x === null || x === '');
const isEmpty = !Object.values(object).some(x => x !== null && x !== '');
Create a function to loop and check:
function checkProperties(obj) {
for (var key in obj) {
if (obj[key] !== null && obj[key] != "")
return false;
}
return true;
}
var obj = {
x: null,
y: "",
z: 1
}
checkProperties(obj) //returns false
You can use Object.values to convert the object into array and use every to check each element. Use ! to negate the value.
let report = {
property1: null,
property2: null,
}
let result = !Object.values(report).every(o => o === null);
console.log(result);
An example some elements are not null
let report = {
property1: null,
property2: 1,
}
let result = !Object.values(report).every(o => o === null);
console.log(result);
Doc: Object.values(), every()
Approach using .some() instead of .every():
function isEmpty (obj) {
return !Object.values(obj).some(element => element !== null);
}
This function (named isEmpty to match the name given in the question) shall return false if any obj property is not null and true otherwise.
You can use an utility function like this:
get = function(obj, key) {
return key.split(".").reduce(function(o, x) {
return (typeof o == "undefined" || o === null) ? o : o[x];
}, obj);
}
Usage:
get(user, 'loc.lat') // 50
get(user, 'loc.foo.bar') // undefined
Or, to check only if a property exists, without getting its value:
has = function(obj, key) {
return key.split(".").every(function(x) {
if(typeof obj != "object" || obj === null || ! x in obj)
return false;
obj = obj[x];
return true;
});
}
if(has(user, 'loc.lat')) ...
You can combine the checks using lazy and:
if(user.loc && user.loc.lat) { ...
Or, you use CoffeeScript. And ES2020 has new syntax ( Nullish coalescing Operator ).
user.loc?.lat?. '...'
which would run the checks for loc property and safeguard against empty objects.