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

98
Visualizações
Why function output doesn't return an expected array

This should be something simple, but I miss why this code outputs 'undefined', while I expect to get an array with numbers: [1, 2]. I tried to debug it in console step by step, but still don't understand why newArr doesn't return from the function. Could someone explain, please.

function filterList(arr) {
    let newArr = []
    for(let i = 0; i <= arr.length; i++) {
        if (typeof arr[i] !== "number") {
            return
        }
        if (typeof arr[i] === 'number') {
            newArr.push(arr[i])
        }
    }
    return newArr
}

console.log(filterList([1,2,'a','b']))

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

0

The first return that is reached inside a function will end the function call and will return whatever you set there.

In your case, you are pushing 2 values in the array, but as soon as you reach the third one a you are just using return. This means that you are returning undefined. You should return newArr

function filterList(arr) {
    let newArr = []
    for(let i = 0; i <= arr.length; i++) {
        if (typeof arr[i] !== "number") {
            return newArr
        }
        if (typeof arr[i] === 'number') {
            newArr.push(arr[i])
        }
    }
    return newArr
}

console.log(filterList([1,2,'a','b']))
about 4 years ago · Juan Pablo Isaza Relatório

0

remove return in for loop

function filterList(arr) {
    let newArr = []
    for(let i = 0; i < arr.length; i++) {
        if (typeof arr[i] === 'number') {
            newArr.push(arr[i])
        }
    }
    return newArr
}
const arr = [1,2,'a','b']
console.log(filterList(arr))

// with Array.filter
let result1 = arr.filter(ele => typeof ele === 'number')
console.log(result1)

// with Array.reduce
let result2 = arr.reduce((res, ele) => typeof ele === 'number' ? [...res, ele] : res, [])
console.log(result2)

function stopFunc(isStop = false) {
  let total = 0
  for(let i = 0; i < 10; i++) {
    total += i
    if(isStop) return 999
  }
  return total // return 45
}
console.log(stopFunc())
console.log(stopFunc(true))

you can check stopFunc function in my example, The return statement ends function execution and specifies a value to be returned to the function caller. . in your function :

if (typeof arr[i] !== "number") {
   return
}

return omitted, undefined is returned instead.

You can check document return

about 4 years ago · Juan Pablo Isaza Relatório

0

You're returning from the function immediately on finding an element that isn't a number, and the return value from the function is undefined not the array you've been patiently pushing numbers into. Just remove that statement altogether.

function filterList(arr) {

  const newArr = [];

  for (let i = 0; i <= arr.length; i++) {
    if (typeof arr[i] === 'number') {
      newArr.push(arr[i]);
    }
  }

  return newArr;

}

console.log(filterList([1, 2, 'a', 'b', 3, 4]))

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