JavaScript/C4/Arrow-function-in-JS/English

From Script | Spoken-Tutorial
Revision as of 11:06, 21 June 2021 by Nancyvarkey (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Title of the script: Arrow Functions

Author: Jayesh Katta Ramalingaiah

Domain Reviewer: Ankita Maske

Novice Reviewer: Praveeen S.

Keywords: JavaScript, HTML, this, Arrow, function


Visual Cue
Narration
Slide: Title Hello and welcome to the spoken tutorial on “Arrow Function in JS”.
Slide:

Learning Objectives

In this tutorial, we will learn about:
  • setInterval
  • clearInterval
  • setTimeout and
  • Arrow Functions in JS
Slide: System Specifications This tutorial is recorded using:
  • Ubuntu Linux OS version 18.04
  • Visual Studio Code version 1.45.0 (code editor)
  • Firefox web browser

However you may use any other browser of your choice.

Slide : Pre-requisites To practice this tutorial,
  • You should be familiar with writing and executing JS files.
  • If not, please go through the prerequisite tutorials on this website.
Slide: Code files
  • The files used in this tutorial are available in the Code files link on this tutorial page.
  • Pls download and extract the files.
  • Make a copy and then use them for practising.
Slide: Arrow Function
  • Arrow Functions are introduced in ES6
  • This is also called as Fat Arrow Function because we use a fat arrow as syntax
  • Doesn’t have ‘this’ context - Does not have it’s own binding
  • whereas the normal function has ‘this’ context.
  • The best part of arrow functions is, it avoids confusion of ‘this’ context in callbacks.
Only Narration Now, let us take an example and understand this better.
Show VS editor Open Visual Studio Code editor
[Editor] Welcome Page -> Open Folder -> Practice-JS -> index.html & main.js


Then open the files index.html and main.js as explained in the earlier tutorials.


For this demonstration, I have already opened the same.


These files are available in the Code files link for practice.

[Editor] Type:


<!DOCTYPE html>

<html lang="en">

<head>

<title>Arrow Functions</title>

</head>

<body>

<script src="main.js"></script>

</body>

</html>

In the index.html file, replace the code as shown.



Press: Ctrl + S


Press: Alt + L and Alt + O

Save the file and start the Live server.
[Firefox] Press Ctrl + Shift + I


Point to the browser Console tab

In the web browser, open the Browser developer tools panel and go to the console tab.
Switch to Editor Switch back to the editor.
[Editor] Type:


function Display() {

this.speed = 0;

var self = this;

var stop = setInterval(function () {

self.speed++;

console.log(self.speed);

}, 300);


setTimeout(function () {

clearInterval(stop);

}, 5000);

}

var d1 = new Display();

In the main.js file, replace the code as shown.
[Editor] Highlight:


var d1 = new Display();

Here, I’m making a function call with new binding.
[Editor] Highlight:


function Display() {

this.speed = 0;

var self = this;

var stop = setInterval(function () {

self.speed++;

console.log(self.speed);

}, 300);


setTimeout(function () {

clearInterval(stop);

}, 5000);

}

Here, I’m declaring a display function,


You are already aware that the normal function has its own scope.

[Editor] Highlight:


this.speed = 0;

In the functional scope, I have declared speed property and assigned it to 0.
[Editor] Highlight:


var self = this;

Here, I’m creating a variable self and assigning ‘this’ context to it.


Here, ‘this’ refers to the scope of the display function which can be used whenever necessary.

[Editor] Highlight:


setInterval(function () {

self.speed++;

console.log(self.speed);

}, 300);

In JS we have an inbuilt method setInterval and it accepts two parameters.


One a callback function and the other is the time interval in milliseconds.


After the specified time interval, the callback function gets executed.


Until we clear the interval, the execution of setInterval won’t stop.

[Editor] Highlight:


function () {

self.speed++;

console.log(self.speed);

}

This is a callback function or you can even call it as an anonymous function.


You are already aware that function has its own scope and the new scope starts here.

[Editor] Highlight:


self.speed++;

Here, I’m increasing the value of speed, which is declared in the display function.


So as to access display function scope, I’m using the self keyword.


By now, you should have understood the reason.


That is why I have declared the variable self and assigned the context.


If I use this.speed, I will have access to the scope of the callback function, which is not needed.

[Editor] Highlight:


console.log(self.speed);

In the console, I will log the value of speed.
[Editor] Highlight:


300

Here, I have kept 300 milliseconds as the time interval.


So, the function executes after 300 milliseconds.

[Editor] Highlight:


setTimeout(function () {

clearInterval(stop);

}, 5000);

In JS, setTimeout is also an inbuilt function.


It takes a callback function and time in milliseconds as parameters.


It is unlike the setInterval method.


setTimeout method will execute the callback function once after the specified time.

[Editor] Highlight:


clearInterval(stop);

Let’s go inside the callback function.


I’m clearing the interval by passing the stop variable, which was assigned to setInterval method.

[Editor] Highlight:


5000

5000 milliseconds is equivalent to 5 seconds.


So, the setTimeout callback function will be executed after 5 seconds.

Only Narration Now , let’s see the output.


Press: Ctrl + S

Switch to Browser

Save the file and switch to the browser.
[Browser] [Console Tab]:

Highlight:


1

2

3

4 . . . . . . . . . . . . . 16

Observe here, we can see numbers from 1 to 16.


The value of speed will not be incremented after that because the interval is cleared after 5 seconds.


It’s a simple math calculation: 5000/300 = 16 point something.


The next execution will happen at 5100 milliseconds.


This is because we cleared the interval at 5000 milliseconds.


We don’t see the next number printed in the console.

Only Narration So far, we just learnt about setInterval, setTimeout and clearInterval


Next let’s learn the display method using arrow function and understand the difference.

Switch to Editor Switch back to the editor.
[Editor] Type:


function Display() {

this.speed = 0;

var stop = setInterval(() => {

this.speed++;

console.log(this.speed);

}, 300);

setTimeout(() => clearInterval(stop), 5000);

}


var d1 = new Display();

In the main.js file, replace the code as shown.
[Editor] Highlight:


var d1 = new Display();

Here, I do a similar function call like done in the previous example.
[Editor] Highlight:


function Display() {

this.speed = 0;

var stop = setInterval(() => {

this.speed++;

console.log(this.speed);

}, 300);

setTimeout(() => clearInterval(stop), 5000);

}

In this function declaration, I have created a speed property in the display function context.


This is similar to the one shown in the previous example.


setInterval function has some major changes, which I’ll be explaining to you.

[Editor] Highlight:


() => {

this.speed++;

console.log(this.speed);

}

Here, the callback function is an arrow function.


Notice the fat arrow in the code as syntax for the arrow function.


The brackets are used for passing the parameters.


I told you in the beginning that for arrow functions we don't have a new scope.


The scope of the display function is the same as the scope of the arrow function.

[Editor] Highlight:


this.speed++;

So, I’m able to access this.speed using the this keyword itself.


Unlike the previous example, I did not store the context in a variable to use it elsewhere.


Assigning a context to a variable and then using it, will create a lot of confusion in huge programs.

[Editor] Highlight:


console.log(this.speed);

In the console, I will log the value of speed.
[Editor] Highlight:


setTimeout(() => clearInterval(stop), 5000);

Here, notice setTimeout.


I have used the arrow function for the callback function.


And I haven’t used open and close curly braces here.


If I have a single statement, I can directly write the instruction within brackets.


This is the advantage of the arrow function.

Only Narration Now, let's see the output.


Press: Ctrl + S

Switch to Browser

Save the file and switch back to the browser.
[Browser] [Console Tab]:

Highlight:


1

2

3

4 . . . . . . . 16

We get the same output here with the use of the arrow function.


The advantage is that we removed unnecessary self-declarations of the variable for context.


Plus we avoided a lot of confusion and wrote a cleaner code.

Only Narration With this we have come to the end of this tutorial.


Let’s summarize.

Slide: Summary In this tutorial, we have learnt:
  • setInterval
  • clearInterval
  • setTimeout and
  • Arrow Function in JS
Slide: Assignment As an assignment:
  • Open the file assignment.js which you have created earlier.
  • Clear the existing code.
  • Display ‘Welcome to Spoken Tutorials’ message in the console after 5 seconds
  • Use setTimeout and arrow function as callback function
  • Open the file MyPage.html in a web browser.
  • Observe the output in the browser’s console
Slide: About Spoken Tutorial Project
  • The video at the following link summarises the Spoken Tutorial project.
  • Please download and watch it
Slide: Spoken tutorial workshops
  • We conduct workshops using spoken tutorials and give certificates.
  • For more details, please write to us.
Slide: Forum questions Pls post your timed queries in this forum
Slide: Acknowledgement Spoken Tutorial Project is funded by Ministry of Education (MoE), Government of India
Slide: Thanks The script for this tutorial is contributed by Jayesh and this is Praveen signing off. Thank you for joining

Contributors and Content Editors

Kr.jayesh, Nancyvarkey, Pravin1389