JavaScript Arrays
In JavaScript, arrays are used to store multiple values in a single variable.
They can hold values of any data type, including numbers, strings, objects, or even other arrays.
Arrays in JavaScript are dynamic, meaning their size can be changed dynamically by adding or removing elements.
Example
const fruits = ['apple', 'banana', 'orange'];
Creating Arrays:
syntax
const array_name = [item1, item2, ...];
Modifying Elements:
You can modify elements in an array by assigning new values to specific indices.
Example
fruits[2] = 'grape'; console.log(fruits); // Output: ['apple', 'banana', 'grape']
Array Length:
You can get the length of an array using the length property.
Example
console.log(fruits.length); // Output: 3
Adding Elements:
You can add elements to the end of an array using the push() method.
Example
fruits.push('pineapple'); console.log(fruits); // Output: ['apple', 'banana', 'grape', 'pineapple']
Removing Elements:
You can remove elements from the end of an array using the pop() method.
Example
fruits.pop(); console.log(fruits); // Output: ['apple', 'banana', 'grape']
Iterating Over Arrays:
You can loop through the elements of an array using for loops or array methods like forEach().
Example
for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); } fruits.forEach(function(fruit) { console.log(fruit); });
Accessing the First Array Element
To access the first element of an array in JavaScript, you can use array indexing. Array indexing starts at 0, so the first element of the array has an index of 0. Here's how you can access the first element:
Example
const array = [10, 20, 30, 40, 50]; const firstElement = array[0]; console.log(firstElement); // Output: 10
Accessing the Last Array Element
To access the last element of an array in JavaScript, you can use array indexing combined with the length property of the array. Here's how you can access the last element:
Example
const array = [10, 20, 30, 40, 50]; const lastElement = array[array.length - 1]; console.log(lastElement); // Output: 50
Looping Array Elements
1. Using a for Loop:
Example
const array = [10, 20, 30, 40, 50]; for (let i = 0; i < array.length; i++) { console.log(array[i]); }
2. Using a forEach Loop:
Example
const array = [10, 20, 30, 40, 50]; array.forEach(function(element) { console.log(element); });
3. Using a for...of Loop:
Example
const array = [10, 20, 30, 40, 50]; for (const element of array) { console.log(element); }
4. Using the map Function: