frenchie
frenchie

Reputation: 51937

javascript: passing global var to function

I have a global variable MyGlobalVar and some code that looks like this:

var MyGlobalVar = null;

function PlayWithMyGlobal() {
    MyGlobalVar = new Object();
    .... adding properties to MyGlobalVar
    MoreFun(MyGlobal);
}

function MoreFun(TheVar) {
    is TheVar here a local or just a reference to the global?
} 

If I pass the global variable, am I still working with the global? Thanks.

Upvotes: 0

Views: 223

Answers (3)

Sarfraz
Sarfraz

Reputation: 382696

If I pass the global variable, am I still working with the global? Thanks.

It depends whether variable you pass is an object or a primitive (number, string, boolean, undefined, null are primitives) value in the first place. Objects are passed by reference and primitives by value.

In your case, you are passing object:

MyGlobalVar = new Object();

And in JS, objects are passed by reference. So you are still working on that variable.

You can confirm it like this:

var MyGlobalVar = null;

function PlayWithMyGlobal() {
    MyGlobalVar = new Object();
    MoreFun(MyGlobalVar);
}

function MoreFun(TheVar) {
    MyGlobalVar.foo = 'I am foo'; // property created here
}

PlayWithMyGlobal();
console.log(MyGlobalVar.foo); // I am foo

Upvotes: 5

Rob W
Rob W

Reputation: 349012

If the global variable is an object, then you're still working with the global variable. Otherwise, it's a copy.

As shown and annotated below, your variables point to the same global object.

var MyGlobalVar = null;

function PlayWithMyGlobal() {
    MyGlobalVar = new Object(); // <--- Object
    MoreFun(MyGlobalVar); // <--- Passing object reference
}

function MoreFun(TheVar) {
    TheVar.test = 'Did I modify global?';
    alert(TheVar === MyGlobalVar); // true
    alert(MyGlobalVar.test);       // "Did I modify global?"
} 

Upvotes: 2

user1106925
user1106925

Reputation:

Yes, you have a local reference to the same object that is referenced globally.

A simple test would be...

console.log(MyGlobalVar === TheVar); // should be true

Upvotes: 1

Related Questions