Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

338
Views
JavaScript: How to push to an array inside an object that was created inside an arrow function

So how do I push to the CONSUPTION array? Using THIS is not working and ia have no clue on how to make the ORDER work.

const createMenu = (menu) => ({
        fetchMenu: () => menu,
        consumption: [1,2],
        order: (string) => {
          this.consumption.push(string);
        },
        pay: () => {
          let cont = 0
          const cardapio = { ...menu.food, ...menu.drink}
          for (let itens of this.consumption){
            cont += cardapio[itens];
          };
          return cont;
        },
      });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Change the order arrow function to a regular function, it's not a good idea to use it in an object.

The reason for that is because that In regular functions the this keyword represented the object that called the function. Unlike regular functions, arrow functions do not have their own this. The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

const createMenu = (menu) => ({
        fetchMenu: function(){ return menu},
        consumption: [1,2],
        order: function(string)  {
          this.consumption.push(string);
        },
        pay: function() {
          let cont = 0
          const cardapio = { ...menu.food, ...menu.drink}
          for (let itens of this.consumption){
            cont += cardapio[itens];
          };
          return cont;
        },
      });
      
      const menu = createMenu();
      console.log(menu.consumption);
      menu.order(3);
      console.log(menu.consumption);

More about this in arrow function could be found here

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!