I want to calculate the age of some persons(birthyears are stored inside an array) using a function and then creating another array with the ages from the for loop but i keep getting an empty array. Can anyone help?
const years = [1991, 1994, 2008, 2020];
const calcAge = function (birthYear) {
return 2021 - birthYear;
};
const age = [];
for (let i = 0; i > years.length; i++) {
calcAge(i);
age.push(i);
}
console.log(age);
2 Answers 2
You're simply using > instead of <:
const years = [1991, 1994, 2008, 2020];
const calcAge = function (birthYear) {
return 2021 - birthYear;
};
const age = [];
for (let i = 0; i < years.length; i++) {
age.push(calcAge(years[i]));
}
console.log(age);
The loop should run until i becomes equal to years.length. If i starts off as 0, the comparison i > years.length will be false (since 0 > 4 === false), and the loop will immediately terminate.
I've made one more improvement for you; I switched:
calcAge(i);
age.push(i);
to:
age.push(calcAge(years[i]));
The former has a number of issues; you pass i, the index, instead of years[i], the actual age. And you perform the calcAge computation but never actually store the answer. The latter fixes these issues.
As suggested by Nur, you could simplify your code using map:
const years = [ 1991, 1994, 2008, 2020 ];
const ages = years.map(year => 2021 - year);
console.log(ages);
2 Comments
for..of loopfor..of or Array.prototype.map would be cleaner solutions, but I want to address the actual question asked by the OP.your for loop condition isn't right. it should be switched from i > years.length to i < years.length. You also need to push the return value of your age calculation to the ages array
const years = [1991, 1994, 2008, 2020];
const calcAge = function (birthYear) {
return 2021 - birthYear;
};
const ages = [];
for (let i = 0; i < years.length; i++) {
const age = calcAge(years[i]);
ages.push(age);
}
console.log(ages);
Comments
Explore related questions
See similar questions with these tags.
i > years.lengthwill always befalse.years.map(birthYear => 2021 - birthYear)