I was experimenting with JavaScript and I ended up with this snippet:
var num = new Number(20);
function f(n) {
n["foo"] = "bar";
}
// the printed object has a "foo" property.
console.log(num, f(num));
I never thought the printed object would have the foo
property added to it in the f(num)
call, because f(num)
comes after the num
in my console.log
(I am using Chrome).
But that happened and my immediate thought was that console.log
was sort of running all the arguments and printing out the results or something, so I went over to MDN's documentation for console.log
, but there wasn't anything about that.
Then I stumbled upon this StackOverflow question.
The second and third questions say that console.log
is a little late when used with objects, but in that case, the printed object in the following snippet should have had a foo
property as well (since it is a Number
object), it doesn't:
var num = new Number(20);
function f(n) {
n["foo"] = "bar";
}
// no "foo" property
console.log(num);
f(num);
The accepted answer to the question I mentioned pretty much says what the second and third answer say, except, it also states that the behavior is console or browser dependent. So, how do different browsers treat this sort of thing nowadays (that question is from 6 years ago) ? Is console.log
asynchronous for extremely large objects only ? And the original question, why does the num
in my first example get printed out with a foo
property ?