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);
};

Upvotes: 9

Views: 18053

Answers (6)

Luan Castro
Luan Castro

Reputation: 1184

it's easy... you can do it on 2 ways

var YouTube = window["EpicKris"] ;// or this["EpicKris"] or objectContainer["EpicKris"]

if( YouTube ) { //if is null or undefined (Zero and Empty String too), will be converted to false

    console.log(YouTube);// exists

}else{

    consol.log(YouTube);// null, undefined, 0, "" or false

}

or you can be

var YouTube = window["EpicKris"] ;// or this["EpicKris"] or objectContainer["EpicKris"]

if( typeof YouTube == "undefined" || YouTube == null ) { //complete test

    console.log(YouTube);//exists

}else{

    console.log(YouTube);//not exists

}

Upvotes: 0

King Friday
King Friday

Reputation: 26076

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 
}

Upvotes: 6

rafa ble
rafa ble

Reputation: 33

I believe this is what you may be looking for:

if (typeof(YouTube)!=='undefined'){
    if (YouTube!==undefined && YouTube!==null) {
        //do something if variable exists AND is set
    }
}

Upvotes: 0

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.

Upvotes: 3

Chango
Chango

Reputation: 6782

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?

Upvotes: 7

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

What about using try/catch:

try {
    //do stuff
} catch(e) { /* ignore */ }

Upvotes: 1

Related Questions