简体   繁体   中英

Trying to modify a global variable using a function

var age=25;

function modify(a) { 
  a=30; 
}

modify(age); 
console.log(age)

I wish to modify the age which is a global variable passing the parameter to the function which I'm not able to do so. I'm still trying to learn javascript. Thanks in advance.

it's pass by value in case of scalar data. So it won't change the age value. If you want to change it then use object or array.

When you are passing a variable to a function, the function creates a local variable whose scope is bounted to that function. That variable will never point to the actual variable that you used. In order to achieve this you need to assign the respinse from that function to your variable.

In your case the global variable age and the local variable a inside the function modify points to different memory address. So updating the local variable inside the function will never updates the global variable.

You can achieve this is multiple ways. You can return the value from that function and assign that to the global varible as a work around

 var age=25; function modify(a) { a = 30; return a; } age = modify(age); console.log(age)

Or else you could directly update the value of the global variable from the function. In this scenario you are pointing to the global variable address itself.

 var age=25; function modify(a) { age = 30; } modify(age); console.log(age)

var age=25;

function modify(a) { return a=30 };

console.log(modify(age)); // logs 30

console.log(age); // still 25

You are updating the value of a

If you want to update age inside your function you must point to the var age

age = 30

 // declared var age and assign 25 var age = 25; console.log("Initial value of age: ", age) function modify(a) { //here, within the function you have a variable 'a' console.log('value of a inside the function ', a) // you update the value of 'a' with 30 // you never modify the value of age. a=30; console.log("value of a after updating it: ", a) // because you declared age in the global scope you get access to it // to update age you must do age = 30 } modify(age); console.log('final value of age: ', age)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM