0

I made a simple js code to input start value and end value form prompt and then find all the odd numbers, unfortunately it's not working properly. when i input 1 and 10 it'll work, but when i input 5 for sValue(start value) the program won't work. any idea?

    var odd = [];
    var sValue = prompt("start");
    var eValue = prompt("end");

    for (var i = sValue; i <= eValue; i++) {

        if (i % 2 != 0) {
            odd.push(i);
        }
    }

    alert(odd);
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Danuja
  • 25
  • 4
  • 3
    `prompt` returns a string or `null`. You’re relying on number coercion a lot, which works almost everywhere, but in the first iteration, both values of `i <= eValue` are strings, so a lexicographic comparison is performed instead of a numeric one. `5` does not come before `10` in a dictionary. Use `Number(prompt(`…`))`. Note that `parseInt` may not be the right tool here. – Sebastian Simon Oct 28 '21 at 16:05

1 Answers1

0

Because the value of prompt is a string. You need to convert it to a number with parseInt(v, 10).

var odd = [];
var sValue = parseInt(prompt("start"), 10);
var eValue = parseInt(prompt("end"), 10);

for (var i = sValue; i <= eValue; i++) {

  if (i % 2 != 0) {
    odd.push(i);
  }
}

alert(odd);
zero298
  • 25,467
  • 10
  • 75
  • 100