re: 10 JavaScript concepts you need to know for interviews VIEW POST

VIEW PARENT COMMENT VIEW FULL DISCUSSION

Interesting distinction, and thanks for clearing that up!

I was curious what would happen if you did something like this

    var o = { p: 'foo' };
    (function(o) {
        o = { x: 'bar' };
    })(o)
    console.log(o);

This is weird at first glance to me because while, yes, you're passing in o to the closure, when you set o to {x: 'bar'}, which o are you talking about; is it the o outside the function?

This becomes a bit more of a scoping issue. But the solution is that the o inside the function is still a separate variable from the o outside the function, because it was "declared" separately as an argument (function(o)). So the final output is still { p: 'foo' }

If you change it to this:

    var o = { p: 'foo' };
    (function(z) { //note now we've declared 'z', and there's no 'o' in the inner function
        o = { x: 'bar' }; //because there's no 'o' inside here, we use the 'o' defined in line 1
    })(o)
    console.log(o);

o gets changed! Because it was never redeclared inside the function. So the final output here is: { x: 'bar' }

This has nothing to do with pass-by-reference issue! it's about scoping

code of conduct - report abuse