Accessing an array element:
Each element in an array has a numbered position known as an index. Arrays in JavaScript are zero-indexed, meaning that the counting of array elements starts from 0.
If we want to access the array element, we can do this by calling the array name with square brackets and the index number inside the brackets.
In the example above, cities[0] means we can access the array element at index 0, which means ‘New York’.
We can access individual characters in a string using bracket notation and index.
const hello = "Hello World"; console.log(hello[6]); // Output: W
Updating an array element:
Once you have access to an element in an array, you can update its value.
Update an array with index number:
In the example above, seasons array contains four elements, we want to update or change the value ‘Fall’ to ‘Autumn’.
We can do this by calling the array seasons with square brackets and index numbers. Here ‘Autumn is a value we will change or update in place of ‘Fall’.
Update an array with a map():
let arr = [1, 2, 3];
let removed = arr.map((item) => (item === 2 ? 20 : item));
console.log(removed);
Result: [1, 20, 3]
Post a Comment