fill the elements in an array with number 5 in javascript

To fill an array with the number 5, we can use the fill() method on the array object. Here's an example:

index.tsx
const arr = new Array(10);
arr.fill(5);
console.log(arr); // Output: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
100 chars
4 lines

In the above example, we first create an empty array with a length of 10. We then fill the entire array with the number 5 using the fill() method. Finally, we log the contents of the array to the console.

Alternatively, you can also fill an array with the number 5 using a loop:

index.tsx
const arr = new Array(10);
for (let i = 0; i < arr.length; i++) {
  arr[i] = 5;
}
console.log(arr); // Output: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
142 chars
6 lines

In this example, we iterate over the length of the array using a for loop and set each element of the array to the number 5. The end result is the same as the first example.

gistlibby LogSnag