JavaScript arrays are like lists that can hold multiple items under one variable name.
These items, called elements, can be anything from numbers and strings to other arrays or objects.
Arrays are useful because they let you group related data together and perform operations like sorting, filtering, and looping over the data.
Arrays in JavaScript are zero-indexed, which means the first element is at index 0, the second at index 1, and so on. You can create an array using square brackets []
, and elements are separated by commas.
For example, let fruits = ['apple', 'banana', 'cherry'];
creates an array with three fruits.
You can access elements using their index, like fruits[0]
to get 'apple'.
You can also change elements, add new ones, or remove them.
JavaScript provides many built-in methods to work with arrays, such as .push()
to add an element at the end, .pop()
to remove the last element, .map()
to transform elements, and .filter()
to get a subset of elements that meet a condition.
10 Example Code Snippets
Create an Array:
let colors = ['red', 'green', 'blue'];
Access an Element:
let firstColor = colors[0]; // 'red'
Change an Element:
colors[1] = 'yellow'; // colors is now ['red', 'yellow', 'blue']
Add an Element:
colors.push('purple'); // colors is now ['red', 'yellow', 'blue', 'purple']
Remove the Last Element:
let lastColor = colors.pop(); // 'purple', colors is now ['red', 'yellow', 'blue']
Find the Length of an Array:
let numberOfColors = colors.length; // 3
Loop Through an Array:
colors.forEach(color => { console.log(color); }); // Outputs: red, yellow, blue
Map Over an Array:
let upperCaseColors = colors.map(color => color.toUpperCase()); // upperCaseColors is ['RED', 'YELLOW', 'BLUE']
Filter an Array:
let longColors = colors.filter(color => color.length > 4); // longColors is ['yellow']
Check if an Element Exists:
let hasGreen = colors.includes('green'); // false