Check for empty of null in javascript - javascript

I had a bug that turned out to be because I forgot to check for null values. I added the check, but would like if it could be written more concise.
<ListItem onClick={!pattern.capped && !pattern.hasInlineRef ? search(pattern.dbValue, pattern.dbValue === "" || pattern.dbValue === null) : undefined}>
Can this check for empty or null be shortened?
search(pattern.dbValue, pattern.dbValue === "" || pattern.dbValue === null)
It's written in Typescript, but I guess the curly braces make it JavaScript.

First, you can create an util function to check null, empty or undefined:
export function isNullOrEmpty(value) {
return (value === null || value === undefined || value === "") ? true : false
}
Or, you can fast test with falsy and truthy:
search(pattern.dbValue, !pattern.dbValue)
List of falsy values in JavaScript: MDN Falsy
false
null
undefined
0
NaN
''
document.all

You can create an helper function in a separate folder and pull out this function into the files where you need to check for null, undefined, empty string or an empty object.You can write something like this:
export default value =>
value === undefined ||
value === null ||
(typeof value === 'object' && Object.keys(value).length === 0) ||
(typeof value === 'string' && value.trim().length === 0);
Hope this helps

Related

Ignore null values while using .find()

I'm using javascript's .find() method to search for values in my array. I am getting the following error: Uncaught TypeError: Cannot read property 'toUpperCase' of null which is occurring at this line: if (this.collection.find(x => x.details.numb.toUpperCase() === numb)) {
I believe this error is happening because there are null values coming in at x.details.numb. Is it possible to ignore null values from within this line of code? Or will I have to remake my array without null values?
You can check for null values before calling toUpperCase
if (this.collection.find(x => x.details && x.details.numb && x.details.numb.toUpperCase() === numb)) {
As #VLAZ pointed out in comments this will fail for numb === '' in that case you can use
(x.details && x.details.numb || '' ).toUpperCase() === numb
Sure !
x.details && x.details.numb && x.details.numb.toUpperCase() === numb
Just use a check for null, as well as toUpperCase:
this.colleciton.find(x => x.details != null && x.details.numb != null && x.details.numb.toUpperCase && x.details.numb.toUpperCase() === numb)
Since you're in a condition, you can use some instead of find, because some stops once the condition is met (resulting in better performance) :
this.collection
.some(item => item && item.details && items.details.numb.toUpperCase() === numb)
As brought up by a wild commenter, you can also prevent undefined values from happening as such :
this.collection
.some(item => item
&& item.details
&& items.details.numb
&& ![undefined, null].includes(items.details.numb)
items.details.numb.toUpperCase() === numb)

How to NOT return the last object in a boolean chain

I have code like this:
function doAThing(var1) {
return typeof var1 === "object" && Object.keys(var1).length > 11;
}
I'm having a problem where when var1 is NOT an object the function tries to return the value of the last statement: Object.keys(var1).length > 11)
Obviously, if obj1 is not an object i don't want to try and get it's keys or it will blow up with Cannot convert undefined or null to object.
How can i get this function to return a boolean and NOT try to check var1's keys if it's not an object?
Try adding a null check to your condition, as typeof null is also object:
function doAThing() {
return !bool1
&& var1 !== null
&& typeof var1 === "object"
&& Object.keys(var1).length > 11);
}

javascript testing for object property

I have a string like this:
var TheDate = "6.14.2012";
and I have an object MyObject that has properties that may match that string. However, when I write this:
if (MyObject[TheDate] === null || MyObject[TheDate] === 'undefined') { .... }
the conditions never seem to evaluate to true even though I know the property doesn't exist.
What am I missing??
Thanks.
Existence of Own Property
If you want to check for the existence of a property use .hasownProperty()...
if (MyObject.hasOwnProperty(TheDate)) {
Existence of Own Or Inherited Property
If the property may be inherited, to test for existence use the in operator...
if (TheDate in MyObject) {
null or undefined value test for Own Or Inherited Property
If it's not existence, but rather a value test, and you want to test for null or undefined, then use this...
if (MyObject[TheDate] == null) {
This will check for both null and undefined.
The problem is with the quotes around undefined ;)
Change
if (MyObject[TheDate] === null || MyObject[TheDate] === 'undefined') { .... }
to
if (MyObject[TheDate] === null || MyObject[TheDate] === undefined) { .... }
It should work :)
If you want to use the string "undefined" rather than the undefined object, the way to do this is to check the "typeof", which returns a string. In this case, if you're looking to test if it's set to "undefined":
if ( MyObject[TheDate] === null || typeof MyObject[TheDate] === 'undefined' ) { .... }
Try the following
if ( (MyObject[TheDate] === null) || (typeof MyObject[TheDate] === 'undefined') {
....
}
You were checking whether your property contains the String 'undefined' and not whether its value is currently undefined.

Checking undefined value not working?

I have the following javascript code:
var currentIds = localStorage.getItem('currentPairsIds');
if ((typeof currentIds === "undefined") ||
(currentIds == null))
$.myNameSpace.currentIDs = new Array(3);
else
$.myNameSpace.currentIDs = currentIds.Split(',');
I'm debugging with Firebug and although currentIds hasn't got any value it always executes else statement.
UPDATE: I'm getting this value from HTML5 storage.
What am I doing wrong?
This is how I have solved my problem:
var currentIds = localStorage.getItem('currentPairsIds');
if ((currentIds === undefined) ||
(currentIds == null) || (currentIds == "undefined"))
$.myNameSpace.currentIDs = new Array(3);
else
$.myNameSpace.currentIDs = currentIds.split(',');
localStorage.getItem('currentPairsIds'); returns the string "undefined".
There is another error in Split() function. The right version is without any capital letter.
I would use a direct comparison instead of the notoriously odd "typeof" operator:
if ((currentIds === undefined) || (currentIds === null)) {
//...
It's not working because localStorage.getItem returns null if the item is not defined, it does not return undefined http://dev.w3.org/html5/webstorage/#dom-storage-getitem
Example: http://jsfiddle.net/mendesjuan/Rsu8N/1/
var notStored = localStorage.getItem('ffff');
alert(notStored); // null
alert(typeof notStored); // object, yes, null is an object.
Therefore you should just be testing
alert(notStored === null);
I think you have to make checking for undefined comparing with == instead of ===.
Example:
typeof currentIds == "undefined"
This will make sure, the variable is really undefined or not.
[Edit Edit Edit Edit :P]
currentIds = "undefined"
implies
typeof currentIds == "String"
Also see, Detecting Undefined, === isn't necessary for string comparison.
In my case LocalStorage.getItem() was converting it to "undefined" as string.
I also needed to check if it s "undefined" as a string.
var myItem = LocalStorage.getItem('myItem');
if(myItem != "undefined" && myItem != undefined && myItem != null){
...
}
if( typeof(varName) != "undefined" && varName !== null )
be sure, you use ( " " ) quotes when checking with typeof()

How do I check for null values in JavaScript?

How can I check for null values in JavaScript? I wrote the code below but it didn't work.
if (pass == null || cpass == null || email == null || cemail == null || user == null) {
alert("fill all columns");
return false;
}
And how can I find errors in my JavaScript programs?
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;
just replace the == with === in all places.
== is a loose or abstract equality comparison
=== is a strict equality comparison
See the MDN article on Equality comparisons and sameness for more detail.
You can check if some value is null as follows
[pass,cpass,email,cemail,user].some(x=> x===null)
let pass=1;
let cpass=2;
let email=3;
let cemail=null;
let user=5;
if ( [pass,cpass,email,cemail,user].some(x=> x===null) ) {
alert("fill all columns");
//return false;
}
BONUS: Why === is more clear than == (source)
a == b
a === b
Strict equality operator:-
We can check null by ===
if ( value === null ){
}
Just by using if
if( value ) {
}
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
false
0
At first sight, it looks like a simple trade-off between coverage and strictness.
== covers multiple values, can handle more scenarios in less code.
=== is the most strict, and that makes it predictable.
Predictability always wins, and that appears to make === a one-fits-all solution.
But it is wrong. Even though === is predictable, it does not always result in predictable code, because it overlooks scenarios.
const options = { };
if (options.callback !== null) {
options.callback(); // error --> callback is undefined.
}
In general == does a more predictable job for null checks:
In general, null and undefined both mean the same thing: "something's missing". For predictability, you need to check both values. And then == null does a perfect job, because it covers exactly those 2 values. (i.e. == null is equivalent to === null && === undefined)
In exceptional cases you do want a clear distinction between null and undefined. And in those cases you're better of with a strict === undefined or === null. (e.g. a distinction between missing/ignore/skip and empty/clear/remove.) But it is rare.
It is not only rare, it's something to avoid. You can't store undefined in a traditional database. And you shouldn't rely on undefined values in your API designs neither, due to interopability reasons. But even when you don't make a distinction at all, you can't assume that undefined won't happen. People all around us indirectly take actions that generalize null/undefined (which is why questions like this are closed as "opinionated".).
So, to get back to your question. There's nothing wrong with using == null. It does exactly what it should do.
// FIX 1 --> yes === is very explicit
const options = { };
if (options.callback !== null &&
options.callback !== undefined) {
options.callback();
}
// FIX 2 --> but == covers both
const options = { };
if (options.callback != null) {
options.callback();
}
// FIX 3 --> optional chaining also covers both.
const options = { };
options.callback?.();
Improvement over the accepted answer by explicitly checking for null but with a simplified syntax:
if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
// your code here ...
}
// Test
let pass=1, cpass=1, email=1, cemail=1, user=1; // just to test
if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
// your code here ...
console.log ("Yayy! None of them are null");
} else {
console.log ("Oops! At-lease one of them is null");
}
Firstly, you have a return statement without a function body. Chances are that that will throw an error.
A cleaner way to do your check would be to simply use the ! operator:
if (!pass || !cpass || !email || !cemail || !user) {
alert("fill all columns");
}
you can use try catch finally
try {
document.getElementById("mydiv").innerHTML = 'Success' //assuming "mydiv" is undefined
} catch (e) {
if (e.name.toString() == "TypeError") //evals to true in this case
//do something
} finally {}
you can also throw your own errors. See this.
In JavaScript, no string is equal to null.
Maybe you expected pass == null to be true when pass is an empty string because you're aware that the loose equality operator == performs certain kinds of type coercion.
For example, this expression is true:
'' == 0
In contrast, the strict equality operator === says that this is false:
'' === 0
Given that '' and 0 are loosely equal, you might reasonably conjecture that '' and null are loosely equal. However, they are not.
This expression is false:
'' == null
The result of comparing any string to null is false. Therefore, pass == null and all your other tests are always false, and the user never gets the alert.
To fix your code, compare each value to the empty string:
pass === ''
If you're certain that pass is a string, pass == '' will also work because only an empty string is loosely equal to the empty string. On the other hand, some experts say that it's a good practice to always use strict equality in JavaScript unless you specifically want to do the type coercion that the loose equality operator performs.
If you want to know what pairs of values are loosely equal, see the table "Sameness comparisons" in the Mozilla article on this topic.
to check for undefined and null in javascript you need just to write the following :
if (!var) {
console.log("var IS null or undefined");
} else {
console.log("var is NOT null or undefined");
}
Actually I think you may need to use
if (value !== null && value !== undefined)
because if you use if (value) you may also filter 0 or false values.
Consider these two functions:
const firstTest = value => {
if (value) {
console.log('passed');
} else {
console.log('failed');
}
}
const secondTest = value => {
if (value !== null && value !== undefined) {
console.log('passed');
} else {
console.log('failed');
}
}
firstTest(0); // result: failed
secondTest(0); // result: passed
firstTest(false); // result: failed
secondTest(false); // result: passed
firstTest(''); // result: failed
secondTest(''); // result: passed
firstTest(null); // result: failed
secondTest(null); // result: failed
firstTest(undefined); // result: failed
secondTest(undefined); // result: failed
In my situation, I just needed to check if the value is null and undefined and I did not want to filter 0 or false or '' values. so I used the second test, but you may need to filter them too which may cause you to use first test.
This is a comment on WebWanderer's solution regarding checking for NaN (I don't have enough rep yet to leave a formal comment). The solution reads as
if(!parseInt(variable) && variable != 0 && typeof variable === "number")
but this will fail for rational numbers which would round to 0, such as variable = 0.1. A better test would be:
if(isNaN(variable) && typeof variable === "number")
You can use lodash module to check value is null or undefined
_.isNil(value)
Example
country= "Abc"
_.isNil(country)
//false
state= null
_.isNil(state)
//true
city= undefined
_.isNil(state)
//true
pin= true
_.isNil(pin)
// false
Reference link: https://lodash.com/docs/#isNil
AFAIK in JAVASCRIPT when a variable is declared but has not assigned value, its type is undefined. so we can check variable even if it would be an object holding some instance in place of value.
create a helper method for checking nullity that returns true and use it in your API.
helper function to check if variable is empty:
function isEmpty(item){
if(item){
return false;
}else{
return true;
}
}
try-catch exceptional API call:
try {
var pass, cpass, email, cemail, user; // only declared but contains nothing.
// parametrs checking
if(isEmpty(pass) || isEmpty(cpass) || isEmpty(email) || isEmpty(cemail) || isEmpty(user)){
console.log("One or More of these parameter contains no vlaue. [pass] and-or [cpass] and-or [email] and-or [cemail] and-or [user]");
}else{
// do stuff
}
} catch (e) {
if (e instanceof ReferenceError) {
console.log(e.message); // debugging purpose
return true;
} else {
console.log(e.message); // debugging purpose
return true;
}
}
some test cases:
var item = ""; // isEmpty? true
var item = " "; // isEmpty? false
var item; // isEmpty? true
var item = 0; // isEmpty? true
var item = 1; // isEmpty? false
var item = "AAAAA"; // isEmpty? false
var item = NaN; // isEmpty? true
var item = null; // isEmpty? true
var item = undefined; // isEmpty? true
console.log("isEmpty? "+isEmpty(item));
The 'Object.is()' method can be used to determine if two values are the same value. So, you can use it to check whether the object is null or not.
Check for null values
let testA = null; //null
//console.log(Object.is(testA, null)); //true //null === null
if(Object.is(testA, null)) {
console.log("This is a Null Value");
}
Output:
This is a Null Value
let x = null;
if (x === null) {
console.log("x is null");
}
Output:
x is null
Check for undefined values (A variable has been declared, but a value has not been assigned.)
let testB; //undefined
//console.log(Object.is(testB, undefined)); //true //undefined === undefined
if(Object.is(testB, undefined)) {
console.log("This is an undefined Value");
}
Output:
This is an undefined Value
If the object has not been declared, this cannot be used. As an alternative, you may try this:
if (typeof x === "undefined") {
console.log("x is undefined");
}
Output:
The value is either undefined or null
Mozilla Object.is():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
I found a another way to test if the value is null:
if(variable >= 0 && typeof variable === "object")
null acts as a number and object at the same time. Comparing null >= 0 or null <= 0 results in true. Comparing null === 0 or null > 0 or null < 0 will result in false. But as null is also an object we can detect it as a null.
I made a more complex function natureof witch will do better than typeof and can be told what types to include or keep grouped
/* function natureof(variable, [included types])
included types are
null - null will result in "undefined" or if included, will result in "null"
NaN - NaN will result in "undefined" or if included, will result in "NaN"
-infinity - will separate negative -Inifity from "Infinity"
number - will split number into "int" or "double"
array - will separate "array" from "object"
empty - empty "string" will result in "empty" or
empty=undefined - empty "string" will result in "undefined"
*/
function natureof(v, ...types){
/*null*/ if(v === null) return types.includes('null') ? "null" : "undefined";
/*NaN*/ if(typeof v == "number") return (isNaN(v)) ? types.includes('NaN') ? "NaN" : "undefined" :
/*-infinity*/ (v+1 === v) ? (types.includes('-infinity') && v === Number.NEGATIVE_INFINITY) ? "-infinity" : "infinity" :
/*number*/ (types.includes('number')) ? (Number.isInteger(v)) ? "int" : "double" : "number";
/*array*/ if(typeof v == "object") return (types.includes('array') && Array.isArray(v)) ? "array" : "object";
/*empty*/ if(typeof v == "string") return (v == "") ? types.includes('empty') ? "empty" :
/*empty=undefined*/ types.includes('empty=undefined') ? "undefined" : "string" : "string";
else return typeof v
}
// DEMO
let types = [null, "", "string", undefined, NaN, Infinity, -Infinity, false, "false", true, "true", 0, 1, -1, 0.1, "test", {var:1}, [1,2], {0: 1, 1: 2, length: 2}]
for(i in types){
console.log("natureof ", types[i], " = ", natureof(types[i], "null", "NaN", "-infinity", "number", "array", "empty=undefined"))
}
I made this very simple function that works wonders:
function safeOrZero(route) {
try {
Function(`return (${route})`)();
} catch (error) {
return 0;
}
return Function(`return (${route})`)();
}
The route is whatever chain of values that can blow up. I use it for jQuery/cheerio and objects and such.
Examples 1: a simple object such as this const testObj = {items: [{ val: 'haya' }, { val: null }, { val: 'hum!' }];};.
But it could be a very large object that we haven't even made. So I pass it through:
let value1 = testobj.items[2].val; // "hum!"
let value2 = testobj.items[3].val; // Uncaught TypeError: Cannot read property 'val' of undefined
let svalue1 = safeOrZero(`testobj.items[2].val`) // "hum!"
let svalue2 = safeOrZero(`testobj.items[3].val`) // 0
Of course if you prefer you can use null or 'No value'... Whatever suit your needs.
Usually a DOM query or a jQuery selector may throw an error if it's not found. But using something like:
const bookLink = safeOrZero($('span.guidebook > a')[0].href);
if(bookLink){
[...]
}
What about optional check with operator ?
for example:
// check mother for null or undefined and
// then if mother exist check her children also
// this 100% sure it support and valid in JS today.
// Apart of that C# have almost the same operator using the same way
if (mother?.children) {
}
else {
// it is null, undefined, etc...
}
Simple Solution for empty values:
function isEmpty(value) {
return (
value === null || value === undefined || value === '' ||
(Array.isArray(value) && value.length === 0) ||
(!(value instanceof Date) && typeof value === 'object' && Object.keys(value).length === 0)
);
}
This is a very non-human code. But works:
if((pass, cpass, email, cemail, user !== null)){
Just try it out and help the answer
Try this:
if (!variable && typeof variable === "object") {
// variable is null
}
This will not work in case of Boolean values coming from DB
for ex:
value = false
if(!value) {
// it will change all false values to not available
return "not available"
}
Checking error conditions:
// Typical API response data
let data = {
status: true,
user: [],
total: 0,
activity: {sports: 1}
}
// A flag that checks whether all conditions were met or not
var passed = true;
// Boolean check
if (data['status'] === undefined || data['status'] == false){
console.log("Undefined / no `status` data");
passed = false;
}
// Array/dict check
if (data['user'] === undefined || !data['user'].length){
console.log("Undefined / no `user` data");
passed = false;
}
// Checking a key in a dictionary
if (data['activity'] === undefined || data['activity']['time'] === undefined){
console.log("Undefined / no `time` data");
passed = false;
}
// Other values check
if (data['total'] === undefined || !data['total']){
console.log("Undefined / no `total` data");
passed = false;
}
// Passed all tests?
if (passed){
console.log("Passed all tests");
}

Categories

Resources