Home > database >  unshift and push inside a loop in Javascript, infinite loop javascript
unshift and push inside a loop in Javascript, infinite loop javascript

Time:12-13

I'm a beginner student and I'm try to get some information from "user" using the prompt() function, and then throw this information in an array. I need to use the loop FOR and the WHILE to solve this problem.

This is my code:

let allEmployeess = Number(prompt("How many employees in the company?"));

let employee = new Array(allEmployeess);
let contador = 1;

for (let i = 0; i <= employee.length; i  ) {
  let colaborador = {
    name: prompt("Employee name:"),
    salary: Number(prompt("What is the salary amount??"))
  }

  employee.unshift(colaborador);
}

This isn't working and I'm falling into an infinite loop.

I suppose this happens because the unshift(and push) method, return the new lenght of the array, and maybe I'm increasing the array leaving it always bigger than the counter.

What can I do to solve this?

CodePudding user response:

The were a few minor mistakes in your code which I tried to address with comments:

let allEmployeess = Number(prompt("How many employees in the company?"));

let employee = new Array(allEmployeess);
let contador = {}; // better to have an empty object instead of 1 for readablity

for (let i = 0; i < employee.length; i  ) { // when you are iterating an array, it should go from 0 to length -1
  let colaborador = {
    name: prompt("Employee name:"),
    salary: Number(prompt("What is the salary amount??"))
  }

  employee[i] = colaborador; // instead of removing ith element, just update it with the new inputs
}

CodePudding user response:

As you point out, you’re continuously adding to the length of the array so employee.length keeps increasing, hence the infinite loop.

It looks like what you want in your for loop conditional is i <= allEmployees rather than i <= employees.length as allEmployees is the total count of employees and will not change.

CodePudding user response:

You are looping through an array that you keep adding elements to, hence the infinite loop. Use the number of employees (scalar) in the for loop instead. Also, I created the colaborador object outside of the loop, so it only takes up one place in memory:

let allEmployeess = Number(prompt("How many employees in the company?"));

let colaborador = {};
let employee = [];

for (let i = 0; i < allEmployeess; i  ) {
  colaborador["name"] = prompt("Employee name:");
  colaborador["salary"] = Number(prompt("What is the salary amount??"));
  employee.unshift(colaborador);
  colaborador = {};
}

console.log(employee);

  • Related