DEV Community


Discussion on: 10 JavaScript concepts you need to know for interviews

washingtonsteven profile image
Steven Washington • Edited

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' };

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 gets changed! Because it was never redeclared inside the function. So the final output here is: { x: 'bar' }

pildit profile image

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

Forem Open with the Forem app