console.log() is not working on all browser

1.3k views Asked by At

I've recently had a strange issue, where console.log doesn't output anything if used inside my code but work fine using directly in the console or using window.console.log.

window.console.log(console);
window.console.log(window.console);
console.log("test1"); // (won't work)
window.console.log("test2");

Ouput:

enter image description here

If i define console myself the console before the code:

var console = window.console;
window.console.log(console);
window.console.log(window.console);
console.log("test1");
window.console.log("test2");

Ouput:

enter image description here


And the strangest thing, if i define console myself after the code

window.console.log(console);
window.console.log(window.console);
console.log("test1");
window.console.log("test2");
var console = window.console;

Ouput:

enter image description here

Note before answering:

  1. It's not a browser-specific issue because the output is the same on every browser (i've checked on chrome/firefox/safari/opera).

  2. It's not being overridden because a log of console & window.console return the same exact object (see screenshot).

2

There are 2 answers

0
Evgeniy Generalov On

This is one of the amazing features of the JavaScript. The var directive is processed on the pre-execution stage. So this code:

function foo() {
    window.console.log(console);
    var console = window.console;
    window.console.log(console);
}

is equivalent to:

function foo() {
    var console;
    window.console.log(console); // console is local variable and undefined
    console = window.console;
    window.console.log(console);
}
0
kirkas On

I found the reason why.. In our grunt uglify function (grunt-contrib-uglify), we use the drop_console options for compress:

uglify: {
    options: {
      compress: {
          drop_console: true
      }
    }, 
// ...

Which obviously drop any appearance of console but strangely doesn't drop window.console.