Wednesday, 6 September 2017

scope - JavaScript, changing a variables value inside of a function when the variable is passed as a parameter





Why doesn't this work and is there any way to get it to work?



Im pretty sure it doesn't work because of variable scoping in javascript, but I can't think of any ways to get it to work.






var x = 5;
var z = function(y) { y = 10; };
z(x);
console.log(x) // Outputs 5 instead of 10

Answer



var x = 5
var z = function(y) { y = 10; }
console.log(x) // Outputs 5 instead of 10



Where exactly did you changed X? you dont have X and you did not call the function as well.



I assume you wish to do this:



var x = {x: 5}
var z = function(y) { y.x = 10; }
z(x);
console.log(x.x) // Outputs 10



The code is using x as variable on an object instead of a primitive number which is passed by value and not by reference and thus cannot be modified.



Using object you can modify the attributes (properties) of the object


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...