Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing the JavaScript variables by reference

Tags:

javascript

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?

like image 850
antonjs Avatar asked Feb 17 '26 15:02

antonjs


1 Answers

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.

like image 54
Bas Slagter Avatar answered Feb 20 '26 04:02

Bas Slagter