I want my code so that if a specific var exists it will perform an action, else it will be ignored and move along. The problem with my code is, if the specific var does not exist it causes an error, presumably ignoring the remainder of the JavaScript code.
Example
var YouTube=EpicKris;
if ((typeof YouTube) != 'undefined' && YouTube != null) {
document.write('YouTube:' + YouTube);
};
The typeof operator will check whether a variable is defined or not. The typeof operator doesn't throw a ReferenceError exception when it is used with an undeclared variable. The typeof null will return an object.
Answer: Use the typeof operator If you want to check whether a variable has been initialized or defined (i.e. test whether a variable has been declared and assigned a value) you can use the typeof operator.
In JavaScript, there are two ways to check if a variable is a number : isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false. typeof – If variable is a number, it will returns a string named “number”.
Using the typeof Operator When we use the function name as the operand of the typeof variable, it returns the 'function' string, and we can check whether the function is defined. If function is not defined, typeof operator returns the 'undefined'.
try {
if(YouTube) {
console.log("exist!");
}
} catch(e) {}
console.log("move one");
Would work when YouTube is not null, undefined, 0 or "".
Does that work for you?
This is a classic one.
Use the "window" qualifier for cross browser checks on undefined variables and won't break.
if (window.YouTube) { // won't puke
// do your code
}
OR for the hard core sticklers from the peanut gallery...
if (this.YouTube) {
// you have to assume you are in the global context though
}
Code:
var YouTube=EpicKris;
if (typeof YouTube!='undefined') {
document.write('YouTube:' + YouTube);
};
Worked out the best method for this, use typeof to check if the var exists. This worked perfectly for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With