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;
}
It may be usefull.
you can use:
If clause to validate if the string or value is not empty. like this:
You can just check if the variable has a
truthy
value or not. That meanswill evaluate to
true
ifvalue
is not:The above list represents all possible
falsy
values in ECMA-/Javascript. Find it in the specification at theToBoolean
section.Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the
typeof
operator. For instanceIf you can be sure that a variable is declared at least, you should directly check if it has a
truthy
value like shown above.Further read: http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html
! check for empty strings (""), null, undefined, false and the number 0 and NaN. Say, if a string is empty
var name = ""
thenconsole.log(!name)
returnstrue
.this function will return true if val is empty, null, undefined, false, the number 0 or NaN.
If you are using
TypeScript
and don't want to account for "values those arefalse
" then this is the solution for you:First:
import { isNullOrUndefined } from 'util';
Then:
isNullOrUndefined(this.yourVariableName)
Please Note: As mentioned below this is now deprecated, use
value === undefined || value === null
instead. ref.This function check for
empty object {}
,empty array []
,null
,undefined
andblank string ""