0

so it's kinda hard to explain ( more that I don't know the terminology for it but that's beside the point) but basically:

var myArray = [1,2,3];
var wantedData = myArray[1];
   console.log(wantedData);
myArray[1] = 4;
   console.log(wantedData);

so here I changed the array from [1,2,3] to [1,4,3] but the value of wantedData still outputs as 2. Did I do something wrong or would I just have to define it again by doing

var myArray = [1,2,3];
var wantedData = myArray[1];
   console.log(wantedData);
myArray[1] = 4;
wantedData = myArray[1];
   console.log(wantedData);
PJJ
  • 87
  • 2
  • 14

4 Answers4

2

wantedData is being assigned the actual value at myArray[1] not just a reference to it. So changes to the values in the array will not be reflected in the value wantedData as it would with C-style pointers.

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
0

wantedData is a primitive data type whereas myArray is reference type. So, when the reference changes, the primitive variable will not be affected from it.

Berk Elmas
  • 19
  • 1
  • 3
  • Can you show a sample of JustAnotherSenpai's code error/what you fixed? Just so that people can see an example if they don't understand your explanation. – Rojo Nov 12 '19 at 21:22
0

In Javascript advanced types are passed by reference and primitive types by value. it means that if you do that:

let a = 5;
let b = a;
b = 10;

in this case, JS engine copies a's value and assigns to b. they have separated values in memory.

in case of advanced types ( advanced means not a single value or in other words, everything what is not a primitive type, is an object )

var a = {
  name: 'Name'
};

var b = a;
b.name = "New value";

memory pointer for var a and var b are the same, because advanced(reference) types in Javascript are passed by reference. they are linked to the same spot in memory.

0

Other answers are correct, but if you want to obtain what you ask, you can use a thing like this:

var myArray = [1,2,3];
var wantedData = ()=> myArray[1]; // or function(){return myArray[1]}
   console.log( wantedData() ); // 2
myArray[1] = 4;
   console.log( wantedData() ); // 4