Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript if var exists

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);
};
like image 307
Kristian Matthews Avatar asked Dec 15 '11 23:12

Kristian Matthews


People also ask

How do you check if a variable is exist or not in JavaScript?

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.

How do you check if a variable already exists?

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.

How do you check if a VAR is a number?

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”.

How do you check function is defined or not in JavaScript?

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'.


3 Answers

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?

like image 115
Chango Avatar answered Oct 20 '22 14:10

Chango


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 
}
like image 36
King Friday Avatar answered Oct 20 '22 16:10

King Friday


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.

like image 36
Kristian Matthews Avatar answered Oct 20 '22 15:10

Kristian Matthews