AhmedSC
AhmedSC

Reputation: 7

What is the difference in these two examples about JavaScript scope chain?

var a = 1;

function x() {
    a = 2
    console.log(a) // 2
}
x();

console.log(a); // 2 

and :

var a = 1;

function x(p) {
    p = 2
    console.log(p) // 2
}
x(a);

console.log(a); // 1 

Why is the output of the second example 1 instead of 2?

Upvotes: 0

Views: 46

Answers (2)

Felippe Duarte
Felippe Duarte

Reputation: 15131

It's because your p variable exists only inside function x(p). So, you have a new space in memory, a copy variable a. In the first example, it's a pointer to memory address of variable a.

In other hand, objects have a "pass by reference", so if you do this:

var obj = { foo: 1 };

function x(paramObj) {
    paramObj.foo = "2";
}

x(obj);
alert(obj.foo);

You will see "2" instead of "1".

Upvotes: 2

Azamantes
Azamantes

Reputation: 1451

Because function arguments are 'created' when the function gets executed.

var a = 1;

function x(p) {
    p = 2
    console.log(p) // 2
};

In this piece of code you create global variable a = 1; Then you pass it to the x function. Inside the function you set the given parameter to 2 and console.log it; But what really happens is this:

var a = 1;


function x(given_argument) {
    var p = given_argument;
    p = 2; // global a variable still equals 1;
    console.log(p) // 2
};

This is because there are 2 types of variables in Javascript. Values like number, string, boolean etc that are just values and referential types like arrays, objects.

If you know C++ then this should lighten things up a bit. Here is equivalent of what happens in Javascript, written in C++:

// javascript
var a = 1; // plain value

// c++
int a = 1; // plain value

// javascript
var a = {}; // referential type, this is a pointer behind the scenes
// or
var a = new Object(); // if you prefer it this way

// c++
Object* a = new Object(); // this is a pointer to the object, but in C++ you make it a pointer explicitly, in Javascript this happens 'automagically'.

Referential types in Javascript are pointers, it means they can be changed from inside function, if passed as arguments. But if you pass normal value like number or boolean, it is declared inside the function, and it happens implicitly.

I hope it clarified the problem.

Upvotes: 0

Related Questions