Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined
or null
? I've got this code, but I'm not sure if it covers all cases:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
I think using try catch will avoid any error of null check, also in Angular or JavaScript Just catching null exception and process in it.
You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
The verbose method to check if value is undefined or null is:
You can also use the
==
operator but this expects one to know all the rules:For everyone coming here for having similar question, the following works great and I have it in my library the last years:
I think using the ? operator is slightly cleaner.
I will leave a registered solution that I liked a lot:
First let's define that a blank variable is
null
, orundefined
, or if it has length, it is zero, or if it is an object, it has no keys:Returns:
undefined
,null
,""
,[]
,{}
true
,false
,1
,0
,-1
,"foo"
,[1, 2, 3]
,{ foo: 1 }