+ 2
Why is "x.reverse()" reversing var y in the code below?
var x = "hello".split(""); var y = x; x.reverse(); console.log(y); console.log(x); /*i am trying to make a palindrome checker. x and y are both reversed and not just x. why? any way around this? PS: running this code on node.js console*/
6 Antworten
+ 2
Mons Joseph This is a very good question and it can be a complex topic when you get into the detail, but CarrieForle has given a really good explanation above.
If you're interested in some more detail as to why this happens, there's a distinction between primitive types (e.g. string) and reference types (e.g. arrays).
When a piece of data that's a reference type (like your array), is assigned to a variable or property, it's not the actual data that gets assigned. It's a reference to that data which gets assigned. When you have 2 or more variables or properties all holding that same data, they are holding references to the data, not copies of the data. Those references all point to the same location in memory. So, if you change the data in one place, it changes everywhere. It's to do with how memory works and saving computational resources.
Look up primitive types and reference types (also known as object types). Then you'll get into the domain of pass by reference, pass by value, immutability etc.
+ 4
Because var x = "hello".split("");
Was stored in the y variable.
+ 3
Because array is reference type. When you modify the original array, the assigned one is the reference of the original one and therefore is also modified.
http://dyn-web.com/javascript/arrays/value-vs-reference.php
+ 2
https://code.sololearn.com/W23P2K3naMsK/?ref=app
i hope this will help you
+ 1
Just to add a bit of code to what I said above, this shows what happens with primitive types like strings:
var string = "code";
var otherString = string
otherString = otherString.toUpperCase();
console.log(otherString); //changed to "CODE"
console.log(string); // still "code"
So, even though we've taken a copy of the first string, it only "changes" in one place. This isn't really a changed string. It's a new string because primitive types can't be changed (immutable).
+ 1
This problem is solved with the slice() array method:
y = x.slice();
And this happens because you assign to the variable "y" not the value of the variable "x", but a link to the array in which the value of the array "x" is stored, (something like this)☺️