9

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);
};
animuson
  • 53,861
  • 28
  • 137
  • 147
Kristian Matthews
  • 800
  • 3
  • 14
  • 28
  • possible duplicate of [Detecting an undefined object property in JavaScript](http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript) – Lee Gary Apr 01 '14 at 03:44

6 Answers6

7
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?

Chango
  • 6,754
  • 1
  • 28
  • 37
  • So if var YouTube=EpicKris; did not exist or if var YouTube=null; or YouTube=0; then no errors should occur and the rest of the JavaScript code should run? – Kristian Matthews Dec 15 '11 at 23:22
  • Ups, ignore my answer, is buggy, gurung's is better! – Chango Dec 15 '11 at 23:28
  • Well, I fixed it with gurung's answer. Now it will execute the code as long as YouTube exist and is not null, 0 or an empty string. Does this answer work for you? – Chango Dec 15 '11 at 23:34
  • Partially, however I'm looking for a simple bit of code that does this but also works if var YouTube=EpicKris; does not exist. – Kristian Matthews Dec 15 '11 at 23:37
  • If the variable EpicKris does not exist? it should work. Just make the assignment inside the try/catch block. – Chango Dec 15 '11 at 23:40
  • well why did you put a semi colon after the if? and why do you think try-catch is a good idea? try catch is really saying "i don't know" so I'll put the code in there. – King Friday Dec 15 '11 at 23:42
  • I've not come across try catch before so I don't completely understand what it is doing. – Kristian Matthews Dec 15 '11 at 23:47
6

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 
}
King Friday
  • 25,132
  • 12
  • 90
  • 84
  • 3
    That won't work if you are in a different scope. I don't recommend doing that. – regality Dec 15 '11 at 23:23
  • Yes, I should have also mentioned, doing any object qualifier as root say you have an object "something = {}" then you check if "something.x" that won't puke either. I had to do this when writing boostrapping plugins such as window.myThing = window.myThing || {}; etc etc. IE is the real reason for this as IE is retarded, even at v9. – King Friday Dec 15 '11 at 23:23
  • So if var YouTube=EpicKris; did not exist then no errors should occur and the rest of the JavaScript code should run? – Kristian Matthews Dec 15 '11 at 23:24
  • This is checking the existence of "YouTube" living on the window object. If it exists, it will do the code within assuming the variable isn't 0 or false or null or undefined or some other falsy value. – King Friday Dec 15 '11 at 23:25
  • Actually it will work everywhere, unless you overwrite the window object. This is JavaScript on the browser, not in some vacuum. This is assuming his scope is root as he didn't write a closure anyway. Going deep in the closures, it will be slightly slower. – King Friday Dec 15 '11 at 23:28
  • 1
    +1 I use this method frequently when testing for the existence and non-falsey value of a global variable. It works in all browsers if the variable you're testing for is global. – jfriend00 Dec 15 '11 at 23:40
3

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.

Kristian Matthews
  • 800
  • 3
  • 14
  • 28
1

What about using try/catch:

try {
    //do stuff
} catch(e) { /* ignore */ }
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
  • Could you explain this to me? – Kristian Matthews Dec 15 '11 at 23:30
  • This approach does work everywhere but its is the equivalent of saying "I don't know how this works so I'll put in some code there". This should be done when you know something can fail based on user or network or something outside of your control in most cases. Typically not things that you understand why they break and are in your control. – King Friday Dec 16 '11 at 17:38
  • @emeraldcode.com: Ah, I was thinking that the OP wanted to know I how to implement it. And I assumed that he knew what a `try/catch` was meant to do. But Thanks for the explanation, it's great. I am pretty sure it will help OP understand what's going on (assuming that he had never heard of `try/catch` before). – Bhesh Gurung Dec 16 '11 at 18:14
0

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
    }
}
rafa ble
  • 33
  • 3
0

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

}
Luan Castro
  • 1,184
  • 7
  • 14