1

I have a newby question in Javascript. If I call console.log(something) before the following MyInit function is called (in a simple html page), I get an exception because console is not defined. That's ok. But I don't see what the MyInit function does to make it work: It looks like it is defining the log function as something empty that does nothing. How does it get from the definition I provide to the actual console log function that writes to the console?

function MyInit()
{
  if (!window.console) console = { log: function () { } };
}
...

<!-- later -->

console.log("OnMouseOver occurred.");

1 Answer 1

1

To break down MyInit():

if (!window.console)           // If `window` does not have a `console` property
    console = {                // Declare `console` object
        log:                   // Add `log` key
            function () { } }; // ...which is a function which does nothing

What this will do is allow console and console.log to be referenced without any errors being thrown. console.log("OnMouseOver occurred."); will simply do nothing on browsers which do not support window.console by default.

To show this more clearly I've created a JSFiddle demo which reverses this method. In this demo we detect if window.console is supported, and if it is we set override console.log to instead equal this empty function. When you run this, you'll see that our console.log("Hello, world!") call doesn't log anything to the console, but it equally doesn't throw any errors about either being undefined.

In short, MyInit() doesn't make it work, it simply creates a console.log function which doesn't do anything whatsoever.

Sign up to request clarification or add additional context in comments.

1 Comment

Am I right here (scope is very different from C++/C#): In globabl scope, look at these two statements: (A) if (!window.console) window.console = <foo>. (B) if (!window.console) console = <foo>. These are the same because the second version sets console on the global scope, which is then a member of window. But this third version fails: (C) if (!console) console = <foo>. because the if statement references an undefined console variable, before it has been assigned anything. In other words, I can test a member of an attribute (window.console) but not an undefined variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.