Search code examples
javascriptarraysclassargs

I'm trying to create an array from ES class arguments but I'm getting an empty Array, why?


Consider this code for this scenario of creating an Array with value of "sideLength" and for "sides" times within this ES class, but I'm keep getting an empty array!! here is codepen link

class ShapeNew {
  constructor(name, sides, sideLength) {
    this.name = name;
    this.sides = sides;
    this.sideLength = sideLength;
  }
  tryArray() {
    let sides_array = [];
    for (let i = 0; i < this.sides; i++) {
      sides_array = sides_array.push(this.sideLength);
    }
    return sides_array;
  }
  newPerimeter() {
    let peri = this.tryArray();
    console.log(peri.reduce((sum, accum) => sum + accum));
  }
}
let new_square = new ShapeNew("square", 4, 5);
new_square.newPerimeter();

All I'm trying to do is convert 4 into [5,5,5,5], how do I do that?

Thanks in advance for looking into this, I appreciate it :)


Solution

  • You want this

    sides_array.push(this.sideLength);
    

    Not this

    sides_array = sides_array.push(this.sideLength);
    

    Because Array.push() does not return anything.