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

128
Visualizações
For Loop while referring to an array with Length

I'm very new to javascript and have just recently learned about For loops. I have a variable that consists of an array containing a bunch names, and i would like to add last names to each of them. I wrote the code as shown below and have a few questions.

let name = ["john", "maria", "brandon", "gaby", "jessica", "angel"];

function addLastName(array) {
  for (let i = 0; i < array.length; i++) {
    console.log(name[i] + " (please insert last name)")
  }
}

console.log(addLastName(name))

Result :

john (please insert last name)
maria (please insert last name)
brandon (please insert last name)
gaby (please insert last name)
jessica (please insert last name)
angel (please insert last name)
undefined

Questions:

  1. About the second statement for the loop. Correct me if i'm wrong, but when using length in an array, it will show the amount of data inside the array right? So in this case, name.length = 6. But to my understanding, when accessing a part of an array, the count always starts at 0. So i used array.length-1. But the result didn't show "Angel". When i used array.length, the result showed Angel. What logic am i missing here?

  2. when i put the result on the console, there's always an "undefined" at the end of it, whether i used array.length or array.length-1. Can anybody tell me why it showed up?

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

0

For your first question:

Inside the for loop, if you start from 0, and the condition is i < array.length and the length of the array is 6, it will go from 0 to 5, and when it reaches 6 it will not respect the condition (6 < 6 false) so it will exit the for loop before executing the block inside (but when you exited the for, i will be 6).

For your second question:

You should not call console.log(addLastName(name)) because addLastName already logs to the console. That console.log is the one that prints undefined since it will print the result of the function, which is undefined by default if you do not return anything inside the function.

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