javascript set array index value code example

Example 1: access index of array javascript

let first = fruits[0]
// Apple

let last = fruits[fruits.length - 1]
// Banana

Example 2: set element at index javascript array and create new array

const items = [1, 2, 3, 4, 5]

const insert = (arr, index, newItem) => [
  // part of the array before the specified index
  ...arr.slice(0, index),
  // inserted item
  newItem,
  // part of the array after the specified index
  ...arr.slice(index)
]

const result = insert(items, 1, 10)

console.log(result)
// [1, 10, 2, 3, 4, 5]

Tags:

Java Example