JasonJohnson JasonJohnson - 3 months ago 11
Javascript Question

Making an Array with range specified

I need to write a function called addToArray. This function should:
take two arguments, num1 and num2
use a for loop to add each number from num1 to num2 to an array

so if num1 = 2 and num2 = 4
then array = [2,3,4]

my attempt:

addToArray = function (num1, num2) {

for (var i = num1; i < num2 + 1 ; i++) {
array.push(i);
}

return array;
}

Answer

You do not initialize the array and addToArray variables, which will cause JS to crash.

var addToArray = function (num1, num2) {
  var array = [];

  for (var i = num1; i <= num2 ; i++) {
    array.push(i);
  }

  return array;
}