I want to check in an JS object (example: { x:false, y:true } ) if some properties are either boolean or if they are (null || undefined).
Is there an easy way in JS or Underscore to check this without doing
(obj.x != null || obj.x != undefined)
???
You could use just the standard typeof operator, which returns 'boolean' if boolean.
console.log(typeof undefined === 'boolean'); // false
console.log(typeof null === 'boolean'); // false
console.log(typeof true === 'boolean'); // true
console.log(typeof false === 'boolean'); // true
The typeof operator can return whether it is boolean or anything else
Reference here
I found an easy way in Underscore:
_.isBoolean(obj.x)
Thanks to Rajesh I know now that obj.x != null returns the same if x is null or undefined.
I prefer the Underscore function because it's readable, but the null comparison is native JS and seems more efficient, and simpler.
Try this Hope it will help you,
JavaScript
function test(v) {
let type = typeof v;
if(type === 'undefined') {
return true;
}
if(type=== 'boolean') {
return false;
}
if(v === null) {
return true;
}
if(v === undefined) {
return true;
}
if(v instanceof Array) {
if(v.length < 1) {
return true;
}
}
else if(type === 'string') {
if(v.length < 1) {
return true;
}
}
else if(type === 'object') {
if(Object.keys(v).length < 1) {
return true;
}
}
else if(type === 'number') {
if(isNaN(v)) {
return true;
}
}
return false;
}
In Javascript, undefined is evaluated as false, so you should be able to do
if (obj.x) {
// ...
}
I have 20 divs, each one with a speficif class, so I select it and check if is 1 of the 4 'special ones'.
The main issue is that the following code is supposed to work...
$('.cbp-ig-grid li, .cbp-ig-grid li a span object').on('click', function () {
/* Variables Definition */
var item = $(this).find('span').attr('class').split(' ')[1]
}
if((item != 'item1') || (item != 'item2') || (item != 'item3') || (item != 'item4')){
// Always enters here!
}else{
// Never enters here :( (I need to enter here for the 4 cases in the if statement)
}
but when I do for just one ... it works!
if(item != 'item1'){
// do stuff
}else{
// do other stuff
}
I don't know what I'm doing wrong, please any help will be useful
Consider your if statement:
if((item != 'item1') || (item != 'item2') || (item != 'item3') || (item != 'item4')){
}
What that is saying is that if ANY of these conditions are true, the if condition is met and it will execute the if block.
Let's say the item is "item2" now the first expression of your if statement is met as it's not item1 so that part is true. thus it executes the block.
What you want is: &&
if((item != 'item1') && (item != 'item2') && (item != 'item3') && (item != 'item4')){
//when it's not the special case.
}
else
{
//the 4 special cases.
}
if((item != 'item1') || (item != 'item2') || (item != 'item3') || (item != 'item4')){
No chance to go into the else here... item is always different from one or the other.
.hasClass() is your best friend. https://api.jquery.com/hasclass/
$('.cbp-ig-grid li, .cbp-ig-grid li a span object').on('click', function () {
/* Variables Definition */
var item = $(this).find('span');
switch(true) {
case item.hasClass('item1'):
// item 1
break;
case item.hasClass('item2'):
// item 2
break;
case item.hasClass('item3'):
// item 3
break;
case item.hasClass('item4'):
// item 4
break;
default:
// other stuff
}
});
Let's make it simple
if((item != 'item1') || (item != 'item2') || (item != 'item3') || (item != 'item4'))
Let's test it:
1:
item = 'item1':
false || true || true || true
that equals to true; because false || true = true
2:
item = 'theGreatOldOnes'
true || true || true || true - that equal to true
Both are true! That means that your expression is flawed - it doesn't make difference between 'special class' and any 'nonspecial class'
To make it understand difference between 'special' and 'not special' you need to use:
if((item != 'item1') && (item != 'item2') && (item != 'item3') && (item != 'item4'))
Or
if((item === 'item1') || (item === 'item2') || (item === 'item3') || (item === 'item4'))
You can do testing with 'item1' and 'theGreatOldOnes' to get a better grip on those things ^ ^
if localStorage["BestScore"] = undefined;
{
localStorage["BestScore"]=0;
maxScore=0;
}
var maxScore=localStorage["BestScore"];
var newScore=false
function drawScore(score) {
if (newScore == true && score < maxScore) {
newScore = false;
}
if (score > maxScore) {
newScore = true;
localStorage["BestScore"] = score;
if ([5, 10, 15, 20].indexOf(score) !== -1) {
play(sndMedal);
} else {
play(sndGain);
}
}
This code is to set the max score and then store it but it doesn't seem to set the local storage to 0 if undefined.
if localStorage["BestScore"] = undefined;
should be:
if( typeof localStorage["BestScore"] === 'undefined' )
However if you need to check a variable against undefined value, there is no need to invent any special method, since JavaScript has a typeof operator, which is simple, fast and cross-platform:
if (typeof localStorage["BestScore"] === "undefined") {
localStorage["BestScore"] = 0;
}
It returns a string indicating the type of the variable or other unevaluated operand. The main advantage of this method, compared to if (value === undefined) { ... }, is that typeof will never raise an exception in case if variable value does not exist.
if localStorage["BestScore"] = undefined;
should be ==
else you are assigning, not comparing.
use == or === as a comparison operator, then it should be fine
How can I check if a variable is empty in Javascript?
if(response.photo) is empty {
do something
else {
do something else
}
response.photo was from JSON, and it could be empty sometimes, empty data cells! I want to check if it's empty.
If you're testing for an empty string:
if(myVar === ''){ // do stuff };
If you're checking for a variable that has been declared, but not defined:
if(myVar === null){ // do stuff };
If you're checking for a variable that may not be defined:
if(myVar === undefined){ // do stuff };
If you're checking both i.e, either variable is null or undefined:
if(myVar == null){ // do stuff };
This is a bigger question than you think. Variables can empty in a lot of ways. Kinda depends on what you need to know.
// quick and dirty will be true for '', null, undefined, 0, NaN and false.
if (!x)
// test for null OR undefined
if (x == null)
// test for undefined OR null
if (x == undefined)
// test for undefined
if (x === undefined)
// or safer test for undefined since the variable undefined can be set causing tests against it to fail.
if (typeof x == 'undefined')
// test for empty string
if (x === '')
// if you know its an array
if (x.length == 0)
// or
if (!x.length)
// BONUS test for empty object
var empty = true, fld;
for (fld in x) {
empty = false;
break;
}
This should cover all cases:
function empty( val ) {
// test results
//---------------
// [] true, empty array
// {} true, empty object
// null true
// undefined true
// "" true, empty string
// '' true, empty string
// 0 false, number
// true false, boolean
// false false, boolean
// Date false
// function false
if (val === undefined)
return true;
if (typeof (val) == 'function' || typeof (val) == 'number' || typeof (val) == 'boolean' || Object.prototype.toString.call(val) === '[object Date]')
return false;
if (val == null || val.length === 0) // null or 0 length array
return true;
if (typeof (val) == "object") {
// empty object
var r = true;
for (var f in val)
r = false;
return r;
}
return false;
}
I see potential shortcomings in many solutions posted above, so I decided to compile my own.
Note: it uses Array.prototype.some, check your browser support.
Solution below considers variable empty if one of the following is true:
JS thinks that variable is equal to false, which already covers many things like 0, "", [], and even [""] and [0]
Value is null or it's type is 'undefined'
It is an empty Object
It is an Object/Array consisting only of values that are empty themselves (i.e. broken down to primitives each part of it equals false). Checks drill recursively into Object/Array structure.
E.g.
isEmpty({"": 0}) // true
isEmpty({"": 1}) // false
isEmpty([{}, {}]) // true
isEmpty(["", 0, {0: false}]) //true
Function code:
/**
* Checks if value is empty. Deep-checks arrays and objects
* Note: isEmpty([]) == true, isEmpty({}) == true, isEmpty([{0:false},"",0]) == true, isEmpty({0:1}) == false
* #param value
* #returns {boolean}
*/
function isEmpty(value){
var isEmptyObject = function(a) {
if (typeof a.length === 'undefined') { // it's an Object, not an Array
var hasNonempty = Object.keys(a).some(function nonEmpty(element){
return !isEmpty(a[element]);
});
return hasNonempty ? false : isEmptyObject(Object.keys(a));
}
return !a.some(function nonEmpty(element) { // check if array is really not empty as JS thinks
return !isEmpty(element); // at least one element should be non-empty
});
};
return (
value == false
|| typeof value === 'undefined'
|| value == null
|| (typeof value === 'object' && isEmptyObject(value))
);
}
Here my simplest solution.
Inspired by PHP empty function
function empty(n){
return !(!!n ? typeof n === 'object' ? Array.isArray(n) ? !!n.length : !!Object.keys(n).length : true : false);
}
//with number
console.log(empty(0)); //true
console.log(empty(10)); //false
//with object
console.log(empty({})); //true
console.log(empty({a:'a'})); //false
//with array
console.log(empty([])); //true
console.log(empty([1,2])); //false
//with string
console.log(empty('')); //true
console.log(empty('a')); //false
A more readable version of #SJ00 answer:
/**
* Checks if a JavaScript value is empty
* #example
* isEmpty(null); // true
* isEmpty(undefined); // true
* isEmpty(''); // true
* isEmpty([]); // true
* isEmpty({}); // true
* #param {any} value - item to test
* #returns {boolean} true if empty, otherwise false
*/
function isEmpty(value) {
return (
value === null || // check for null
value === undefined || // check for undefined
value === '' || // check for empty string
(Array.isArray(value) && value.length === 0) || // check for empty array
(typeof value === 'object' && Object.keys(value).length === 0) // check for empty object
);
}
See http://underscorejs.org/#isEmpty
isEmpty_.isEmpty(object)
Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.
Combining answers from #inkednm into one function:
function isEmpty(property) {
return (property === null || property === "" || typeof property === "undefined");
}
Empty check on a JSON's key depends on use-case. For a common use-case, we can test for following:
Not null
Not undefined
Not an empty String ''
Not an empty Object {} [] (Array is an Object)
Function:
function isEmpty(arg){
return (
arg == null || // Check for null or undefined
arg.length === 0 || // Check for empty String (Bonus check for empty Array)
(typeof arg === 'object' && Object.keys(arg).length === 0) // Check for empty Object or Array
);
}
Return true for:
isEmpty(''); // Empty String
isEmpty(null); // null
isEmpty(); // undefined
isEmpty({}); // Empty Object
isEmpty([]); // Empty Array
just put the variable inside the if condition, if variable has any value it will return true else false.
if (response.photo){ // if you are checking for string use this if(response.photo == "") condition
alert("Has Value");
}
else
{
alert("No Value");
};
What about doing like this.
JSON.stringify({}) === "{}"
just be careful with all what i see here:
typeof object === 'object' && Object.keys(object).length === 0) is indeed checking if an object is Empty. But did you know that Date in javascript are considered object also?
so if you do:
const shouldNotbeEmpty = new Date(Date.now())
isEmpty(shouldNotbeEmpty) // this will return true when it should not
my only way to figure it out to fix that was to check if the object is a Date instance:
typeof value === "object" && Object.keys(value).length === 0 && !value instanceof Date
so something like this:
const isObject = value => typeof value === "object" && Object.keys(value).length === 0
const isString = value => typeof value === "string" && value.trim().length === 0
const isEmpty = value => {
const isDate = value instanceof Date
return value === undefined || value === null || (isObject(value) && !isDate) || isString(value)
}
exports.isEmpty = isEmpty
const isEmpty = value => {
if (!value && value !== 0) return true
if(Array.isArray(value)){
if(!value.length) return true
return value.every(isEmpty)
}
if (typeof value === 'object') {
return Object.values(value).every(isEmpty)
}
return false
}
isEmpty(); // true
isEmpty(undefined); // true
isEmpty(null); // true
isEmpty(0); // false
isEmpty(1); // false
isEmpty(''); // true
isEmpty('a'); // false
isEmpty([]); // true
isEmpty([0]); // false
isEmpty([1]); // false
isEmpty([[]]); // true
isEmpty([[], []]); // true
isEmpty([[], null, undefined]); // true
isEmpty([[], 1]); // false
isEmpty({}); // true
isEmpty({a: 1}); // false
isEmpty({a: 1, b: 2}); // false
isEmpty({a: 1, b: {}}); // false
isEmpty({a: null, b: [], c: undefined}); // true
isEmpty({a: {}, b: {}, c: {}}); // true
isEmpty(() => {}) // false
It depends on what you mean by "empty". The most common pattern is to check to see if the variable is undefined. Many people also do a null check, for example:
if (myVariable === undefined || myVariable === null)...
or, in a shorter form:
if (myVariable || myVariable === null)...
if (myVar == undefined)
will work to see if the var is declared but not initalized.
Check for undefined:
if (typeof response.photo == "undefined")
{
// do something
}
This would do the equivelant of vb's IsEmpty. If myvar contains any value, even null, empty string, or 0, it is not "empty".
To check if a variable or property exists, eg it's been declared, though it may be not have been defined, you can use the in operator.
if ("photo" in response)
{
// do something
}
If you're looking for the equivalent of PHP's empty function, check this out:
function empty(mixed_var) {
// example 1: empty(null);
// returns 1: true
// example 2: empty(undefined);
// returns 2: true
// example 3: empty([]);
// returns 3: true
// example 4: empty({});
// returns 4: true
// example 5: empty({'aFunc' : function () { alert('humpty'); } });
// returns 5: false
var undef, key, i, len;
var emptyValues = [undef, null, false, 0, '', '0'];
for (i = 0, len = emptyValues.length; i < len; i++) {
if (mixed_var === emptyValues[i]) {
return true;
}
}
if (typeof mixed_var === 'object') {
for (key in mixed_var) {
// TODO: should we check for own properties only?
//if (mixed_var.hasOwnProperty(key)) {
return false;
//}
}
return true;
}
return false;
}
http://phpjs.org/functions/empty:392
what am I missing if empty array... keyless object... falseness
const isEmpty = o => Array.isArray(o) && !o.join('').length || typeof o === 'object' && !Object.keys(o).length || !(+value);
Here's a simpler(short) solution to check for empty variables. This function checks if a variable is empty. The variable provided may contain mixed values (null, undefined, array, object, string, integer, function).
function empty(mixed_var) {
if (!mixed_var || mixed_var == '0') {
return true;
}
if (typeof mixed_var == 'object') {
for (var k in mixed_var) {
return false;
}
return true;
}
return false;
}
// example 1: empty(null);
// returns 1: true
// example 2: empty(undefined);
// returns 2: true
// example 3: empty([]);
// returns 3: true
// example 4: empty({});
// returns 4: true
// example 5: empty(0);
// returns 5: true
// example 6: empty('0');
// returns 6: true
// example 7: empty(function(){});
// returns 7: false
const isEmpty = val => val == null || !(Object.keys(val) || val).length;
function isEmpty(variable) {
const type = typeof variable
if (variable === null) return true
if (type === 'undefined') return true
if (type === 'boolean') return false
if (type === 'string') return !variable
if (type === 'number') return false
if (Array.isArray(variable)) return !variable.length
if (type === 'object') return !Object.keys(variable).length
return !variable
}
My solution:
function isEmpty(object) {
return (
(!object)
|| (object === undefined)
|| (object === null)
|| (object === '')
|| ((object?.length !== undefined) && (object.length === 0))
|| (typeof object === 'object' && Object.keys(object).length === 0)
);
}
Tests with Jest:
describe('isEmpty should return `false` when the parameter have some truthy value.', () => {
test('Empty objects should return true', () => {
expect(utils.isEmpty([])).toBe(true);
expect(utils.isEmpty({})).toBe(true);
expect(utils.isEmpty('')).toBe(true);
expect(utils.isEmpty(undefined)).toBe(true);
expect(utils.isEmpty(null)).toBe(true);
});
test('Truthy objects should return false', () => {
expect(utils.isEmpty([1])).toBe(false);
expect(utils.isEmpty({a: undefined})).toBe(false);
expect(utils.isEmpty({a: 5})).toBe(false);
expect(utils.isEmpty({a: 5, b: 6, c: undefined})).toBe(false);
expect(utils.isEmpty('f00')).toBe(false);
expect(utils.isEmpty('0')).toBe(false);
});
})
var message_1 = message.trim();
if (message_1.length > 0) {
// to do
}