When You Meet '...'(Three Dots) in JavaScript
Explanation
'...' can be used in many ways, and that made me confused every time I saw it. So, in this article, let me show you all the ways.
Rest Parameter
function print(num1, num2, ...rest) {
console.log('num1:', num1);
console.log('num2:', num2);
console.log('rest:', rest);
}
print(1, 2, 3, 4, 5);
// num1: 1
// num2: 2
// rest: [ 3, 4, 5 ]
In the above example, 'rest' took 3, 4, and 5, which are not used by other parameters, and became an array.
Please be careful that it should be written at the end.
Spread Syntax - about Arrays
const array = [1, 2, ...[3, 4]];
console.log(array); // [ 1, 2, 3, 4 ]
In the above example, '[3, 4]' broke down and the elements inside it became independent.
Spread Syntax - about Objects (Also Called 'Spread Property')
const object = { k1: 1, k2: 2, ...{ k3: 3, k4: 4 } };
console.log(object); // { k1: 1, k2: 2, k3: 3, k4: 4 }
In the above example, "{ k3: 3, k4: 4 }" broke down and the properties inside it became independent.
In Destructuring - Rest Element
const [i1, i2, ...rest] = [1, 2, 3, 4, 5];
console.log(i1); // 1
console.log(i2); // 2
console.log(rest); // [ 3, 4, 5 ]
In the above example, 'rest' took 3, 4, 5 and became an array.
Please be careful that it should be written at the end.
In Destructuring - Rest Property
const { k1, k2, ...rest } = { k1: 1, k2: 2, k3: 3, k4: 4, k5: 5 };
console.log(k1); // 1
console.log(k2); // 2
console.log(rest); // { k3: 3, k4: 4, k5: 5 }
In the above example, 'rest' took k3, k4, k5 and became an object.
Please be careful that it should be written at the end.