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:
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:
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:
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:
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:
1fruits.pop();
2console.log(fruits); // Output: ['apple', 'grape', 'orange']
This will remove the last element 'pear'
from the fruits
array.
xxxxxxxxxx
// Example of creating and accessing elements in an array
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits[0]); // Output: apple
// Example of modifying elements in an array
fruits[1] = 'grape';
console.log(fruits); // Output: ['apple', 'grape', 'orange']
// Example of adding elements to an array
fruits.push('pear');
console.log(fruits); // Output: ['apple', 'grape', 'orange', 'pear']
// Example of removing elements from an array
fruits.pop();
console.log(fruits); // Output: ['apple', 'grape', 'orange']