Search code examples
javascriptarrayspushsplice

Delete all elements in an array - Function appends 'undefined' at the array end



Here is my code

var x = [];

function random(min,max) {
  return Math.floor(Math.random() * (min-max))+min;
}
function random2(a, b) {
  for (let i = 0; i < a; i++) {
    x.push(random(0,b));
  }
}
random2(5, 100);
console.log(x); // [ -43, -27, -38, -21, -79 ]

x.splice(0, x.length);
x.push(random2(5,100));
console.log(x); // [ -24, -97, -99, -43, -66, undefined ]

I simply wanna remove all the elements in the array then add new elements in it. But when I try to do it with the code above, undefined is also adding to the array.
How can I prevent it?


Solution

  • You need not to puish the function call, which returns undefined, but just call the function random2, because the function itselft add the elements to the array.

    function random(min, max) {
        return Math.floor(Math.random() * (min - max)) + min;
    }
    
    function random2(a, b) {
        for (let i = 0; i < a; i++) {
            x.push(random(0, b));
        }
    }
    
    var x = [];
    
    random2(5, 100);
    console.log(x);
    
    x.length = 0;          // better performance than x.splice(0, x.length)
    random2(5,100);        // call without using push
    console.log(x);        // no undefined anymore

    A better approach is to return an array in random2, because this function does not access an outer defined array. To push the values, you could take the spread syntax.

    function random(min, max) {
        return Math.floor(Math.random() * (min - max)) + min;
    }
    
    function random2(a, b) {
        return Array.from({ length: a }, _ => random(0, b));
    }
    
    var x = random2(5, 100);
    console.log(x);
    
    x.length = 0;          
    x.push(...random2(5, 100));
    console.log(x);