
Join the Conversation!
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.
In this lesson, you'll learn about arrays in JavaScript, a fundamental data structure used to store ordered collections of elements.
In programming, we often need an ordered collection where we have a 1st, 2nd, 3rd element, and so on. For example, we might need this to store a list of users, items, or elements.
JavaScript provides a special data structure named to store ordered collections.
This is how we declare an array, the most important part here is the square brackets :
const months = ['January', 'February', 'March', 'April'];
Array elements are numbered, starting with zero.
We can get an element by its index using square brackets :
console.log(months[0]); // 'January'
We can replace an element:
months[2] = 'Not March'; // [ 'January', 'February', 'Not March', 'April' ]
Or add a new one to the array:
months[4] = 'May'; // [ 'January', 'February', 'Not March', 'April', 'May' ]
The total count of the elements in the array is its :
console.log(months.length); // 5
An array can store elements of any type:
const arr = [
'Apple',
{ name: 'John' },
true,
function() {
console.log('hello');
}
];
You'll often need to loop through all the elements of an array. That's where the loop comes in handy:
for (let i = 0; i < months.length; i++) {
console.log(months[i]);
}
Later, we'll dedicate a few lessons to different built-in for looping. These methods allow us to loop faster, with added functionality and less code. are a powerful tool in JavaScript, enabling you to manage collections of data efficiently.
"Please login to view comments"
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.