Rest parameter is for collect all remaining elements into an array,
the syntax allows use to represent indefinite number of arguments as an array.
We use ... syntax in parameter of function to present it.
<script>
function average(...args){
let sum = 0;
for(let val of args){
sum += val;
}
return sum / args.length;
}
alert(average(1,2,3,4,5,6,7));
</script>
The sum is 28 and these are 7 items in arguments, the the result is 4.
No comments :
Post a Comment