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

199
Visualizações
if statement not evaluating but console log shows it should

I am trying to write a function to get the length of a string without using the .length property nor any loops or built in methods. I am using recursion, however, the stopping statement is not evaluating and causing a stack overflow. I tried console logging string[i] and sure enough, once the length is reached, it console logs "undefined" but the if statement still won't evaluate.

const getLength = (string, i = 0) => {
    if (string[i] === 'undefined') return 0;
    return 1 + getLength(string, i+1);
}

console.log(getLength("what is going on??")); //18

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

0

the if-state should be string[i] === undefined

about 4 years ago · Juan Pablo Isaza Relatório

0

Your test for undefined is not working

You can test for falsy or more detailed

Here is just a falsy one, it will fail on falsy values like 0

const getLength = (string, i = 0) => string[i] ?  1 + getLength(string, i+1) : 0;
console.log(getLength("what is going on??")); //18

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