Javascript Question

How can I shorten this code? (loop)

So, I just want to shorten the code below:

var start=function(){
var bevetel = document.getElementsByClassName("bevetel");
var yearlyincome2010=0;
var yearlyincome2011=0;
var yearlyincome2012=0;
var yearlyincome2013=0;
var yearlyincome2014=0;
var yearlyincome2015=0;
var yearlyincome2016=0;
for(var i=0; i < bevetel.length; i++) {
if (i<3) {
if (bevetel[i].value) {
yearlyincome2010 += parseInt(bevetel[i].value);
document.getElementById("yearlyincome2010").innerHTML=yearlyincome2010;
}
else {}
}
else if (i<7){
if (bevetel[i].value) {
yearlyincome2011 += parseInt(bevetel[i].value);
document.getElementById("yearlyincome2011").innerHTML=yearlyincome2011;
}
else {}
}
else if (i<11) {
if (bevetel[i].value) {
yearlyincome2012 += parseInt(bevetel[i].value);
document.getElementById("yearlyincome2012").innerHTML=yearlyincome2012;
}
else {}
}
else if (i<15) {
if (bevetel[i].value) {
yearlyincome2013 += parseInt(bevetel[i].value);
document.getElementById("yearlyincome2013").innerHTML=yearlyincome2013;
}
else {}
}
else if (i<19) {
if (bevetel[i].value) {
yearlyincome2014 += parseInt(bevetel[i].value);
document.getElementById("yearlyincome2014").innerHTML=yearlyincome2014;
}
else {}
}
else if (i<23) {
if (bevetel[i].value) {
yearlyincome2015 += parseInt(bevetel[i].value);
document.getElementById("yearlyincome2015").innerHTML=yearlyincome2015;
}
else {}
}
}


};

Theese #yearlyincome201$'s are IDs of headings...
.bevetel is a class for inputs.

This function calculates each FOUR inputs and gives me the answer of them separately.

Answer
var YearsAndIncomes = {
    yearIncomes = [],
    quarters = [],
}

let year = 2009;
let income = 0;

for (let i = 0; i < bevetel.length; i++) {
    income += bevetel[i];
    if ((i%4) == 3) {
        year += 1;
        YearsAndIncomes.yearIncomes.push("YearlyIncome" + year);
        YearsAndIncomes.income = income;
        income = 0;
    }
}

for (let i = 0; i < YearsAndIncomes.yearIncomes.length; i++) {
    document.getElementById(YearsAndIncomes.yearIncomes[i]).innerHTML = YearsAndIncomes.income[i];
}

This makes it easier and abstracts your work. Basic rules of looping. Don't hard code anything that you are going to have to add more of later (like years). Try and do everything that is repeated once, (i.e. document.getElementById). This is performed multiple times, but only exists in one place, so you always know where to go if it needs to be fixed or changed.

Also, use 'for (let i' instead of 'for (var i'. Var makes a global variable every time, which you don't want on iterators like 'i'. Let makes a variable that disappears once you are out of the closure, i.e. the 'let i' only exists inside that for loop.

Comments