-1

I am trying to understand what is happening when I call console.log within another console.log(), like so:

console.log(console.log("Hello"));

My results are:

Hello
undefined

What is the outer console.log() trying to show that is undefined?

Vaibhav Mule
  • 5,016
  • 4
  • 35
  • 52
jabe
  • 784
  • 2
  • 15
  • 33

6 Answers6

2

The first call of console.log("Hello") prints "Hello" and returns undefined value to the next call. Thus the order is

Hello // from console.log("Hello");
undefined // from console.log(undefined);
Artyom Neustroev
  • 8,627
  • 5
  • 33
  • 57
1

The return value of console.log("Hello") : "void" is about the same as "undefined" in javascript

xerx593
  • 12,237
  • 5
  • 33
  • 64
1

console.log() returns nothing, it just prints to the console. Thus, you are trying to log an undefined value.

As you can see below, we mimic the behavior of console.log with a document.write. The second value is undefined, as expected:

document.write(document.write("Hello"));
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
1

Basically

typeof console = "object"
typeof console.log = "function"
typeof console.log("Hello") = "undefined"

So the first console.log(x); has an undefined where there is an x.

thysultan
  • 340
  • 3
  • 10
1

Its because you are writing this code in console and console.log() is not return any value. if you write same code in any function then you get different result

for E.g

function test()
{
console.log("test")
return 1;
}

Now when you execute test() function in console you will get

test
1

and if you define another function with not return type..

  function test2()
    {
    console.log("test")
    }

Then you get

test
undefined
Anant Dabhi
  • 10,864
  • 3
  • 31
  • 49
1

If a JavaScript method does not have a explicit return then it returns undefined object. console.log according to chrome looks like:

console.log(object [, object, ...])

So, the inner console.log('Hello') //Print output browser console but it returns undefined so outer console.log is printing undefined.

KrishnaDhungana
  • 2,604
  • 4
  • 25
  • 37