Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope in javascript acting weird

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

like image 821
Suman Lama Avatar asked Jun 19 '15 05:06

Suman Lama


People also ask

What is blocked scope in JavaScript?

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.

What does scope do in JavaScript?

In JavaScript, objects and functions are also variables. Scope determines the accessibility of variables, objects, and functions from different parts of the code.

What kind of scope does JavaScript use?

JavaScript uses lexical scope which means that scope of variables is determined at compile time.

What are the two different scopes in JavaScript?

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.


2 Answers

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.

like image 143
Jesse Kernaghan Avatar answered Sep 25 '22 00:09

Jesse Kernaghan


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)
like image 21
Nikola Dimitroff Avatar answered Sep 22 '22 00:09

Nikola Dimitroff