I had a lot of energy today and I was more focused. I was able to finish 2 section of Colt Steele’s Web Dev Bootcamp. That’s about 2-3 hours of classes.

As I mentioned before, most of these are refreshers. However, I am glad I am still looking at it even in double speed. There are actually stuff that he teaches that I didn’t know about. For example, I didn’t know that you can add your own method to an Array. More about that later.

Aside from this, I also worked on our project-newbs project. I wanted to keep on getting better at building navs from scratch to help solidify my knowledge. So, I took on this issue.

I was much faster than the other times I did it. I used flexbox to build it and it was pretty easy. I also don’t feel like it is too hacky. It feels like that’s how it’s supposed to be. Here’s what it looks like.

So, now, let me teach you how to create your own array method.

Class Starts Now

Yesterday, I talked about loops.  One thing I didn’t talk about is the forEach loop. What is the forEach loop? This loop is an array method that allows you to loop through an array. It takes in one argument, a function.  It provides 3 parameters to the function that you pass to it.

  1. An element of the array
  2. The index of the array
  3. The Array itself.

Here’s how it would work.

let myNumbers = [1, 3, 5, 7, 9];

myNumbers.forEach(function(num, index, myArray) {
  myArray[index] = num * 2;
}

// This would double the values on the array numbers
// myNumbers will now be[2, 6, 10, 14, 18]

As you can see, by using the forEach loop, we don’t need to know the length of the array or even create conditions and iterators to ensure the loop stops. The method itself does this for us.

It’s pretty cool, right?

Now that we are talking about Array methods, let me teach you how to create your own Array method.

We need to define the method. We need to use Array.prototype to do this. Then, we have to name our method. After that, we assign it the function that we want to be executed on the array. Here’s a sample definition that multiplies each value of the array by 5.

Array.prototype.multiplyByFive = function() {
  for(let x = 0; x < this.length; x++) {
    this[x] = this[x] * 5;
  }
}

// We can then call this method on an Array

let myNumbers = [1, 3, 5, 7, 9];

myNumbers.multiplyByFive();

// myNumbers will now be [ 5, 15, 25, 35, 45 ]

When defining the Array method, you would need to use the this keyword. this basically represents the current element in the array.

As you can see this is really powerful stuff. Even though we already have built in methods to arrays, we are able to extend the capabilities of Arrays by defining our own methods.

Please let me know if you have any questions.

 

 

Day[14] - A Little Bit of Rest Day - I'll Teach you About Loops
Day[16] - Project Update - Project Newbs

Leave a Comment

Your email address will not be published. Required fields are marked *