fill 5 elements in an array with a static value in javascript

To fill an array with a static value in JavaScript, you can use the fill() method available on Array objects. This method allows you to fill all the elements in an array with a specified static value.

The syntax for using fill() method is as follows:

index.tsx
arr.fill(value, start, end)
28 chars
2 lines

where

  • value is the static value to fill the array with
  • start (optional) is the index to start filling the array from (default is 0)
  • end (optional) is the index (exclusive) to stop filling the array at (default is array length)

To fill an array with 5 elements with a static value of 0, you can create a new array of size 5 and use the fill() method as shown below:

index.tsx
let myArray = new Array(5);
myArray.fill(0);
console.log(myArray); // Output: [0, 0, 0, 0, 0]
94 chars
4 lines

In this example, we create a new array myArray of size 5 using new Array(5) and then use the fill() method to fill all the elements with the static value of 0. Finally, we log the array to the console, which outputs [0, 0, 0, 0, 0].

gistlibby LogSnag