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?
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.
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/
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.
JavaScript is very flexible with regards to checking for "null" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:
if(!pass || !cpass || !email || !cemail || !user){
Which will check for empty strings (""), null, undefined, false and the numbers 0 and NaN.
Please note that if you are specifically checking for numbers, it is a common mistake to miss 0 with this method, and num !== 0 is preferred (or num !== -1 or ~num (hacky code that also checks against -1)) for functions that return -1, e.g. indexOf).
To check for null SPECIFICALLY you would use this:
if (variable === null)
This test will ONLY pass for null and will not pass for "", undefined, false, 0, or NaN.
Additionally, I've provided absolute checks for each "false-like" value (one that would return true for !variable).
Note, for some of the absolute checks, you will need to implement use of the absolutely equals: === and typeof.
I've created a JSFiddle here to show all of the individual tests working
Here is the output of each check:
Null Test:
if (variable === null)
- variable = ""; (false) typeof variable = string
- variable = null; (true) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Empty String Test:
if (variable === '')
- variable = ''; (true) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Undefined Test:
if (typeof variable == "undefined")
-- or --
if (variable === undefined)
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (true) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
False Test:
if (variable === false)
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (true) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Zero Test:
if (variable === 0)
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (true) typeof variable = number
- variable = NaN; (false) typeof variable = number
NaN Test:
if (typeof variable == 'number' && !parseFloat(variable) && variable !== 0)
-- or --
if (isNaN(variable))
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (true) typeof variable = number
As you can see, it's a little more difficult to test against NaN;