First Example:
In the following example: http://jsfiddle.net/maniator/ScTAW/4/
I have this js:
var storage = (function () {
var store = [];
return {
"add": function (item) {
store.push(item);
},
"get": function () {
return store;
}
};
}());
storage.add('hi there')
console.log(storage, storage.get(), storage.add('hi there #2'));
And here is what gets printed to the console:
Object
[“hi there”, “hi there #2”] undefined
One would think that the console should only say:
Object
[“hi there”] undefined
becase the second push did not happen until after the value was logged, therefore it should not be displayed.
Second Example:
In the following example: http://jsfiddle.net/maniator/ScTAW/5/
I am using the same storage variable but I log like so:
storage.add('hi there')
console.log(storage, storage.get(), (function() {
storage.add('hi there #2');
console.log('TESTING');
})());
What gets printed to the console is:
TESTING
Object
[“hi there”, “hi there #2”] undefined
hmmmm well that is odd now isnt it? One could expect to see:
Object
[“hi there”] undefined
TESTING
Why is this happening? What is going on behind the scenes of the console logging mechanism?
In most (if not all) imperative programming languages, any arguments passed to a function call have to be evaluated before the function can be called (so called Eager evaluation). Also, they are in general evaluated in order from left to right (for C for instance it’s undefined), however in both examples the order in which the arguments are evaluated does not matter. This should be pretty obvious when looking at what happens in detail:
As mentioned, before
console.logcan be called,storage.get()has to be executed first, returning thestorearray. Thenstorage.add('hi there #2')will be executed (or the other way round), so its result (in this caseundefined, sinceadddoes not return anything) can be passed as the third argument toconsole.log. This means that the onceconsole.logwill be called with the arguments(storage, storage.store, undefined), thestorearray already contains “hi there #2”, hence producing the results you observe.In the second example the reasoning is again the same, the function call is just a bit more obscured. On first look it looks there is a function passed as a 3rd argument to the
console.logfunction; but it’s actually a function call (observer the()at the end). Sostorage.add('hi there #2')will be executed, thenconsole.log('TESTING')and then theundefinedresult from the anonymous function execution will be again passed toconsole.log.If you did actually pass a function to
console.log, it would print that function definition, and not execute anything. So:, without the
()at the end, results in:I hope this makes things a bit clearer.