0

I am looking to find out why something that seems so simple, doesn't work like you'd expect it to.

Array1 = ["item1", "item2", "item3", "item4", "item5"];

Array1[0] = "changeditem1";

This method of using Array1[0] to change the array works fine and changes the value to changeditem1

["changeditem1", "item2", "item3", "item4", "item5"]

Though if you put it in a variable

var arrayvariable = Array1[0]

Attempting to then change the array using the variable using

arrayvariable = "changeditem1"

Array1 = ["item1", "item2", "item3", "item4", "item5"];

does nothing to the array. If someone could explain if there is something I am missing or what I am doing wrong, that would be great. Thank you.

  • JavaScript doesn't work that way; there's no way to obtain an alias to an array element. – Pointy Feb 20 '17 at 21:38
  • Your comparison is flawed. Try `arrayvariable[0] = "changeditem1"`. – PM 77-1 Feb 20 '17 at 21:39
  • Array1 is taking different memory location than arrayvariable. So, changes in Array1 itself is change its contetnt whereas changes in arrayvariable change its own content rather than than changing other memory location. – Akash KC Feb 20 '17 at 21:41
  • 1
    Basic types are passed by values not by reference. Changing a copy of them will not affect the original value. If the items of the array were objects for example, you'll be right, but since they are strings (basic) you can't change them like that! – ibrahim mahrir Feb 20 '17 at 21:42
  • 2
    http://stackoverflow.com/questions/42045586/whats-the-difference-between-a-boolean-as-primitive-and-a-boolean-as-property-o/42045636#42045636 – Scott Marcus Feb 20 '17 at 21:46

2 Answers2

0

It is quite simple. It has nothing to do with array.

var a = "some value";
var b = a;
var b = "change the value";
console.log(a);  //some value

= operator will change the value which is stored in it's left.

So by changing the value of b in line 3 we will only change the value of b and not a.

To change a you will again need to assign b to a i.e. by writing a=b;

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
0

In javascript, the = operator will copy the value from the right side of the operand to the left. Unless the variable on the right is of type object, then a reference to that object will be copied.

var obj = {num:5};
var number = 5;
var array = [obj, number]

obj.num = 10;
number = 10;

console.log(array[0].num)
console.log(array[1])

See here for more detailed explanation

To solve your issue, you can either store the index of the item so that you can modify the array. Or you can store your data as an array of objects so that when you copy a variable you can still modify it by it's reference.

Community
  • 1
  • 1
dpix
  • 2,765
  • 2
  • 16
  • 25