In JavaScript, an array is an ordered collection of data elements. Each element can be of a different data type, and the elements are stored in a contiguous block of memory.
You can create an array in JavaScript using square brackets []
and separating the elements with commas. For example:
const numbers = [1, 2, 3, 4, 5];
const words = ['apple', 'banana', 'orange'];
const mixed = [1, 'apple', true, null];
You can access the elements of an array using their index, which starts at 0 for the first element and goes up to the length of the array minus 1 for the last element. For example:
console.log(numbers[0]); // prints 1
console.log(words[1]); // prints 'banana'
console.log(mixed[2]); // prints true
You can also use the length
property to get the number of elements in an array:
console.log(numbers.length); // prints 5
JavaScript arrays are dynamic, which means you can add or remove elements from them. Here are some examples:
// Adding elements to the end of an array
numbers.push(6); // numbers is now [1, 2, 3, 4, 5, 6]
words.push('pear'); // words is now ['apple', 'banana', 'orange', 'pear']
// Removing elements from the end of an array
numbers.pop(); // numbers is now [1, 2, 3, 4, 5]
words.pop(); // words is now ['apple', 'banana', 'orange']
// Adding elements to the beginning of an array
numbers.unshift(0); // numbers is now [0, 1, 2, 3, 4, 5]
words.unshift('kiwi'); // words is now ['kiwi', 'apple', 'banana', 'orange']
// Removing elements from the beginning of an array
numbers.shift(); // numbers is now [1, 2, 3, 4, 5]
words.shift(); // words is now ['apple', 'banana', 'orange']
JavaScript also provides a number of methods for manipulating arrays, such as sort
for sorting the elements, splice
for adding or removing elements at a specific index, and map
and filter
for creating new arrays based on the elements of an existing array.