Arrays are where you can store multiple elements in the same variable. You can store numbers, strings, booleans, arrays, objects, etc.
Examples:
const numbers = []; // empty array
const ages = [10, 21, 35, 45]; // array of numbers
const names = ['Dutches', 'Monty', 'Benny', 'Lucky', 'Chili']; // array of strings
const mixAndMatch = [25, false, 'Brody'] // mixed
.length property
.length
property gives the number of elements in an array.
Examples:
[].length; // 0
const numbers = [22, 35, 43, 49, 98];
numbers.length; // 5
.length
is a property of objects that are instances of type array. Objects have a property, and that property tracks length. So length is like an object key. Calling it will return that value.
Get Element by Index
If you use square bracket [] syntax with an index starting at 0, you can retrieve a specific element from an array.
For example:
const members = ['Dutches', 'Monty', 'Benny', 'Lucky', 'Chili'];
members[2]; // 'Benny'
You can alternatively use the .at(index)
method, which makes it simpler to locate the array's final element because it permits negative indices.
const members = ['Dutches', 'Monty', 'Benny', 'Lucky', 'Chili'];
members.at(3); // 'Lucky'
members.at(-2); // 'Lucky'
.push() method
The .push()
method can be used to add an element to an array.
const ages = [12, 25, 45, 49];
ages.push(64);// returns 5 (the new length of the array)
console.log(ages); // [12, 25, 45, 49, 64];
Array.push()
returns the new length of the array.
We were able to add new data into the variable ages even though it was defined with const
. The const
states that once a variable is defined, it can only be assigned once. The variable may not always be immutable, but the contents are flexible.
Array.forEach()
One of the most important concepts in javascript is array iteration.
Let's imagine you want to loop (or iterate) through every element in an array of ages.
const ages = [21, 35, 49];
ages.forEach(function(age) {
// do something with individual age
console.log(age);
});
Always begin your .forEach()
with a console.log()
so you can visualize the transition from array to array item.
The callback function can be executed for each element in the array using the .forEach(callback)
method.
A callback
is a function definition passed as an argument to another function.
function(ages) {
// do something with individual age
console.log(grade);
}
When a grade is received, this callback function logs it to the console. This is a function definition because it's not being executed. It just describes how the function will behave. On the other hand, the .forEach()
method receives this function definition as an argument.
ages.forEach(callBackHere);
When you combine them together, pass the function definition as an argument to the .forEach()
method:
ages.forEach(function(age) {
// do something with individual age
console.log(age)
});
The code above will print each age from the ages array to the console.
21
35
49
Top comments (0)