Luis Murga
Luis Murga

Reputation: 1

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);

Upvotes: 0

Views: 343

Answers (4)

Wajid
Wajid

Reputation: 593

It is because your added wrong loop condition

what it mean of your conditon for (let i = 1; i <= people; i++){ it mean it will run at last index of array so suppose you have length of array is 3 but in array start of index from 0 so it will finish on 2 now when again 3<=3 here i now is 3 so condition true and loop will run and when loop go in then it find undefine index mean 3 is not index of your array

Solution is

you need to set like this for (let i = 1; i < people; i++){ now at last iteration when i=3 3<3 then this condition will false now loop will break

hope this will help for you to understand working of loop

Upvotes: 0

Nachman
Nachman

Reputation: 11

You have to start your array index (in your case the Counter) from zero, and end your loop when Counter equal People -1.

Upvotes: 1

Shiz
Shiz

Reputation: 693

your code:

for (let i = 1; i <= people; i++){

solution:

for (let i = 0; i < people; i++){

Upvotes: 2

Yadab
Yadab

Reputation: 1883

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);

Upvotes: 1

Related Questions