I wrote a simple function to add odd numbers and even numbers separately, for between given two numbers
here is my code :
function calculateSum() {
var startV = document.getElementById("startV").value;
var endV = document.getElementById("endV").value;
var evenV = 0;
var oddV = 0;
console.log(">>", "evenV", typeof evenV)
console.log(">>", 'oddV', typeof oddV)
for (var i = startV; i <= endV; i++) {
if ((i % 2) == 0) {
evenV = evenV + i;
console.log(i, "evenV", typeof evenV)
} else {
oddV = oddV + i;
console.log(i, 'oddV', typeof oddV)
}
}
var disMessage = "even Value:" + evenV + "</br> odd Value:" + oddV;
document.getElementById("dis").innerHTML = disMessage;
}
if startV is 2 and endV is 5, expected output is evenV = 6 and oddV = 8. But received output is
even Value:024 odd Value:8
- Why javascript has this behavior ?
- I know I can use
parseIntexplicitly. But is it the only way to overcome this issue? Because for every add function, using parseInt should not be necessary and it can be a waste of resources AFAIK.
