is there something like isset of php in javascript/jQuery? [duplicate]
Is there something in javascript/jQuery to check whether variable is set/available or not? In php, we use isset($variable)
to check something like this.
thanks.
Solution 1:
Try this expression:
typeof(variable) != "undefined" && variable !== null
This will be true if the variable is defined and not null, which is the equivalent of how PHP's isset works.
You can use it like this:
if(typeof(variable) != "undefined" && variable !== null) {
bla();
}
Solution 2:
JavaScript isset() on PHP JS
function isset () {
// discuss at: http://phpjs.org/functions/isset
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: FremyCompany
// + improved by: Onno Marsman
// + improved by: Rafał Kukawski
// * example 1: isset( undefined, true);
// * returns 1: false
// * example 2: isset( 'Kevin van Zonneveld' );
// * returns 2: true
var a = arguments,
l = a.length,
i = 0,
undef;
if (l === 0) {
throw new Error('Empty isset');
}
while (i !== l) {
if (a[i] === undef || a[i] === null) {
return false;
}
i++;
}
return true;
}
Solution 3:
typeof will serve the purpose I think
if(typeof foo != "undefined"){}
Solution 4:
If you want to check if a property exists: hasOwnProperty is the way to go
And since most objects are properties of some other object (eventually leading to the window
object) this can work well for checking if values have been declared.
Solution 5:
Not naturally, no... However, a googling of the thing gave this: http://phpjs.org/functions/isset:454