3

Here is the code-

function setOptions(obj, options) {
    if (!obj.hasOwnProperty('options')) {
        obj.options = obj.options ? create(obj.options) : {};
    }
    for (var i in options) {
        obj.options[i] = options[i];
    }
    return obj.options;
}
var x={};
setOptions(x, {prop1:2});
console.log(x);
setOptions(x,{prop1:3});
console.log(x); 

I expected that the first setOptions() call should assign a prop1:2 property to x . And second setOptions() call will reassign prop1 as 3. According to my assumption, the output should be-

 first console.log output - {prop1:2} 
 second console.log output - {prop2:3} 

But it is printing the following stuff in web console-

 first console.log output - {prop1:3} 
 second console.log output - {prop2:3}

What am I missing in my assumption?

APL
  • 353
  • 2
  • 16
  • 4
    Nothing, it's due to unintuitive browser handling of logging objects live. Try `console.log(JSON.stringify(x))` instead. – CertainPerformance May 08 '18 at 06:13
  • 1
    This is one of the reasons not to stumble around in the dark with a `console.log` torch when you can *turn on the lights* with a debugger. :-) Stepping through with the debugger built into your browser or IDE would show you that the code is doing what you expect it to do, whereas (as CertainPerformance pointed out), `console.log`'s deferred evaluation can catch you out. (When you *have* to use `console.log`, to log something as of a certain point in time, often `console.log(JSON.stringify(theThing));` is useful.) – T.J. Crowder May 08 '18 at 06:17
  • Thank you so much . :-) – APL May 08 '18 at 06:20

0 Answers0