Code Highlights logo

Learn

Arrays

Arrays with let and const

Using let with Arrays:

The let keyword allows us to declare variables that can be reassigned. When using let with arrays, we can update the array elements and even reassign the array entirely. Here's an example:

1let fruits = ['apple', 'banana', 'orange'];
2fruits[0] = 'pear'; // Update the first element
3fruits.push('grape'); // Add a new element
4fruits = ['kiwi', 'pineapple']; // Reassign the entire array

By using let, we have the flexibility to modify and reassign the array as needed.

Using const with Arrays:

The const keyword, on the other hand, creates variables that cannot be reassigned. When using const with arrays, we can still modify individual elements, but we cannot assign a new array to the variable. Let's see an example:

1const colors = ['red', 'green', 'blue'];
2colors[1] = 'yellow'; // Update the second element
3colors.push('purple'); // Add a new element
4
5// The following line will result in an error
6colors = ['pink', 'orange'];

With const, we can be certain that the array itself cannot be overwritten, providing a level of immutability and stability to our code. code.


Instructions

1.

Declare a constant variable named fruits and assign it an array of strings containing the names of some fruits, at least 4 elements.

2.

Access and print the third element of the fruits array using index notation.

3.

Update the fourth element of the fruits array to be "banana" using index notation.

4.

Print the updated fruits array.

Sign up to start coding

Already have an account?

Sign In

Course content