I am wondering if I can modify the parameter in the function?
-
2Googling your title.. http://sirdarckcat.blogspot.com.ar/2007/07/passing-reference-to-javascript.html – Gonzalo.- Aug 11 '12 at 03:04
2 Answers
Objects and arrays are passed by reference and changes to the argument you pass to a function will affect the original. All other types behave like they are passed by value and you cannot change the original.
Javascript does this automatically - you cannot specify that something be passed by value or by reference like you can in some other languages. If you want something passed by reference, put it in an array or object and pass the array/object.
Example 1 (passing an object):
function myFunc(myObject) {
// this changes the original object
myObject.ready = true;
}
var obj = {ready: false;};
myFunc(obj);
// obj.ready == true - value is changed
Example 2 (passing a string):
function hello(str) {
str = str + " and goodbye";
alert(str);
}
var greeting = "Hello";
hello(greeting);
// greeting == "Hello" - value is unchanged
Example 3 (passing a string in an object):
function hello(obj) {
obj.str = obj.str + " and goodbye";
alert(obj.str);
}
var o = {greeting: "Hello"};
hello(o);
// o.greeting == "Hello and goodbye" - value is changed
Example 4 (passing a number):
function hello(num) {
num++;
alert(num);
}
var mynum = 5;
hello(mynum);
// mynum == 5 - value is unchanged
Note: One thing that is sometimes confusing is that strings are actually passed by reference (without making a copy), but strings in javascript are immutable (you can't change a string in place in javascript) so if you attempt to modify the string passed as an argument, the changed value ends up in a new string, thus the original string is not changed.

- 683,504
- 96
- 985
- 979
I think you are meaning to ask "Is it possible to change a value passed parameter to a referenced one?"
Javascript is, by nature, a pass by reference language for objects. Primitives like numbers, booleans, and strings are passed by value. If your thinking about how PhP (or a few others) can change the pass by reference or value modifier (IE function passByRef( &refVar ) ) this is not possible with javascript. There is a good post here about how sometimes javascript can be a little more indifferent while passing certain objects and what you might expect, vs what actually happens if it helps.
Is JavaScript a pass-by-reference or pass-by-value language?