I'm really new to code optimization and JS. And I like to learn with clean code. I would like to ask for help on optimizing my code.
The code below parses the value of four inputs as floating point numbers and adds them together. The sum is then displayed in an output element.
if(document.getElementById('salary-field').value ===''){
salary = 0;
}else{
salary = parseFloat(document.getElementById('salary-field').value).toFixed(2);
document.getElementById('salary-field').value = salary;
}
if(document.getElementById('commission-field').value ===''){
commission = 0;
}else{
commission = parseFloat(document.getElementById('commission-field').value).toFixed(2);
document.getElementById('commission-field').value = commission;
}
if(document.getElementById('rental-field').value ===''){
rental = 0;
}else{
rental = parseFloat(document.getElementById('rental-field').value).toFixed(2);
document.getElementById('rental-field').value = rental;
}
if(document.getElementById('other-income-field').value ===''){
other_income = 0;
} else {
other_income = parseFloat(document.getElementById('other-income-field').value).toFixed(2);
document.getElementById('other-income-field').value = other_income;
}
sum = parseFloat(salary) + parseFloat(commission) + parseFloat(rental) + parseFloat(other_income);
document.getElementById('sum-field').value = sum.toFixed(2);