-1

Why does calling console.log()

function test1() {
  console.log('test1')
}

// or ES6
const test2 = () => { console.log('test2') }

Give the same results as returning console.log()

function test3() {
  return console.log('test3')
}

// or ES6
const test4 = () => console.log('test4')

test1() // -> test1 undefined
test2() // -> test2 undefined
test3() // -> test3 undefined
test4() // -> test4 undefined

While I understand a function without an explicit return will always return undefined, it seems counter-intuitive to me that returning the result of console.log() gives the exact same output.

skube
  • 5,867
  • 9
  • 53
  • 77
  • 6
    What value are you expecting `console.log` to return and why? – David Aug 25 '20 at 11:45
  • 1
    Well, `console.log()` does return `undefined`? You can alternatively write `function test5() { console.log('test5'); return undefined; }` and it will be indistinguishable from the outside. – Bergi Aug 25 '20 at 11:49

2 Answers2

1

I think you shall get a better understanding by looking at this:

const realConsoleLog = console.log
console.log = (...val) => {
  realConsoleLog(...val)
  return val
}
const noReturn = () => { console.log('yep') }
const doesReturn = () => console.log('yep')
const a = noReturn()
const b = doesReturn()
console.log(`a is ${a}`)
console.log(`b is ${b}`)

If you ran the program, you'll notice that the noReturn() and doesReturn() functions get executed when you assign them to variables. So in the first case, the function is executing its block and then returns nothing, therefore a is undefined. But in the doesReturn function, you are actually executing the console.log method, which we've tweaked to return all the original arguments, and then returning the variable which the console.log returns. Since the original console.log does not return anything, so you get undefined as the answer.

Pranav
  • 674
  • 1
  • 6
  • 23
0

Javascript does not have void return type specification, so whenever any executing context stops if there is no such explicit return, undefined will get returned.

To justify - void in JavaScript is an operator that evaluates the expression next to it. No matter which expression is evaluated, void always returns undefined

You can get this idea that whenever you use console in your browser, and even if you assign a value to a variable, you will see undefined get returned which is from main thread execution context return

Found this answer which has a good explanation to relate - Why do functions return `undefined` instead of `null` by default?

Satyam Pathak
  • 6,612
  • 3
  • 25
  • 52