feat(curriculum): Add interactive examples to How Do You Access and Update Elements in an Array (#63282)

Co-authored-by: Ilenia <26656284+ilenia-magoni@users.noreply.github.com>
This commit is contained in:
Clarence Bakosi
2025-10-30 12:10:09 +01:00
committed by GitHub
parent fff30399b5
commit 1a8e023021
@@ -5,39 +5,55 @@ challengeType: 19
dashedName: how-do-you-access-and-update-elements-in-an-array
---
# --description--
# --interactive--
In the previous lesson, you were first introduced to working with arrays and accessing different elements from arrays. Here is a reminder on how to access the second element from an array:
:::interactive_editor
```js
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[1]); // "banana"
```
:::
Since arrays are zero based indexed, the first element will be at index `0`, the second index will be at index `1`, etc. It's important to note that if you try to access an index that doesn't exist in the array, JavaScript will return `undefined`.
:::interactive_editor
```js
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[3]); // undefined
```
:::
In this example, there is no index `3` for the `fruits` array. So the log will show `undefined`. Now, let's look at how to update elements in an array. You can update an element by assigning a new value to a specific index.
:::interactive_editor
```js
let fruits = ["apple", "banana", "cherry"];
fruits[1] = "blueberry";
console.log(fruits); // ["apple", "blueberry", "cherry"]
```
:::
In this example, we've replaced `banana` with `blueberry` at index `1`. This method allows you to change any element in the array, as long as you know its index. You can also add new elements to an array by assigning a value to an index that doesn't yet exist:
:::interactive_editor
```js
let fruits = ["apple", "banana", "cherry"];
fruits[3] = "date";
console.log(fruits); // Outputs: ["apple", "blueberry", "cherry", "date"]
console.log(fruits); // ["apple", "blueberry", "cherry", "date"]
```
:::
However, exercise caution when doing this. If you assign a value to an index that is much larger than the current length of the array, you will create undefined elements for the indices in between, which can lead to unexpected behavior. As you continue to work with JavaScript, you'll find that these ways of accessing and updating array elements are fundamental to many programming tasks. Whether you're building a simple todo list or processing complex data structures, these skills will be invaluable.
# --questions--