Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Need help with array. JavaScript

Hello, people!!! Help me to understand! I want to change order of elements in array. But my code are changing also function argument array (arr) (which is external variable.) instesad of changing only result array.

So I want : [[2,1,3], [1,2,3]]. But return of the function is [[2,1,3],[2,1,3]]. And I don't understand why?

function permutate(arr, index) {
    var result = arr;
    var element = arr[index +1];
    if (arr[index + 1] !== undefined) {
        result[index + 1] = result[index];
        result[index]  =  element;
    } else {
        result[index] = arr[0];
        result[0] = arr[index];
    }
  return [result, arr];
}

permutate([1,2,3], 0);

1 Answer

Steven Parker
Steven Parker
243,656 Points

Array assignment in JavaScript creates a reference to the array.

So anything you do with the new variable affects the original array, and vice-versa.

If you want a copy of the array values instead, you can do that in several ways. But one of the most convenient might be to use a slice method with no arguments:

var newarray = oldarray.slice();

Thank you Steven!
I also found the way.

var newarray = Object.assign([], oldarry);