fill 5 elements in an array with number 5 in javascript

To fill an array with five elements of value 5 in JavaScript, we can create an array with a length of 5 and then use a loop to set each element to the value of 5. Here's an example:

index.tsx
const myArray = new Array(5);  // create an array with a length of 5
for (let i = 0; i < myArray.length; i++) {
  myArray[i] = 5;  // set each element to the value of 5
}
console.log(myArray);  // output: [5, 5, 5, 5, 5]
221 chars
6 lines

Alternatively, we can use the fill() method in modern browsers to simplify this process:

index.tsx
const myArray = new Array(5).fill(5);  // create an array with a length of 5 and fill it with 5s
console.log(myArray);  // output: [5, 5, 5, 5, 5]
147 chars
3 lines

gistlibby LogSnag