code not working for bigger range of numbers

So my problem is that I wrote this code that takes two numbers and writes all numbers between those numbers (including the given two numbers). The code works for the numbers 4 and 7, it prints out "4 5 6 7" but when the 2nd number is a little bigger than the first number for example for the numbers 6 and 14 the code does nothing. If someone could explain to me why it is like this and how could I solve this problem I would-be so happy.

function calculate() {
  var start = document.getElementById("number1").value;
  var end = document.getElementById("number2").value;
  var answer = "";
  for (var i = start; i <= end; i++) {
    answer = answer + i + " ";
  }
  document.getElementById("answer2").innerHTML = answer;
}
<input type="number" id="number1">
<input type="number" id="number2">
<button onclick="calculate()">Poka┼╝</button>
<div id="answer2"></div>

27 thoughts on “code not working for bigger range of numbers”

  1. The value property returns a string representing the value of the value attribute of a text field.
    To compare start and end you need to convert them into numbers (e.g. with the Number primitive wrapper), else the string 6 will be (alphabetically) greater than the string 14.

    function calculate() {
      var start = Number(document.getElementById("number1").value);
      var end = Number(document.getElementById("number2").value);
      var answer = "";
      for (var i = start; i <= end; i++) {
        answer = answer + i + " ";
      }
      document.getElementById("answer2").innerHTML = answer;
    }
    <input type="number" id="number1">
    <input type="number" id="number2">
    <button onclick="calculate()">Poka┼╝</button>
    <div id="answer2"></div>
    Reply

Leave a Comment