A Super quick guide to arrow functions

I added a video version of this blog. If you prefer video, check it out: https://youtu.be/HC2W75WMw6c

This is NOT a definitive guide to arrow functions. I’m writing a few other tutorials and blogs and want to have something to point people to so they can have a quick explanation and example of arrow functions since they are in so many of the modern frameworks. Just enough to be dangerous! To be clear, there are reasons where you should not use arrow functions, but they are not going to be discussed in this blog post. I just want you to be able to know how they work when you see them “in the wild”.

Let’s get started. I’m going to take you step by step converting a regular function into an arrow function.

Here’s a regular function using the function keyword

Let’s change that to an anonymous function expression

Should be nothing new here so far. No Arrows or ES6 yet, but here it comes…

First remove the function keyword and add the arrow

The only thing going on there is removing the function keyword and adding the arrow. And that’s it! You’ve gone and made an arrow function! Hurray! But wait, there’s more!

If there is only one argument, you can get rid of the parentheses around it.

Getting pretty lean but we can take it even further. If the body of the code is only one line, we can get rid of the curly braces.

Frequently, you’ll see these used as a callback in another function so there is no const and no function name. This is the case that we see quite a bit and the real reason I wrote this all up in the first place

This doesn’t do anything on its own, but as a callback it’s useful. Here we’re using as a callback for looping over an array with the forEach array method.

As a comparison, here’s a regular old for loop. Sure, we understand this as programmers, but the arrow function just reads like a sentence in normal language. So much easier to understand!

I think that covers the basics. Again this is not meant to be the definitive guide, just an intro to figure out what they mean because we see them ‘in the wild’ in all the modern frameworks.

Just Enought JavaScript To Be Dangerous

I made a series of videos on my youtube channel about the basics of JavaScript. These might not be the best for the total beginner and it’s not meant to be a “learn everything about JavaScript deeply” kind of a course. They might be best suited for someone who has started to learn JavaScript and needs a refresher. It goes pretty quickly and it might gloss over a few things. My goal was to get to doing something more useful quickly. I’m pretty sure nobody ever said “The day I knew web development was for me was the day the computer confirmed for me that racecar spelled backward is in fact racecar”. I wanted to get to making things actually happen on the page ie. DOM manipulation, event listeners, etc. sooner than later.

Event Delegation in JavaScript

You don’t always have to write event listeners for everything. Event delegation lets you add one listener to the parent element and then use the information from the created event object to tell which child element was the target of the event. Here’s how it’s done.

REST API in Node/Express – live coding

The latest thing I’ve been live coding is a REST API in Node/Express.

https://www.youtube.com/channel/UCqdNQHOLz3PmB4cDvQkdQ1w/videos

Admittedly, the videos are kind of slow paced because, to be honest, I’m figuring it out as I go!  My goal with this series is to re-record it into more of a formal tutorial on building a REST API.   So, stay tuned for that.  What should I live code next?  React, ES6, something else?  I’d love to hear from you.

How to write your own forEach method in Javascript – Part 2

So let’s get started on writing our own version of .forEach.  Here is the starter code given in the git repo

1 // ===================== EACH =====================
2 // Call iterator(value, key, collection) for each element of collection.
3 // Accepts both arrays and objects.
4 //
5 // Note: each() does not have a return value, but rather simply runs the
6 // iterator function over each item in the input collection.
7
8     var each = function(collection, iterator) {
9      // Write your code here
10   };

So there are a few things going on here.  The best thing to do when approaching a coding problem is to break the larger problem down into manageable chunks.  Let’s start by understanding what they are really asking for here.

The first line tells us what is supposed to happen inside our function.  Call a function with some arguments for each element of a collection.  What do they mean by collection?  While forEach is typicall thought of as an array method, this challenge is asking for us to accept both arrays and objects so collection refers to whichever one is passed in.  Keeping with our simple chunks idea, let’s start with only worrying about arrays.  We’ll get to the other parts soon.

So we’re doing something to every item in an array.  So if that doesn’t make you say “we need some kind of a loop” then you’re probably not ready for this blog post!

The term iterator was a bit confusing at first.  Dictionary.com doesn’t even list it, even as a form of iterate.  thefreedictionary.com redirects it to the listing enumerator and gives us “a person or thing that enumerates”.  Ok so we’re getting the idea here, it’s the thing that repeats.  In our case, what we are trying to repeat is a function. 

Ok, what about our parameters?  Value is referring to the current value of the array we are looping over.   Key is the position in the array.  Collection is the array we are working on.  This is a bit different than .forEach is a method that is attached to the array.  We’re making a function of our own so we include the array as an argument.  So when we’re done, instead of saying:

ourArray.forEach(someFunction)

we will say

each(ourArray, someFunction)

So for me, this would have have been much easier to grasp if they had said

// Call someFunction(value, key, collection)
or
// Call someFunction(currentArrayItem, index, ourArray)

But maybe I just need to work on my vocabulary!  So let’s get some code down finally.  So we plug that function call into our starter code.

const each = function(collection, iterator) {
 someFunction(currentArrayItem, index, ourArray)
};

Great!  We’ve got a function that calls a function.  But it still doesn’t do anything.  We are supposed to call this function for each item in our collection, in our case, an array.  So here comes the for loop with our function inside the block.

const each = function(collection, iterator) {
  for (let i = 0; i < collection.length; i++) {
    iterator(collection[i], i, collection)
  }
};

It doesn’t satisfy all the requirements yet, but this basically works already.  Check it out here: https://repl.it/NrWI/1

We need this to work on objects too so let’s make a version that works on objects.  Remember that arrays are actually objects, so this shouldn’t be too much different.  We can use a “for in” loop which goes something like this:

const each = function(collection, iterator) { 
  for (let key in collection) { 
    iterator(collection[key], key, collection) 
  }
};

Pretty similar and here is the working example: https://repl.it/NrYS/1

All that’s left if to test the input to decide if it an array or object.  We could use the typeof operator, but arrays are objects too in JS so that won’t work.  Fortunately we can use Array.isArray().  For example:

Array.isArray([1, 2, 3]); // returns true
Array.isArray({one:1, two:2}); // returns false

So we just us an if statement to decide which one to use and we’re done.

const each = function(collection, iterator) {
 if (Array.isArray(collection)) {
   for (let i = 0; i < collection.length; i++) {
     iterator(collection[i], i, collection);
   }
 } else {
   for (let key in collection) {
     iterator(collection[key], key, collection);
   }
 }
};
// call the function with:
// each(collection, iterator);

What about the access to index and collection part?  That will depend on your iterator function.  If you only have one argument, it will only work with the current array or object item.  If you use two arguments, it will work with the current item and the index, and finally, if you use three arguments the third will use the original array (or object).  You can check it out here: https://repl.it/Nv1q/2

Well, I hope this explanation can be of some help for anyone struggling to understand what is going on under the hood of forEach.  Please feel free to reach out to me if you have any questions, comments, or corrections.

This was my first attempt at a technical blog post, so be nice!  🙂