Just delving into the world of JavaScript and recently grasped the concept of For loops. I have a variable that holds an array with a list of first names, and my goal is to add last names to each of them. Here's the code snippet I came up with:
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))
Output :
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
Queries:
In regards to the loop condition, my understanding is that the length property of an array provides the total number of data elements. So in this case,
name.length = 6
. However, arrays are zero-indexed, so shouldn't it bearray.length-1
to account for this? Surprisingly, when I usedarray.length
, it did include "Angel". Can someone shed light on this discrepancy?Another puzzling aspect is the appearance of "undefined" at the end of the console output regardless of whether I used
array.length
orarray.length-1
. Any insights into why this occurs?