JS Interview Question/Ans Series
The interview question series continues …
4. Difference between spread and rest operators?
Ans: Imagine an situation where you have function called showNum which can take any number of arguments and at the end it should return the numbers or params passed to it. This is rest operator.
function showNum(...num){
console.log(num);
}showNum(4,5); // [4,5]
showNum(1,2,3,4,5); [1,2,3,4,5]function show(){
console.log(arguments)
}
sum(4,5); // [Arguments] { '0':4, '1': 5}const show =()=>{
console.log(arguments)
}sum(4,5); //error arguments object doesn't work with arrow function
With rest operator we are creating an array of arguments but with arguments object we have a kind of object literal i.e. key and value.
As the rest operator puts the separate data values in one array, the spread does exactly the opposite. It spreads the array into separate data values.
let arr1 = [1,2,3];
let arr2 = [...arr1,4,5,6];
console.log(arr2) // [1,2,3,4,5,6]
5. Can the rest operator be placed anywhere in the function parameter list?
Ans: We can’t have rest parameter in the beginning of parameter list. We have to put it at last position as it is the rest of the params.
function test(...a,b){
//statements
}
test(4,5,6) // error else try (a,...b)
Thanks for Reading. Hope you understood the basic difference. For more Questions, click on the below link.