paint-brush
JS Arrow Functions for Newbiesby@jony1
1,514 reads
1,514 reads

JS Arrow Functions for Newbies

by Jony DarkoJune 10th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Arrow Functions are a new ES6 js feature that has its pros and cons. This article covers the basic difference between regular functions and arrow functions as well as the use of 'this' keyword.

Company Mentioned

Mention Thumbnail
featured image - JS Arrow Functions for Newbies
Jony Darko HackerNoon profile picture

A few important things to consider before we begin:


I am a beginner developer and writing articles is my way of learning, this means that there might be errors. If you find any, please let me know in the comments and І will correct them :)


Some of the information like definitions or examples are taken from the internet, if you see something that belongs to you and would like credit or it to get removed - please contact me and І will be happy to do so.



Learning is fun, so let’s go!🔥


Arrow Functions are a new ES6 js feature and they are essential to understand as they help make your life as a developer easier and more fun :)


Let's try to understand it better by comparing them with regular Functions.

Here are a few examples of regular functions:


Example 1 - Function with two parameters:

function sum(a, b) {
 return a + b
}


Example 2 - Function with one parameter:

function isPositive (number) { 
return number ›= 0 
} 


Example 3 - Function with no parameters:

function randomNumber() {
return Math.random 
}


Example 4 - Anonymous function without a name:

document. addEventListener('click', function() { 
console.log(‘Click’)
})


Now let’s try to convert these Regular Functions into the Arrow Functions.

Example 1 - Function with two parameters.

function sum(a, b) {
 return a + b
}

step 1: 
sum(a, b) {
 return a + b
}

step 2: 
let sum = (a, b) {
 return a + b
}

step 3: 
let sum = (a, b) => {
 return a + b
}


This is one of the easiest and most common functions to go around.


Step 1 - remove function keyword. This is because with arrow function function keyword is assumed.


Step 2 - assign our function to a variable. When we have function keyword, it will do it for us but since we remove it, we have to assign our function sum to a variable in order to store it. For this, we use let . Thus we create a variable sum and with = sign store our arrow function in there.


Step 3 - add Arrow ➡️ 😄. This is what creates the magic. It shows that we have parameters on the left side of the Arrow and on the right side of it, in the brackets, we have the function.


Now our Example 1 function and function in step 3 are the same! Congratulations on your first arrow function 🎉


This is not the end, we could make it even better!

step 3: 
let sum = (a, b) => {

 return a + b

}

Shorten to one line
let sum = (a, b) => a + b


With the arrow function, we can shorten our code to one line. This can be done by removing return keyword and curly brackets. This is possible because everything after the arrow is assumed to be returned so we can omit return and {} . Now 1st example function = function in step 3 = one-line function, AMAZING MAGIC 🔥


Example 2 - Function with one parameter:

function isPositive (number) { 
return number ›= 0 
} 

Step 1: 
isPositive (number) { 
return number ›= 0 

}

Step 2: 
let isPositive = (number) { 
return number ›= 0 
}

Step 3: 
let isPositive = (number) => { 
return number ›= 0 
}

Step 4: 
let isPositive = (number) => number ›= 0 

Step 5: 
let isPositive = number => number ›= 0 

Now lets repeat the proccess for our function with one parameter.


Step 1 - remove function keyword.

Step 2 - store our function by creating variable with the help of let statement.

Step 3 - ARROW ➡️

Step 4 - Remove return and brackets. Beautiful 🤓

Bonus Step 5 - since we have one parameter, we can even remove parentheses around the parameter we pass into the function.


Example 3 - Function with no parameters

function randomNumber() {
return Math.random 
}

“І want to play a game” 👹


Let’s practice a bit. This example follows our 4 steps. Try to do it by yourself and write in the comments one line that you get. Before that, don’t look into the comments.


Example 4 - Anonymous function without a name:

document. addEventListener('click', function() { 
console.log(‘Click’)
})
step 1: 
document. addEventListener('click', () => { 
console.log(‘Click’)
})
step 2: 
document. addEventListener('click', () => console.log(‘Click’))


Anonymous function without a name this is where Arrow Functions really shine.


Step 1 - remove function and add arrow ➡️. Note that we don’t have to assign it to a variable by writing let and = .


Step 2 - put everything in one line and remove curly brackets.


It is nice that Arrow Functions help us to write less code but now comes the whole point of using them - they redefine this keyword inside of Arrow Functions as opposed to this in Normal Functions. Here it is used much differently.


w3schools explains the difference:


“In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button, or whatever.


With arrow functions the this keyword always represents the object that defined the arrow function.”


So basically, Arrow Functions helps us to simplify function scope and make the process of using this keyword much easier.


To better understand it let’s see how this is used in ES5.

var cat = {
name: 'Garfield', 
showName: function() {
 alert(this.name);
  }
};
cat.showName(); // it will show - Garfield


Here we have a simple object - cat. Inside this object, we have a method (function that belongs to an object). So what is this referring to here? Right! It will point out to the object cat.


Next, lets see how this behaives inside method’s function:

var cat = {
  name: 'Garfield',
  tasks: ['transform', 'eat fish', 'sleep'],
  showTasks: function() {
    this.tasks.forEach(function(task) {
      alert(this.name + " wants to " + task);
    });
  }
};
cat.showTasks();
// [object Window] wants to transform
// [object Window] wants to eat fish
// [object Window] wants to sleep


Hmm… you see how instead of cat we are getting [object Window]?

What might be our guesses as to why this is happening?


  1. Method’s inner function?
showTasks: function() {
    this.tasks.forEach(function(task) {
      alert(this.name + " wants to " + task);
    });


  1. The whole object - cat?


The truth is that this has fallen out of scope. ‘This’ always points to the owner of the function it is in and since we are out of the scope - we then deal with a global object, which is window.


When it is inside of an object’s method — the function’s owner is the object. Thus the ‘this’ keyword is bound to the object. Yet when it is inside of a function, either stand-alone or within another method, it will always refer to the window/global object.


Our method has two functions with this , the one that should point to the name is inner and thus falls out of the scope.


One more example from the internet:

function Person() {
    this.name = 'Jack',
    this.age = 25,
    this.sayName = function () {

        // this is accessible
        console.log(this.age);

        function innerFunc() {

            // this refers to the global object
            console.log(this.age);
            console.log(this);
        }

        innerFunc();

    }
}

let x = new Person();
x.sayName();

// output:
// 25
// undefined
// Window {}


So, in regular functions this changes according to the way that function is invoked - it is dynamic. This is a poor design which can in some cases lead to unpredicted behavior while using this keyword.


On the other hand, the value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function which means No matter how or where being executed, this value inside of an arrow function always equals this value from the outer function.


function Person() {
    this.name = 'Jack',
    this.age = 25,
    this.sayName = function () {

        console.log(this.age);
        let innerFunc = () => {
            console.log(this.age);
        }

        innerFunc();
    }
}

const x = new Person();
x.sayName();
// output:
// 25
// 25


One Important thing to remember is that even though Arrow Functions brings lexical scoping that makes it easier to use this , you should be careful because we cannot use it everywhere.


If you like the article and find it helpful, І will be happy to further explore Arrow Functions together with you 🎉


JS Arrow Functions For Newbies Pt2? 👍 👎