9

I used the Chrome Console to write a simple statement:

console.log(4)

and received the Output:

4

undefined

What does the undefined statement mean? Does the undefined statement imply correct execution? If I execute the statement via a separate html file and then look at the console, the output is just 4.

AnthonyS
  • 2,429
  • 2
  • 24
  • 17
  • 1
    possible duplicate of [Chrome/Firefox console.log always prepends a line saying undefined](http://stackoverflow.com/questions/14633968/chrome-firefox-console-log-always-prepends-a-line-saying-undefined) – Bergi Jun 02 '15 at 20:51
  • not sure that this can be a duplicate if it was asked in '12, and the one you linked was asked in '13... – Zoran P. Jun 05 '15 at 09:17
  • I believe `Which thread has better and clear-cut answers` is also a criterion while marking a question as duplicate. It is a way of better consolidation of related threads on SO. – RBT Sep 20 '17 at 02:55

2 Answers2

11

The undefined is the return value of console.log(...).

You can see this by defining two functions in the console, one returning something, and the other returning nothing, e.g. like this:

function f1() {
  return 1;
}
function f2() {
  return;
}

And then calling them separately (manually)

f1(); // shows '1'

and

f2(); // shows 'undefined'

Also note the little symbol before these return value string.

Bart
  • 2,062
  • 15
  • 19
  • Oh cool. Is this featured implemented as such for debugging purposes? – AnthonyS Jun 19 '12 at 23:20
  • interesting: apparently the console gives you the most recent return value, so if you call f2(); f1(); the output is just 1 – AnthonyS Jun 19 '12 at 23:27
  • By calling them after each other on the same line, you're effectively discarding the first result. By the way, if you just put `var x = f1();`, you'll also see `1`, because the result of that expression is still `1`. Which is why statements like `x = y = z = f1()` work. – Bart Jun 20 '12 at 07:42
  • @Bart - For me 'var x = f1();' in the console still gives me undefined. But of course just f1() returns 1 like it should. – renegadeofunk Jun 16 '13 at 20:02
  • Hmm apparently calling `var x=f1();` gives `undefined` while calling `x=f1()` (i.e. without the `var` keyword) gives `1`. Not sure if this is new behavior since my previous comment or if I simply missed it. Thanks for noting this. – Bart Jul 02 '13 at 12:53
0

I've tested it and even with a preset variable it did not work in my Safari:

i = 2;
console.log(i);

This seems to explain the bug that WebKit (engine of both Chrome and Safari) has: Link