Object are passed with their reference in javascript. Meaning change in that object from any where should be reflected. In this case, the expected output was {} for console.log(a)
function change(a,b) {
a.x = 'added';
a = b;//assigning a as {} to b
}
a={}
b={}
change(a,b);
console.log(a); //expected {} but output {x:'added'}
console.log(b)
What is happening here? It should not be because of functional scope as far as I know. Thank you
Block Level Scope: This scope restricts the variable that is declared inside a specific block, from access by the outside of the block. The let & const keyword facilitates the variables to be block scoped.
In JavaScript, objects and functions are also variables. Scope determines the accessibility of variables, objects, and functions from different parts of the code.
JavaScript uses lexical scope which means that scope of variables is determined at compile time.
JavaScript has two scopes: global and local. Local scope has two variations: the old function scope, and the new block scope introduced with ES6. It's worth noting that function scope is actually a special type of a block scope.
If you added another line you can get a clearer picture of what is happening:
function change(a,b) {
a.x = 'added';
a = b;
a.x = 'added as well';
};
a={};
b={};
change(a,b);
console.log(a); //{x:'added'}
console.log(b); //{x:'added as well'}
When you're doing a = b
you're assigning the local variable a
to the reference that b
is holding.
You are right that objects are passed by reference and any change made to the object in the function will be reflected everywhere. This is precisely why adding the x
property in the function modified the object outside of it.
What you are missing is that the line a = b;
does not modify the object, it modifies the reference to the object. You can pass both of the objects in another container object / array if you need to set the reference:
function change(container) {
container.a.x = 'added';
container.a = container.b;//assigning a as {} to b
}
var container = { a: {}, b: {}};
change(container);
console.log(container.a);
console.log(container.b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With