JavaScript if var exists

Kristian Matthews picture Kristian Matthews · Dec 16, 2011 · Viewed 17.8k times · Source

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

Answer

Chango picture Chango · Dec 16, 2011
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?