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:
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 usedarray.length
, the result showed Angel. What logic am I missing here?When I put the result on the console, there’s always an “undefined” at the end of it, whether I used
array.length
orarray.length-1
. Can anybody tell me why it showed up?
Advertisement
Answer
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.