0

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.

4
  • I'm not sure the let is needed? Remove the let, then it can be accessed by this.listOfItems Commented Mar 25, 2021 at 12:31
  • create a constructor and initialize the array, then use this.listOfItems in the method to push Commented Mar 25, 2021 at 12:32
  • Introduce a constructor and initialise this.listOfItems = [] inside of that. Commented Mar 25, 2021 at 12:32
  • Please at least read developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… preferably a full javascript tutorial, that includes a section about classes. Commented Mar 25, 2021 at 12:37

2 Answers 2

1

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);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried it, but now I get error: listOfItems is not defined
@Anz, for console.log it should be console.log(this.listOfItems)
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.