Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome/Firefox console.log always appends a line saying 'undefined'

Every time console.log is executed, a line saying undefined is appended to the output log.

It happens in both Firefox and Chrome on Windows and Linux.

like image 638
N. Chamaa Avatar asked Jan 31 '13 19:01

N. Chamaa


People also ask

Why does Chrome console say undefined?

If a function does not use a return statement or an empty return statement with no value, JavaScript automatically returns undefined.

How do I add console log to my browser?

Adding a console log is something Google recently add. In the selected row instead of left click,click right click and select 'add logpoint', a small text box will pop up, enter the variable you want you console log. If you do not see this feature update your browser. Thanks for the answer!

What is console log in browser?

The console. log() method outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects. Note: This feature is available in Web Workers.


2 Answers

If you're running console.log() from a JS file, this undefined line should not be appended.

If you're running console.log() from the console itself, it makes sense. This is why: In the console you can type a name of a variable (for example try typing window) and it prints info about it. When you run any void function (like console.log) from the console, it also prints out info about the return value, undefined in this case.

I tested both cases on my Chrome (Mac ver 23.0.1271.101) and indeed I see the undefined line when I run it inside the console. This undefined also appears when I write this line in the console: var bla = "sdfdfs"

like image 102
talkol Avatar answered Oct 10 '22 16:10

talkol


Although talkol´s answer is ok, I try to put it more straight:

JavaScript is designed as a dynamic language which means that the type (string, void, boolean …) of a function return value is not pre-defined. If a function does not use a return statement or an empty return statement with no value, JavaScript automatically returns undefined. That means that in JavaScript every function returns something, at least undefined.

So the function console.log() in Chrome console either uses no or an empty return statement, so that the return value of this function is undefined. This function return value gets also displayed in the Chrome console.

[If somebody know where to find the definition of the console.log() function in Google Chrome source code, please comment with the link, then we can even go further and look at the real code, would be nice.]

Sources:

  • https://stackoverflow.com/a/20915524/1744768
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
like image 27
Paul Vincent Beigang Avatar answered Oct 10 '22 16:10

Paul Vincent Beigang