0

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; } 
1
  • 1
    Cool. So what's your question? Commented Aug 29, 2016 at 20:25

4 Answers 4

2

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; } 
Sign up to request clarification or add additional context in comments.

Comments

1
function addToArray(num1, num2) { var array = []; //missing initialization for (var i = num1; i <= num2; i++) { array.push(i); } return array; } 

Comments

0

in ES 6 :

var addToArray = (num1, num2) => { var array = []; for (var i = num1; i < num2 + 1 ; i++) array.push(i); return array; } console.log(addToArray(2,5)); // [ 2, 3, 4, 5 ] 

Comments

0

You are missing one line before the for loop

var array=[]; //initialize the variable 

So completely

addToArray = function (num1, num2) { var array=[]; for (var i = num1; i < num2 + 1 ; i++) { array.push(i); } return array; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.