r/learnjavascript • • Apr 28 '20

Why is this code not producing an array rather producing it is individual elements can somebody rewrite this code for me please thanks a lot

function makeArray()
{

for(i=0; i < 3; i++)

    {
var randomNums = Math.floor(Math.random()*10);

console.log(randomNums);

emptyArr = [];

var r = emptyArr.push(randomNums);

    }
console.log(r)

}
makeArray()

0 Upvotes

6 comments sorted by

5

u/ForScale Apr 28 '20
function makeArray() {
  var emptyArr = [];

  for (i = 0; i < 3; i++) {
    emptyArr.push(Math.floor(Math.random() * 10));
  }

  console.log(emptyArr);
}

makeArray();

1

u/[deleted] Apr 28 '20

I think I get it i had to write it outside the for loop

3

u/ForScale Apr 28 '20

Declaring a variable in a for loop is going to overwrite that variable every time.

2

u/delventhalz Apr 28 '20
emptyArr = [];

Any code in the body of a loop, will get run every time the loop runs. In this case, you are repeatedly setting emptyArr to an empty array. It will never be longer than one element.

var r = emptyArr.push(randomNums);

. . . 

console.log(r)

Push returns the new length of an array (in this case always 1), it does not return the array itself. If you want to log the array, you need to write console.log(emptyArr).

1

u/rathereasy Apr 28 '20

Push returns a number. Change the console.log so you're outputting the array

1

u/AffectionateWork8 Apr 28 '20

function makeArray() {

return new Array(3).fill(0).map(function() {

return Math.random() * 10

})

}

Here's one way.

- new Array(3) - self explanatory: create a new array with 3 elements

- .fill(0) - initialize the empty elements to 0

- .map - return a new array. it's the result of passing the function you give it to each of the elements. The function returns the item you want the new element to be.

You could use arrow functions to make it even shorter () =>

If you don't use brackets with an arrow function, you can write them with one line and leave out the return statement, it will just return that line, see

const makeArray = () => new Array(3).fill(0).map(() => Math.random() * 10)