1

I have the following code:

console.log(doSomething);
doSomething();

function doSomething() {
    console.log("Declare something");
}

which in the console returns

[Function: doSomething]
Declare something

But when I write

console.log(doSomething());

function doSomething() {
    console.log("Declare something");
}

the console says

Declare something
undefined

I understand why it just says "Declare something" and not "[Function: doSomething]", but why does it say "undefined"? Why does it not say "Declare something Declare something"?

  • The default return value of a function is `undefined` which is what you see there – Sirko Sep 09 '20 at 18:33
  • Does this answer your question? [Chrome/Firefox console.log always appends a line saying undefined](https://stackoverflow.com/questions/14633968/chrome-firefox-console-log-always-appends-a-line-saying-undefined) – JoshG Sep 09 '20 at 18:34

3 Answers3

2

Undefined is the return value of the function. Change your function for this for example to prove it.

function doSomething() {
    console.log("Declare something");
    return "test";
} 
someRandomDev
  • 561
  • 6
  • 15
  • I added `return "Declare something";` and now the console says `Declare something Declare something` as expected. I had assumed that a `console.log` output counted as a return value but now I understand that it does not. Thanks! – HarrisonCarto Sep 09 '20 at 18:40
1

The second log is regarding your console.log(doSomething()); which is printing the return of your function. In this case, you are not returning anything and therefore it prints undefined.

Diogo Santos
  • 780
  • 4
  • 17
0

Thats because you didn't declare the return statement of the function.

sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35