Skip to content

Instantly share code, notes, and snippets.

@sandrabosk
Last active April 28, 2020 21:56
Show Gist options
  • Save sandrabosk/024a075082e1b8c81c0f95307d28b2e3 to your computer and use it in GitHub Desktop.
Save sandrabosk/024a075082e1b8c81c0f95307d28b2e3 to your computer and use it in GitHub Desktop.
// ************************************************
// ************** Rest parameter ******************
// ************************************************
// Reminder: 'arguments' represents a special array-like object that contains all arguments by their index.
function add1() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
add1(); // 0
add1(1); // 1
add1(1, 2, 5, 8); // 16
function add2() {
return arguments.reduce((sum, next) => sum + next);
}
add2(1, 2, 3); // TypeError: arguments.reduce is not a function
// use spread to turn arguments into array so we can apply array methods on them
function add3(...args) {
return args.reduce((sum, next) => sum + next);
}
add3(1, 2, 3); // 6
// Rest parameter collects all remaining elements into an array.
function showMovie(title, year, ...actors) {
console.log(
`${title} is released in ${year} and in the cast are: ${actors[0]} and ${actors[1]}.`
);
}
showMovie('Titanic', '1997', 'Leonardo Di Caprio', 'Kate Winslet');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment