460

How to check whether a JavaScript variable defined in cross-browser way?

I ran into this problem when writing some JavaScript utilizing FireBug logging. I wrote some code like below:

function profileRun(f) {
    // f: functions to be profiled
    console.profile(f.constructor);
    f();
    console.profileEnd(f.constructor);
}

It works fine in FireFox/FireBug, but it reports error in IE8 RC1. So, I'd like to do some checking whether console variable exists in the execution environment.

Below code works fine in FireFox, but not in IE8 RC1.

function profileRun(f) {
    if (console != undefined) {
        console.profile(f.constructor);
    }

    f();

    if (console != undefined) {
        console.profileEnd(f.constructor);
    }
}

However, if I do it this way. It works in IE8 RC1. Why?

function profileRun(f) {
    if (window.console != undefined) {
        console.profile(f.constructor);
    }

    f();

    if (window.console != undefined) {
        console.profileEnd(f.constructor);
    }
}

Is there any cross-browser way to check it?

John Bachir
  • 22,495
  • 29
  • 154
  • 227
Morgan Cheng
  • 73,950
  • 66
  • 171
  • 230
  • Why was this marked as a duplicate? I don't understand. This question is 2 years older, has more votes and views, and not any worse than the other question. – Cruncher Jun 24 '14 at 14:42
  • That's a good question, @Cruncher - but all things being equal, the other question is *shorter* so I'm merging to preserve the answers and provide a redirect. – Shog9 Jul 25 '14 at 16:35

0 Answers0