Array with() Method in JavaScript

Level 3129 keystrokes

The with() method returns a new array with a specific element replaced at a given index.

JavaScript code

// Create an array of colors
1const colors = ["red", "green", "blue"];
// with(1, "yellow") replaces element at index 1 in a new array
2const newColors = colors.with(1, "yellow");
// Output the new array with replacement: ["red", "yellow", "blue"]
3console.log(newColors);
// Original array remains unchanged: ["red", "green", "blue"]
4console.log(colors);

Output

[ 'red', 'yellow', 'blue' ]
[ 'red', 'green', 'blue' ]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • "× 8
  • ;× 4
  • ,× 3
  • .× 3
  • (× 3
  • )× 3
  • =× 2
  • [× 1
  • ]× 1

More JavaScript examples at level 3

← JavaScript typing practice