Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
Variable assignment avoids an infinite loop

I have two pieces of recursive code, intending to recursively print out half of the array until we get to arrays of array length 1. The code without variable assignment runs infinitely while the code with variable assignment behaves as expected.

Any clues why this is the case?

Runs infinitely, CAREFUL

function half(arr) {
  halfway = Math.floor((arr.length) / 2)
  console.log(arr)
  if (arr.length > 1) {
    half(arr.slice(0, halfway));
    half(arr.slice(halfway));
  }
  return
}

half([1, 2, 3, 4, 5]);

Does not run infinitely

function half(arr) {
  halfway = Math.floor((arr.length) / 2)
  console.log(arr)
  if (arr.length > 1) {
    var a = arr.slice(0, halfway);
    var b = arr.slice(halfway);
    half(a);
    half(b);
  }
  return
}

half([1, 2, 3, 4, 5]);

I thought that maybe some kind of mutability might be at play here but I can't imagine how there would be run on effect. I thought that we were passing what is effectively a whole new array into the function every time it gets called...

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Because it lacks var, let and const, halfway has global scope, as if you wrote window.halfway. As a result, all recursive calls modify and use the same single variable.

In the 1st function the value is changed in the first recursive call before it can be used in the second recursive call. In my testing this actually led to a kind of Stack Overflow error (or rather a Maximum call stack size error), very appropriate for this site :-).

In the 2nd function the value is used twice before the recursive calls start, and then it gets modified by both after each other.

Issue solved by using const:

function half1(arr) {
  const halfway = Math.floor((arr.length) / 2)
  console.log(arr.toString())
  if (arr.length > 1) {
    half1(arr.slice(0, halfway));
    half1(arr.slice(halfway));
  }
  return
}

function half2(arr) {
  const halfway = Math.floor((arr.length) / 2)
  console.log(arr.toString())
  if (arr.length > 1) {
    var a = arr.slice(0, halfway);
    var b = arr.slice(halfway);
    half2(a);
    half2(b);
  }
  return
}

const data = [1, 2, 3, 4, 5];
half1(data);
console.log("------------------------")
half2(data);

Final note: the whole problem would have been detected and prevented by the JS compiler if you had put 'use strict'; on top of your code. I don't really like how clumsily this directive works (why does putting a "dead and unused" string on top of your code have such a special and far-reaching effect?), but we'll have to make use of what we can get.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda