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;
}
is a really nice and clean way to handle it in a lot of places, can also be used to assign variables
You may find the following function useful:
Or in ES7 (comment if further improvements)
Results:
"Note that the bind operator (::) is not part of ES2016 (ES7) nor any later edition of the ECMAScript standard at all. It's currently a stage 0 (strawman) proposal for being introduced to the language." – Simon Kjellberg. the author wishes to add his support for this beautiful proposal to receive royal ascension.
In ES6 with trim to handle whitespace strings:
This will return true for
and zero argument functions since a function's
length
is the number of declared parameters it takes.To disallow the latter category, you might want to just check for blank strings
This is a very simple one.
Here's mine - returns true if value is null, undefined, etc or blank (ie contains only blank spaces):