Mark As Completed Discussion

Arrays

Arrays are one of the most commonly used data structures in JavaScript. They allow you to store multiple values in a single variable. Each value in an array is called an element, and each element has a numeric index that represents its position in the array.

Creating Arrays

You can create an array in JavaScript by enclosing a comma-separated list of values in square brackets. For example:

JAVASCRIPT
1const fruits = ['apple', 'banana', 'orange'];

In this example, we create an array called fruits that contains three elements: 'apple', 'banana', and 'orange'.

Accessing Array Elements

To access a specific element in an array, you can use its index. Array indices start at 0, so the first element is at index 0, the second element is at index 1, and so on. For example:

JAVASCRIPT
1console.log(fruits[0]); // Output: apple

This will log the first element 'apple' to the console.

Modifying Array Elements

You can modify the value of an element in an array by assigning a new value to its index. For example, to change the second element 'banana' to 'grape', you can do:

JAVASCRIPT
1fruits[1] = 'grape';
2console.log(fruits); // Output: ['apple', 'grape', 'orange']

This will modify the second element from 'banana' to 'grape'.

Adding Elements to an Array

You can add elements to the end of an array using the push() method. For example, to add the element 'pear' to the fruits array, you can do:

JAVASCRIPT
1fruits.push('pear');
2console.log(fruits); // Output: ['apple', 'grape', 'orange', 'pear']

This will add the element 'pear' to the end of the fruits array.

Removing Elements from an Array

You can remove the last element from an array using the pop() method. For example, to remove the last element 'pear' from the fruits array, you can do:

JAVASCRIPT
1fruits.pop();
2console.log(fruits); // Output: ['apple', 'grape', 'orange']

This will remove the last element 'pear' from the fruits array.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment