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>
2
  • 2
    Yes, a = change(a); Commented Mar 31, 2013 at 11:33
  • Check this answer: stackoverflow.com/questions/518000/… Commented Mar 31, 2013 at 11:34

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The problem is that there is a callback function inside my "change" function, thus I cannot return the value. I get 'undefined' then.
@Pithikos You should use callback function.
"However, an object's value is a reference" You mean, a variable's value is a reference, which points to an object.
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

Comments

-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

1 Comment

Adding a console.log(a) at the end of your window.onload function proves you wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.