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;
}
If the variable hasn't been declared, you wont be able to test for undefined using a function because you will get an error.
Both will generate an error if foo has not been declared.
If you want to test if a variable has been declared you can use
if you want to test if foo has been declared and it has a value you can use
but this solution is over-engineered, if you dont'want to modify the function later for busines-model needings, then is cleaner to use it directly in code:
To check Default Value
check Result:
I used @Vix function() to check the object of which type.
using instansof «
This will never throw an error. If myObject, child, or myValue is null then myNewValue will be null. No errors will be thrown
This condition check
is all you need.
This will check if variable of indeterminate nesting is undefined
The above checks if the Google translate function TranslateElement exists. This is equivalent to: