klarate
klarate

Reputation: 41

Why is this function returns an empty array?

I just don't understand why does this function return an empty array instead of newArr = [1, 2, 3, etc.] depending on the length of the array.

function randomFunction(num) {
      var newArr = [];


      for(var i = 1; i < num.length; i++) {   
          newArr.push(i);
     }

      return newArr;
 };

Upvotes: 1

Views: 80

Answers (4)

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10396

If num is supposed to be the length of the new array, and the last number of the range of values, you have to use it directly, instead of using length (which is meant to be used for an array):

function randomFunction(num) {
     var newArr = [];

     for(var i = 1; i <= num; i++) {   
        newArr.push(i);
     }

     return newArr;
 };

 var array = randomFunction(5);
 console.log(array);

Also, you might want use <= instead of <, in case you want to start the value by 1 and go through n, and not n - 1.

Upvotes: 4

KATq
KATq

Reputation: 409

num is already a number. You don't need use .lenght property

function randomFunction(num) {
      var newArr = [];


      for(var i = 1; i <= num; i++) {   
          newArr.push(i);
     }

      return newArr;
 };
randomFunction(5); // [ 1, 2, 3, 4, 5 ]

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 122026

randomFunction(8) ; for example

A number doesn't have length at all. It's already a value.

You do not need length attribute at all. just

 for(var i = 1; i < num; i++) {   
        newArr.push(i);
    }

function randomFunction(num) {
    var newArr = [];

    for (var i = 1; i < num; i++) {
        newArr.push(i);
    }

    return newArr;
};
console.log(randomFunction(8))

Upvotes: 1

Ozgur
Ozgur

Reputation: 3756

function randomFunction(num) {
      var newArr = [];


      for(var i = 1; i < num /* number has no length */; i++) {   
          newArr.push(i);
     }

      return newArr;
 };

Es6 alternative for fun:

return new Array(num).fill().map((r, i) => i)

Upvotes: 2

Related Questions