Reputation: 4818
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:
Upvotes: 1
Views: 173
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 undefined
s.
HTH
PS: undefined
s sounds funny :)
Upvotes: 2
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