JavaScript Arrays
In JavaScript, an array is a special type of object used to store multiple values within a single variable. Arrays can contain elements of any data type, including numbers, strings, objects, functions, or even other arrays, and they can dynamically grow or shrink in size as needed.
Here’s how you can create and work with arrays in JavaScript:
Creating Arrays:
// Array literal syntax
let fruits = ['apple', 'banana', 'orange'];
// Using the Array constructor
let cars = new Array('Toyota', 'Honda', 'BMW');
// An array can hold elements of different types
let mixedArray = [1, 'two', true, { name: 'John' }];
Accessing Array Elements:
console.log(fruits[0]); // Output: 'apple'
console.log(cars[1]); // Output: 'Honda'
Modifying Array Elements:
fruits[1] = 'grape'; // Change the value at index 1 to 'grape'
console.log(fruits); // Output: ['apple', 'grape', 'orange']
Array Length:
console.log(fruits.length); // Output: 3
Adding Elements to an Array:
fruits.push('kiwi'); // Adds 'kiwi' to the end of the array
console.log(fruits); // Output: ['apple', 'grape', 'orange', 'kiwi']
fruits.unshift('lemon'); // Adds 'lemon' to the beginning of the array
console.log(fruits); // Output: ['lemon', 'apple', 'grape', 'orange', 'kiwi']
Removing Elements from an Array:
fruits.pop(); // Removes the last element ('kiwi')
console.log(fruits); // Output: ['lemon', 'apple', 'grape', 'orange']
fruits.shift(); // Removes the first element ('lemon')
console.log(fruits); // Output: ['apple', 'grape', 'orange']
Iterating Over Arrays:
fruits.forEach(function(fruit) {
console.log(fruit);
});