Example 1:
const alphabet = ["A", "B", "C", "D", "E", "F", "G"];const number = [1, 2, 3, 4, 5, 6, 7];const [a, b, c] = alphabet;console.log(a);// Result: Aconsole.log(b);// Result: Bconsole.log(c);// Result: C
Example 2:
If we wanna skip any of the elements of an array.
const alphabet = ["A", "B", "C", "D", "E", "F", "G"];const number = [1, 2, 3, 4, 5, 6, 7];const [a, , c] = alphabet;console.log(a);// Result: Aconsole.log(c);// Result: C
Example 3:
If we wanna get the rest of the element, then we can do it with a spread operator(with three dots).
const alphabet = ["A", "B", "C", "D", "E", "F", "G"];const number = [1, 2, 3, 4, 5, 6, 7];const [a, , c, ...rest] = alphabet;console.log(a);// Result: Aconsole.log(c);// Result: Cconsole.log(rest);// Result:// ["D", "E", "F", "G"];
Example 4:
If we wanna combine two arrays…
const alphabet = ["A", "B", "C", "D", "E", "F", "G"];const number = [1, 2, 3, 4, 5, 6, 7];const newArray = [...alphabet, ...number];console.log(newArray);// Result:// ["A", "B", "C", "D", "E", "F", "G", 1, 2, 3, 4, 5, 6, 7];
Post a Comment