Javascript day 5
Arrays
Arrays enable us to store multiple elements in a single variable. We can store numbers, strings, booleans, arrays, objects, and more. These can be mixed within the same array.
Naming arrays in the plural form will be useful when we need to iterate over them.
We can
- use the
.lengthproperty - get elements by index (starting from [0])
- use
.at(index), which accepts negative indices
Adding an element
We can add a new element to the end of an array using the .push() method, but remember that this method returns the new length of the array.
const numbers = [10, 8, 13, 15];
numbers.push(20); // returns 5
console.log(numbers); // [10, 8, 13, 15, 20]
// Array.push() returns the new length of the array.
Arrays & const
The benefit of declaring an array as const is that once we define it as an array, it will always remain an array; however, the contents of the array can change.
const numbers = []; // start with an empty array
numbers.push(10); // returns 1
console.log(numbers); // [10] (still an array, but content changed)
Array forEach
Let's say we have an array of grades and we'd like to loop (iterate) over every item in this array. Here’s how we do it.
const grades = [10, 8, 13];
grades.forEach(function(grade) {
// do something with each grade
console.log(grade);
});
// Always start with a console.log() inside our .forEach so that we can visualize the shift from array to array item.
The .forEach(callback) method allows us to run the callback function for every item in that array. Callbacks will be explained in depth later. Let's start with a basic definition.
A callback is a function definition passed as a parameter to another function. In our example above, here’s the callback function:
function(grade) {
// do something with each grade
console.log(grade);
}
This callback function receives a grade and then logs it to the console. This is a function definition because it's not being executed—it defines the behavior of the function. However, this function definition is passed as an argument to the .forEach() method:
grades.forEach(insert_callback_here);
What is the difference between parameters and arguments?
Think of it like this: parameters are the empty slots in a form, and arguments are the actual data you fill into those slots.