-1

Totally newbie question. So I have an array and I pass it to a function. If the function changes the array in anyway, after the function returns, the array is actually changed.

When I do the same with lets say with an integer parameter, the parameter value before and after the call is the same.

Here is an example.

function test2(inputValue) {
    inputValue += 5;
}


function test1() {
    var input = 1;
    input = test2(input);
    console.log('input: ' + input);
}

test1();

input : 1 so the value of the parameter was unchanged.

not sure how to explain that.

Thoughts?

reza
  • 5,972
  • 15
  • 84
  • 126
  • 1
    read about references and pointers. – gdoron Nov 20 '14 at 01:44
  • and here's a link to where you can read about passing by reference and by value: http://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value – Lee Jenkins Nov 20 '14 at 01:44
  • 1
    What is your question? "Why is this?" "How to change an integer?" "How not to change an array?" – Amadan Nov 20 '14 at 01:45
  • See [Javascript by reference vs. by value](http://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value). Objects are assigned or shared or passed by pointer, all others by value. – jfriend00 Nov 20 '14 at 01:45

2 Answers2

1

When you invoke the function, if the parameter is a primitive type, it make a copy of the parameter. So what you change is the copy. If the parameter is an array(or other object), it make the copy of reference, when you make change, it change the array by the going to the address(reference). So the values in array change.

0

Add a return inputValue; statement after your inputValue += 5; so that the function returns the value.

By returning a value, the function will be equivalent to its input plus 5, or in this case, 6, and will pass back that number.

Firedrake969
  • 763
  • 8
  • 22