Javascript day 5

Arrays

Arrays allow us to store multiple elements in the same 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 .length property
  • get elements by index (starting from [0])
  • use .at(index), which accepts negative indices

Adding an element

We can add an element to the end of an array using the .push() method.

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 a const is that once we define it as an array, it will always stay as an array; however, the array contents 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);

I will edit this post later, as I don't want to rush past this concept. That's about it for today. I'm going to get back to more arrays and callback concepts tomorrow!