Anz
Anz

Reputation: 49

Can I add array in class in JavaScript?

I am very new to JavaScript, and I tried to add array to my class to save some data:

class ListOfItems {
  let listOfItems = []
  addItem(item) {
    listOfItems.push(item);
    console.log(listOfItems);
  }
}

const lOi = new ListOfItems();

lOi.addItem(10);

But I get this error:

SyntaxError: Unexpected identifier

I don't know if it is allowed to have variables in class. What can I do? I just want to have array of every added item.

Upvotes: 0

Views: 49

Answers (2)

Not A Robot
Not A Robot

Reputation: 2684

You need constructor for creating and initializing an object of that class.

Instead of

let listOfItems = [];

Use constructor to initialize the array.

constructor(listOfItems) {
  this.listOfItems = [];
}

Code:

class ListOfItems {
  constructor(listOfItems) {
    this.listOfItems = [];
  }

  addItem(item) {
    this.listOfItems.push(item);
    console.log(this.listOfItems);
  }
}

const lOi = new ListOfItems();

lOi.addItem(10);
lOi.addItem(20);

Upvotes: 0

Salman Bukhari
Salman Bukhari

Reputation: 94

You can simply write. I hope it worked for you.

class ListOfItems
{
  constructor(listOfItems) {
    this.listOfItems = [];
  }

  addItem(item)
  {
    this.listOfItems.push(item);
    console.log(this.listOfItems);
  }
}

Upvotes: 1

Related Questions