Why is the final value undefined for the for loop?

I am new to JavaScript and as I was practising I was not able to figure out why does the last value in my oddPairs array returns undefined when the loop ends?

const people = 56;
let numberGenerator = 0
let tickets = [];
let evenPais = [];
let oddPairs = [];

for (let counter = 1; counter <= people; counter++){
    let numberGenerator = Math.ceil(Math.random() *56);
    tickets.push(numberGenerator);
}

for (let i = 1; i <= people; i++){
    if (tickets[i] % 2 === 0){
        evenPais.push(tickets[i]);
    }else {
        oddPairs.push(tickets[i]);
    }
}

console.log(evenPais);
console.log(oddPairs);
console.log(evenPais.length + oddPairs.length);

3 thoughts on “Why is the final value undefined for the for loop?”

  1. Try this. Array always starts with 0 and ends with n – 1.

    const people = 56;
    let numberGenerator = 0
    let tickets = [];
    let evenPais = [];
    let oddPairs = [];
    
    for (let counter = 1; counter <= people; counter++){
        let numberGenerator = Math.ceil(Math.random() *56);
        tickets.push(numberGenerator);
    }
    
    for (let i = 0; i < people; i++){
        if (tickets[i] % 2 === 0){
            evenPais.push(tickets[i]);
        }else {
            oddPairs.push(tickets[i]);
        }
    }
    
    console.log(evenPais);
    console.log(oddPairs);
    console.log(evenPais.length + oddPairs.length);
    Reply

Leave a Comment