learner learner - 9 months ago 28
Javascript Question

Only one undefined is printed while using console.log twice in two functions

I have following piece of code:

function a()
{
x = 2;
console.log(x);
}

function b()
{
x = 4;
console.log(x);
}

a();
b();


What am I expecting as output is:

2
undefined
4
undefined


but the output I got is:

2
4
undefined


where is one of the undefined?
Screenshot from chrome console:

Screenshot

Answer Source

In consoles like the one in Chrome, when a code or a code block is executed, it is treated as a single function that must return something. When you run this block:

a()
b()

console is treating it like:

(function() {
  a()
  b()
})()

And of course it is not returning anything.

If you call those functions individually, you will see 2 undefineds.

HTH

PS: undefineds sounds funny :)