Changing an array elements in JavaScript

Array elements can be changed:

let arr = ['a', 'b', 'c']; arr[0] = '!'; console.log(arr); // shows ['!', 'b', 'c']

Create an array with the elements 'a', 'b', 'c'. Write the number 1 instead of the first element, 2 instead of the second, 3 instead of the third.

Overwriting elements

You can also read the current value of an element, perform some operation on it, and write the changed value back to that element:

let arr = ['a', 'b', 'c']; arr[0] = arr[0] + '!'; arr[1] = arr[1] + '!'; arr[2] = arr[2] + '!'; console.log(arr); // shows ['a!', 'b!', 'c!']

The previous code can be rewritten using the operator +=:

let arr = ['a', 'b', 'c']; arr[0] += '!'; arr[1] += '!'; arr[2] += '!'; console.log(arr); // shows ['a!', 'b!', 'c!']

Create an array with numbers. Add the number 3 to each element of the array. Display the modified array on the screen.

Increment and decrement

You can also use increment and decrement operations:

let arr = [1, 2, 3, 4]; arr[0]++; ++arr[1]; arr[2]--; --arr[3]; console.log(arr); // shows [2, 3, 2, 3]

Create an array with elements 1, 2 and 3. Use the ++ operator to increase each array element by one.

enru