learner
learner

Reputation: 4818

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

Upvotes: 1

Views: 173

Answers (2)

Harsh Gupta
Harsh Gupta

Reputation: 4538

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 :)

Upvotes: 2

Vic
Vic

Reputation: 723

Chrome's Console intended to return the last function of your code block. But since there was nothing to return, it outputs undefined.

Here's some proof.

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

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

a();
b();

Upvotes: 2

Related Questions