Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

swapping elements in an array

let a = 1;
let b = 3;

[a, b] = [b, a]; // destructuring assignment, assigning the value of a and b to a new array created with b and a
console.log(a); // 3
console.log(b); // 1

const arr = [1,2,3];
[arr[2], arr[1]] = [arr[1], arr[2]];
console.log(arr); // [1,3,2]
Source by developer.mozilla.org #
 
PREVIOUS NEXT
Tagged: #swapping #elements #array
ADD COMMENT
Topic
Name
7+3 =