Arrow functions in JavaScript ES6

Out of the many wonderful ES6 features arrow functions are one of the most used and also save developers a lot of time since it shortens code so much! So I thought I would write a tutorial regarding arrow functions as well as give examples of its usage in addition to explain the dreaded “this” and how it changes due to the implementation of arrow functions… Ok, here we go!

Valentin Serov painting

The main purpose of arrow functions is to shorten the syntax required when writing a function. Below is an example of a function “pre ES6”.

var myName;
myName = function(){
return "Alex";
}

This code is 38 characters long, however, if we implement this using an arrow function there will be significantly less code. An example of this is below.

myName = () =>{
return "Alex";
}

Our code is now 32 characters long, although that does not seem like a lot we can shorten the function even more so. Since inside of our function we are only returning a value and not doing anything else within the function we can remove the “return” keyword and just leave “Alex” instead. Our code has decreased from 38 characters to 25!

myName = () =>{
“Alex”
};

However, with a lot of functions you will need to have parameters, luckily for us arrow functions accommodate this, we include parameters inside of the brackets as usual, however, if you only have one parameter required to go into your function you can remove the “()” brackets from the function, otherwise you are required to enter your parameter list in between the brackets. Two examples are below.

myName = (lastName) =>{
return “Alex ” + lastName;
}
myName = lastName =>{
return “Alex “ + lastName;
}

When you are concatenating a string and variable within an arrow function you can also remove the “return” keyword from within the function, let me show you an example below using an arrow function inside of a “map” call.

var favouriteShows = [
'Breaking Bad',
'Peep Show',
'MindHunter',
'Narcos'
];
favouriteShows.map(element => {
console.log(element);
});

Above we have an array of my favourite shows and we are doing a simple “map” i.e. iteration over every element in the array and printing them to the console, as you can see I have not written map as:

favouriteShows.map(function(element){
console.log(element);
});

As I am far too lazy for that and so are a lot of programmers! haha, so within a map as long as we only have one parameter we can remove the brackets from the parameter as well as the word “function” thus dramatically decreasing the amount of code we actually have to write.

The dreaded “this” in JavaScript

Pre ES6 every function call defined it’s own “this” and thus by default is referred to the global object of the DOM, a quick example is below.

function car(){
console.log(this.colour);
}
var colour = 'red';
car();

If you were to run this code then you’d see that the colour printed onto the console is ‘red’, because the ‘this’ keyword is looking in the global object for a variable ‘color’ as the context of where the ‘this’ gets executed from is not defined, however, if we create an object and place the bike method inside of this then we will get a different result since we have defined a “context of execution”.

function car() {
console.log(this.colour);
}
var colour = "red";
var myObjectOne = { colour: "green", car: car };
var myObjectTwo = { colour: "yellow", car: car };
car();           
myObjectOne.car();
myObjectTwo.car();

So as you can see the two colours that will be printed out is “red” first because it is using the global context so will look for a variable “colour” within the global context , whereas, the second colour printed out is green because we defined the “colour” inside the “myObjectOne” variable so when we call “myObjectOne.car()” the object of execution is “myObjectOne” so it will look for a “car” property inside of this variable and print the “this.colour” property of the “myObjectOne” variable.

“This” in the context of arrow functions

An arrow function doesn’t define its own “this”, it uses its parents “this” context instead. In ES5 you can use workarounds such as the “.bind” method and defining a variable inside of the function you wish to define its own “this” context like the below.

var that = this;

Below is an example of how a successful arrow function uses “this”

function Myself(){  this.myAge = 24;  setInterval(() => {    this.myAge++; // this refers to the myself object  }, 1000);}var myVariable = new Myself();

In the example above since an arrow function does not bind its own “this” the “this.myAge” value inside of the “setInterval” function is the same as the “this.myAge” value outside of the arrow function.

I hope you have learned something from this article, and as always if you have any criticisms or feedback I am more than happy to listen and learn from them, thank you and have a good day 🙂

Map, Filter & Reduce in JavaScript

Map

This function returns a new array with a callback function acting upon every element within the array. Map will run a callback function that takes 3 arguments. The first being the “current item” in the array (this is a required argument), the second being the “index” within the array of the current item (this is an optional argument), finally, the last argument in the callback is the entire array itself (this is also an optional argument).

Here is an example of an array of objects I have created which contains a few of my favourite movies (Don’t judge me!), each with their movie name and the name of the actresses/actors who starred in them.

var favouriteMovies = [
{'name':'aliens','mainStar':'Sigourney Weaver'},
{'name':'Predator','mainStar':'Arnold Schwarzenneger'},
{'name':'Godzilla','mainStar':'Bryan Cranston'},
{'name':'Blade','mainStar':'Wesley Snipes'},
{'name':'Prometheus','mainStar':'Noomi Rapace'}
]

For this example I will just be extracting the movie name from the object of arrays using map and to do this is seen below.

var movieName = favouriteMovies.map(function(currItem){return currItem.name});

As you can see I have created a variable called “movieName” and set it to equal to “map” over the “favouriteMovies” array with one parameter defined (the mandatory parameter which represents the current item in the array) and I am returning the key “name” from the “favouriteMovies” array, copy and paste both the map function and object of arrays into a code editor such as https://playcode.io and look at the result, or create your own :).

Below is the result from the console.

However you can write your own function and insert it into the parameter of the map function as seen below.

This will produce the exact same output as above however it is just some nice “syntatic sugar”.

Filter

Filter does exactly what it says on the tin, it will take in an array and filter out elements of the array depending on the criteria you set, i.e. numbers over 20, strings not equal to “david” etc. Filter works the same way as map in that it takes a callback as its first argument and that callback has 3 arguments (first is current item, second is current index, third is the whole array), filter will run the callback on every element within the array and return a new array that contains only elements which have returned true for the callback criteria, an example is below.

var icecreams = [
{'flavour':'chocolate','rating':'5'},
{'flavour':'vanilla','rating':'9'},
{'flavour':'strawberry','rating':'8'},
{'flavour':'salted caramel','rating':'9'}
]
var filterIcecreams = icecreams.filter(function(currItem){
return currItem.rating >8
})

As you can see from the above, we have created an array of objects pertaining to an ice cream flavour as well as its rating, I have then performed a filter operation on the array to only return ice creams that have a rating greater than 8. The output can be seen below which will be the flavours “vanilla” and “salted caramel”

NOTE: One thing to remember when using map, reduce and filter is that within the callback function it must use the “return” keyword, otherwise your variable will return “undefined”.

Reduce

Reduce as its name suggests reduces, however, to put it more professionally, the reduce function takes in all of the array elements and “reduces” them into a single value, furthermore, reduce differs from map and filter in that it supports 4 arguments within its callback (first being the current value, second being the previous value, third being the current index and finally the fourth is the array you are looping over). Reduce gives you the option to set the initial previous value (Which you can do by writing a comma and then the value after the closing “}”)as on the first loop iteration there isn’t a previous value present and is the reason as to why you can pass an initial value to reduce. The most basic usage of reduce is to sum a list of numbers.

var myNumbers = [9,8,7,6,5,4,3,2,1];
var sumOfMyNumbers = myNumbers.reduce(function(previous,current,myIndex,myArray){
console.log(previous)
console.log(current)
return previous+current
},0);
console.log(sumOfMyNumbers)

As you can see from the example above I have an array of numbers and return the sum of the previous value adding to the current value, in addition, I have also set an initial value of 0, so the reduce will begin from 0. The first value of “previous” is 0, and the first value of “current” is 9, however, if I change the initial value to be 5 and not 0, then the first “previous” value is 5 and the total then becomes 50, not 45 because I have told the reduce to begin from 5 and not 0. You could also reduce to find the average of a group of numbers too

All in all, these 3 methods are a great way to implement list operations within JavaScript, however, this tutorial is a basic example of this and implements them using ES5 not ES6, with ES6 you can use more shorthand features such as arrow functions.

Hope you enjoyed this article, I will continue to learn and share my knowledge, any feedback is thoroughly appreciated 🙂