Push Multiple items to Array

I was working on the Building a Library exercise on the JavaScript - Classes and couldn’t figure out how to pass an unknown number of items to an empty array. I did some research online and found ‘…item’ used to pass an unknown number of items, but I couldn’t find out why that worked. I was assuming I needed to run some kind of loop on the addRating function to push the arguments to the empty array. The code I used below worked, but a further explanation would be great! Thanks!

class Media {
constructor (title) {
this._title = title;
this._isCheckedOut = false;
this._ratings = ;
get title() {
return this._title;
get isCheckedOut() {
return this._isCheckedOut;
get ratings() {
return this._ratings;
toggleCheckOutStatus () {
if (this._isCheckedOut === false) {
this._isCheckedOut = true;
} else this._isCheckedOut = false;
set isCheckedOut(isCheckedOut) {
this._isCheckedOut = isCheckedOut;
getAverageRating () {
const totalRatings = this._ratings.reduce((total, currentValue) => total + currentValue);
return Math.floor(totalRatings / this.ratings.length);
addRating (…ratings) {

Welcome to the forums! :slight_smile:

MDN documentation is always a useful reference with javascript.

The ... idea is known as rest parameter in js. More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

Of note you should compare it to the arguments object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments


function bakeBread(first, second, ...rest) {
  console.log("I will first bake: ", first)
  console.log("Then I will bake: ", second)
  console.log("Bread types remaining to be baked: ", rest)

bakeBread("baguette", "pita", "naan", "rustic", "focaccia")

// Output:
// I will first bake:  baguette
// Then I will bake:  pita
// Bread types remaining to be baked:  [ 'naan', 'rustic', 'focaccia' ]
1 Like