1

I assign the new variable to an array. after modifying the array the assigned variable follows the changes of array unexpectedly!

let reference = "I was sent* to Earth,* to protect you."

let orders = reference.split("*").map(s => s.toLowerCase().replace(/\,|\?|\!|\:|\./g,'').trim());

let answer = orders;

console.log(orders)
console.log(answer)
// changing orders and not answer!
orders.push(orders.shift());

// the orders changes as expected but the answer (that is not changed before follows the orders changes)
console.log(orders)
console.log(answer)

4 Answers 4

2
let answer = orders;

You are copying reference of orders to answer as it is an array.

It's like giving another name to the same array(block of memory).

This should solve your problem

Change let answer = orders; to let answer = [...orders];

let reference = "I was sent* to Earth,* to protect you."

let orders = reference.split("*").map(s => s.toLowerCase().replace(/\,|\?|\!|\:|\./g,'').trim());

let answer = [...orders];

console.log(orders)
console.log(answer)
// changing orders and not answer!
orders.push(orders.shift());

// the orders changes as expected but the answer (that is not changed before follows the orders changes)
console.log(orders)
console.log(answer)

Sign up to request clarification or add additional context in comments.

4 Comments

What if I assign a variable to another variable (none of them is an array); like let var1 = var2
Then only the value is copied.
The variable that holds an array actually holds a reference to the memory location
If you were to do var a = arr[0] still only value is copied
1

let answer = orders.slice(0) will make a shallow copy of your array object. in my opinion, to copy your array object the solution is:

let answer = copy(orders);

// copy function
function copy(object) {
    var output, value, key;
    output = Array.isArray(object) ? [] : {};
    for (key in object) {
        value = object[key];
        output[key] = (typeof value === "object") ? copy(value) : value;
    }
    return output;
}

Comments

0

You're mutating the existing array. Clone it by doing the following:

let reference = "I was sent* to Earth,* to protect you."

let orders = reference.split("*").map(s => s.toLowerCase().replace(/\,|\?|\!|\:|\./g,'').trim());

let answer = [...orders];

console.log(orders)
console.log(answer)
// changing orders and not answer!
orders.push(orders.shift());

// the orders changes as expected but the answer (that is not changed before follows the orders changes)
console.log(orders)
console.log(answer)

Alternatively, you can use let answer = orders.slice(0) if you're not using es6

Comments

0

This will solve your issue.

let answer = [...orders];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.