Is there a standard function to check for null, undefined, or blank variables in JavaScript? – Stack Overflow
Posted by jpluimers on 2017/10/11
Yes there is; it’s the answer below. Note I needed to exclude false by adding a check value === false to the code below as that was a valid value for me.
You can just check if the variable has a
truthyvalue or not. That meansif( value ) { }will evaluate to
trueifvalueis not:
- null
- undefined
- NaN
- empty string (“”)
- 0
- false
The above list represents all possible
falsyvalues in ECMA-/Javascript. Find it in the specification at theToBooleansection.Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the
typeofoperator. For instanceif( typeof foo !== 'undefined' ) { // foo could get resolved and it's defined }If you can be sure that a variable is declared at least, you should directly check if it has a
truthyvalue like shown above.Further read: http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html
Thanks to [WayBack] User jAndy – Stack Overflow who answered the above at [WayBack] Is there a standard function to check for null, undefined, or blank variables in JavaScript? – Stack Overflow.
–jeroen






Leave a comment