3

I'm a bit confused about passing the JavaScript variables by reference.

Take the following piece of code:

var p = [1,2];
var pRef = p;
p.push(3);
pRef === p; // true

Then consider the following piece of code:

var s = "ab";
var sRef = s;
s = s + "c";
sRef === s; // false

what is the trick about passing the JavaScript variables by reference?

Does it exist a way to create a reference to a string?

5 Answers 5

4

Manipulating the string causes the creation of a new instance of a string object. Pushing items in an array does not create a new instance of the array but only adds an item to it.

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

1 Comment

"Manipulating the string causes the creation of a new instance of a string object." And assigning the new instance to the variable makes it point to that new object.
2

The two examples are not doing the same thing. In the first case, you never reassign p, you simply call methods on it to modify the values within the array. In the second case, you reassigned s after setting sRef so they are no longer equivalent.

Comments

0

Strings are immutable in javascript.

Comments

0

p is not representing [1,2] but a pointer from where [1,2] is save in memory. So if you change p, or pRef, the place where this array is save in memory will not change only its value will.

1 Comment

The same can be said about the String variable, too, though.
0

Objects are passed around by reference. If you want a function to manipulate a string by reference, you can pass that string on an object

function manipulate(obj) {
    obj.bar += ' changed';
}

var foo = {
   bar: 'that';
};

manipulate(foo);

//foo.bar is now 'that changed'

So all objects are passed by reference. Arrays are objects in js.

Comments

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.