Mark As Completed Discussion

Arrays

In JavaScript, arrays are used to store multiple values in a single variable. You can think of an array as a collection of items arranged in a specific order.

Creating an Array

To create an array in JavaScript, you can use square brackets [] and separate each item with a comma. Here's an example:

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

Accessing Array Elements

Array elements are accessed using their index. The index starts at 0 for the first element, 1 for the second element, and so on. Here's how you can access array elements:

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

Modifying Array Elements

You can modify elements in an array by assigning a new value to a specific index. For example, let's change the second element in the fruits array to 'pear':

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

Array Methods

JavaScript provides several built-in methods for manipulating arrays. Here are some commonly used methods:

  • push(): Adds one or more elements to the end of an array.
  • pop(): Removes the last element from an array.
  • splice(): Adds or removes elements from a specific position in an array.
  • shift(): Removes the first element from an array.

Here's an example that demonstrates these methods:

JAVASCRIPT
1const fruits = ['apple', 'banana', 'orange', 'mango'];
2
3fruits.push('grape');
4console.log(fruits); // Output: ['apple', 'banana', 'orange', 'mango', 'grape']
5
6fruits.pop();
7console.log(fruits); // Output: ['apple', 'banana', 'orange', 'mango']
8
9fruits.splice(2, 0, 'kiwi', 'pineapple');
10console.log(fruits); // Output: ['apple', 'banana', 'kiwi', 'pineapple', 'orange', 'mango']
11
12fruits.shift();
13console.log(fruits); // Output: ['banana', 'kiwi', 'pineapple', 'orange', 'mango']

Arrays are incredibly useful when working with lists or collections of data. They allow you to perform various operations such as adding, removing, and modifying elements.

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