Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save junaidtk/c081c8c8695c45e70b32f634a37fc9b8 to your computer and use it in GitHub Desktop.
Save junaidtk/c081c8c8695c45e70b32f634a37fc9b8 to your computer and use it in GitHub Desktop.
Check a javascript variable is valid one
In javascript, to check a variable contain a valid data or not, we can use the below code.
var value;
if(value){
// do something
}
If the variable doesn't contain a valid value it may have following 6 type of content.
This checking will valid if the variable is already defined.
null
undefined
NaN
empty string ("")
0
false
if the value is an array you need to check the length of value is not equal to zero.
(value.length != 0).
The safest way to check the variable is valid.
if (typeof value != 'undefined' && value) {
// Do something
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment