Swapping array elements in JavaScript

Elements can be swapped using destructuring assignment expression

var numbers = [1,2,3];
[numbers[2], numbers[1]] = [numbers[1], numbers[2]];
console.log(numbers); // [1,3,2]

Without destructuring assignment, swapping two values requires a temporary variable

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array