fill 5 elements in an array with number 1 in javascript

To fill an array with initial values, you can use the fill() method in JavaScript. To fill 5 elements with the number 1, you can do:

index.tsx
let myArray = new Array(5).fill(1);

console.log(myArray); // Output: [1, 1, 1, 1, 1]
86 chars
4 lines

In the above example, we initialize an array with 5 elements using the new Array() constructor with a length of 5. Then we chain on the fill() method and pass in the value of 1 to fill all 5 elements. Lastly, we log the array to the console to confirm that all elements are properly initialized with the value of 1.

gistlibby LogSnag