1

I signed the variable bubbleL1 to 1, but why the first variable in the bubbles list, which is bubbleL1 still shows undefined? I know this maybe a stupid question, but I really don't know why.

    let bubbleL1, bubbleL2, bubbleL3, bubbleR1, bubbleR2, bubbleR3;
    let bubbles = [bubbleL1, bubbleL2, bubbleL3, bubbleR1, bubbleR2, bubbleR3];

    bubbleL1 = 1;
    console.log(bubbleL1) // 1
    console.log(bubbles) // [undefined, undefined, undefined, undefined, undefined, undefined]

What I want is a list with a specific name for each item in it (for the declared reason, I really don't just use bubbles[0], bubbles[1]...)

Let's say we have a list named bubbles, and we also have six variables called bubbleL1, bubbleL2, bubbleL3, bubbleR1, bubbleR2, bubbleR3. I want to put all these six variables into the bubbles list, so later I can assign values to each variables that in the list, like this:

bubbles.forEach((bubble) => {
  bubble = "something";
})
Xin Chen
  • 107
  • 7

1 Answers1

3

bubbleL1 is a primitive and therefore copied by value.

let x = 3;

let sum = x;
sum = 3 + 5;

console.log(x); // 3

Objects and arrays, on the other hand, will exhibit your expected copy-by-ref behavior:

let x = {a: 3};

let sum = x;
sum.a = 3 + 5;

console.log(x.a); // 8
junvar
  • 11,151
  • 2
  • 30
  • 46