2

My issues with global variable in JavaScript

Hello everyone, I am facing an issues with global variable in JavaScript. My issues as given below.

Why the global variable "g_MobileAssociatedPlans" is getting updated whenever I modifying the other input variable "data".

var g_MobileAssociatedPlans = "";

$(function () {
    var data = { "Item1": "Burger", "Item2": "Soft Drink" };

    displayMobileDevices(data);
});

function displayMobileDevices(data) {

    g_MobileAssociatedPlans = data;

    alert(JSON.stringify(g_MobileAssociatedPlans));

    data.Item1 = "Wine";

    alert(JSON.stringify(g_MobileAssociatedPlans));
}

Please see the above example and review it and revert me the issues. Thank you!

captainsac
  • 2,484
  • 3
  • 27
  • 48
Raju Chauhan
  • 43
  • 1
  • 1
  • 8
  • 1
    Within your `displayMobileDevices` function, you assign the reference of `data` to the `g_MobileAssociatedPlans` so whenever `data` changes, so will `g_MobileAssociatedPlans`. – Anthony Forloney Jun 10 '15 at 11:36
  • what is your problem ? i can't find any problems here..what is the issue? and also data is not a varibale it is an object.and the objects are passed by reference – Arunprasanth K V Jun 10 '15 at 11:37

4 Answers4

2

Because you are assigning object not value,it will be assigning object reference, for getting the desired output you have to clone the object

g_MobileAssociatedPlans = JSON.parse(JSON.stringify(data));

Or

g_MobileAssociatedPlans = jQuery.extend({}, data);

Fiddle

Arunprasanth K V
  • 20,733
  • 8
  • 41
  • 71
Balachandran
  • 9,567
  • 1
  • 16
  • 26
1

You are passing the reference. Not value. Only primitive types (like numbers, boolean) can be passed by reference. And, Objects are passed by value. If you don't want reference, clone the object.
The easiest way to clone JSON object is JSON.parse(JSON.stringify(originalObject)).
refer to What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
Navaneeth
  • 2,555
  • 1
  • 18
  • 38
1

Please update your code like below

var g_MobileAssociatedPlans = "";
$(function () {
    var data = { "Item1": "Burger", "Item2": "Soft Drink" };
    displayMobileDevices(data);
});

function displayMobileDevices(data) {
    g_MobileAssociatedPlans = JSON.parse(JSON.stringify(data));
    alert(JSON.stringify(g_MobileAssociatedPlans));
    data.Item1 = "Wine";
    alert(JSON.stringify(g_MobileAssociatedPlans));
}
Anil Singh
  • 4,173
  • 4
  • 41
  • 47
0

That's because objects in JavaScript are passed by reference. More about that. Try Most elegant way to clone a JavaScript object.

Community
  • 1
  • 1
andale
  • 463
  • 2
  • 13