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

222
Views
why ".length" is acting differently in the similar cases in javaScript?

Here the length is declared before the for loop and the function is giving the correct answer.
The console: []

function dropElements(arr, func) {
  let len = arr.length;

  for (let i = 0; i < len; i++) {
    if (!func(arr[0])) {
      arr.shift();
    }
  }

  return arr;
}

console.log(dropElements([1, 2, 3, 4], function(n) {
  return n > 5;
}));

Now the length is used directy in the for loop and the function is leaving behind two elements of the array. The console: [3,4]

function dropElements(arr, func) {

  for (let i = 0; i < arr.length; i++) {
    if (!func(arr[0])) {
      arr.shift();
    }
  }

  return arr;
}

console.log(dropElements([1, 2, 3, 4], function(n) {
  return n > 5;
}));

about 4 years ago · Santiago Gelvez
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!