1

I have the function change(x) which takes an integer and changes its value

function change(x) {
   x=26;
}

Then I make a variable and I try to change its value

window.onload=function(){
   var a = 10;
   change(a);
   console.log(a);
}

a doesn't change as I would expect. Is it possible to achieve this behaviour in JavaScript in a simple way without using return? I would prefer to avoid objects and globals.

Here is my whole code:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
   <script>
   function change(x) {
      x=26;
   }
   window.onload=function(){
      var a = 10;
      change(a);
      console.log(a);
   }
   </script>
</body>
</html>
Pithikos
  • 18,827
  • 15
  • 113
  • 136

3 Answers3

3

JavaScript always passes arguments by value, so you can't do it as you originally written.

However, an object's value is a reference, so you could use an object.

However, that would be confusing for this use case. You should have that function return the transformed number.

alex
  • 479,566
  • 201
  • 878
  • 984
  • The problem is that there is a callback function inside my "change" function, thus I cannot return the value. I get 'undefined' then. – Pithikos Mar 31 '13 at 11:37
  • @Pithikos You should use callback function. – dfsq Mar 31 '13 at 11:52
  • 1
    "However, an object's value is a reference" You mean, a variable's value is a reference, which points to an object. – newacct Mar 31 '13 at 19:15
1

You cannot pass a variable by reference like that (or at all). What you can do is pass an object and modify its properties:

function change(obj) {
    obj.a = 4;
}

var obj = {a: 0};
change(obj);

// obj.a is "4" now
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
-2

I did this and it worked:

function change(x) {   
  x=26;  
  return x;  
}  
  window.onload=function(){  
  var a = 10;  
  console.log(change(a));  
}

Hope it helps

phiri861
  • 5
  • 2