How do I check if a given variable has a value? What is the JS equivalent of PHP's isset?
2 Answers
if (myVariable === undefined) {
// myVariable has not been assigned a value...
}
Also, this same question was asked and answered here on Stackoverflow. See, How can I determine if a JavaScript variable is defined in a page?
2 Comments
sehummel
Is this how you do if it is not undefined? if (myVariable !== undefined) { // myVariable has not been assigned a value... }
Scott Mitchell
@shummel: Sure, that would work. You could also do:
if (!(myVariable === undefined)) { ... }if(typeof variable === "undefined") {
//code here
}