Dean
Dean

Reputation: 751

Defining console in Javascript

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.");

Upvotes: 1

Views: 133

Answers (1)

James Donnelly
James Donnelly

Reputation: 128771

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.

Upvotes: 1

Related Questions