Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this happening? (javaScript's reverse method)

repl.it : https://repl.it/BuXR/3

var str = "abc";
var str2 = str.split(" ").join("").split("");
var tmp = str2;
console.log(str2);
// => ['a','b','c']
console.log(tmp.reverse());
// => ['c','b','a']
console.log(str2);
// => ['c','b','a']

My question is why str2 is being changed even though it is not being reversed?

This is very upsetting to me, but I have a guess as to why this is happening. The tmp is just a pointer to the original str2, and when I call reverse() on tmp, it actually reverses str2.

Even if that really is what's happening, I still feel like it is a very counterintuitive way for a language to work.

like image 325
John Chen Avatar asked Mar 09 '16 05:03

John Chen


People also ask

What Reverse () will do in JavaScript?

The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.

How do you reverse a given string in place JavaScript?

The split() method splits a String object into an array of string by separating the string into sub strings. The reverse() method reverses an array in place. The first array element becomes the last and the last becomes the first.

How do you reverse an array in place in JavaScript?

prototype. reverse() The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first.


2 Answers

Your guess is right.

The tmp is just a pointer to the original str2, so whatever operations are performed on str2 it will be stored to memory and when you access tmp it find the reference to str2.

I have a guess as to why this is happening. The tmp is just a pointer to the original str2, and when I call reverse() on tmp, it actually reverses str2.

like image 147
Hemant Metalia Avatar answered Nov 08 '22 19:11

Hemant Metalia


2 Reasons why this is happening:

  • The reverse() method reverses an array in place, hence tmp is reversed: ref
  • The variable tmp and str2 are references to the same array instance, hence str2 also reversed.
like image 45
Royal Pinto Avatar answered Nov 08 '22 18:11

Royal Pinto