Difference between revisions of "JavaScript/C2/Functions-in-JS/English"

From Script | Spoken-Tutorial
Jump to: navigation, search
 
Line 3: Line 3:
 
Author: Jayesh Katta Ramalingaiah
 
Author: Jayesh Katta Ramalingaiah
  
Domain Reviewer:  
+
Domain Reviewer: Ankita Maske
  
Novice Reviewer:  
+
Novice Reviewer: Praveeen S.
  
 
Keywords: JavaScript, HTML, Function, value, arguments, parameters
 
Keywords: JavaScript, HTML, Function, value, arguments, parameters

Latest revision as of 11:17, 21 June 2021

Title of the script:Functions

Author: Jayesh Katta Ramalingaiah

Domain Reviewer: Ankita Maske

Novice Reviewer: Praveeen S.

Keywords: JavaScript, HTML, Function, value, arguments, parameters


Visual Cue
Narration
Slide: Title Hello and Welcome to the spoken tutorial on “Functions in JS”.
Slide:

Learning Objectives

In this tutorial, we will learn about:
  • Functions
  • Different types of functions and
  • Function declarations in JS
Slide: System Specifications This tutorial is recorded using:
  • Ubuntu Linux OS version 18.04
  • Visual Studio Code version 1.51.1 (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: Functions
  • A function is a block of code which is defined once and can be called multiple times.
  • The main advantage of a function is reusability.
Slide: Types of Functions The different types of functions are,
  • Basic Function
  • Parameterized Function
  • Function as a value
  • Function as an Argument/Parameter
  • Function as Property
  • Function Arguments
  • Constructor Function

Let us take an example and understand this better.

Switch to Visual Studio code editor Switch to the Visual Studio code editor.
[Editor]


Welcome Page ->

Open Folder ->

Practice-JS

In the Welcome page, click on the Open folder link at the top left corner.


Browse and locate the folder “Practice-JS ”.


Then click on the OK button at the top right corner.

[Editor] Click on


Explorer panel -> Practice-JS -> index.html

In the Explorer panel on the left, under Practice-JS click on the file named index.html
[Editor] Type:


<html lang="en">

<head>

<title>Functions</title>

</head>

<body>

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

</body>

</html>

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


In this code we have written a small HTML code and linked the JS file.

Press: Ctrl + S Save the file.
Press: Alt + L and Alt + O


Now press the key combinations Alt + L and Alt + O.


The Live server gets started.

Show firefox The default browser will open automatically and a new tab opens.
[Firefox] Press Ctrl + Shift + I


Point to the Browser developer tools

Now press Ctrl + Shift + I keys together.


The Browser developer tools panel opens.

[Firefox] Click on the Console tab Now click on the console tab in the developer tools.
Switch to Editor Switch back to the editor.
[Editor] Click on


Explorer panel -> Practice-JS -> main.js

In the Explorer panel on the left, under Practice-JS click on the file named main.js
[Editor] Type:


function add() {

console.log(1+2);

return true;

}


add();

console.log(add());

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


function add()

In JS, to create a basic function, we use the function keyword.


This is followed by the name of the function and brackets.

[Editor] Highlight:


console.log(1+2);

Inside the function block, we can have multiple instructions.


Here we just logged 1 + 2

[Editor] Highlight:


return true;

Functions always return some value.


return is an optional keyword


If you don’t use return keyword to return any value, by default undefined will be returned.


Here, this function is returning true.

[Editor] Highlight:


add();

Only when the function is called, the function block will get executed.


A function call can be made any number of times.

[Editor] Highlight:


console.log(add());

Here, I have written the add() function inside the console log statement.


So, whatever is being returned by the add() function, will get logged.

Press: Ctrl + S Save the file.
Switch to browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


3

true

Here in the output, we observe:


3


true


In the console, at the right end of the 3, we see (2).


This means 3 is printed twice.

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


add();

The first 3 is printed for the first function call.
[Editor] Highlight:


console.log(add());

The second 3 is printed for the second function call.
[Editor] Highlight:


console.log(add());

And true is printed because add() function’s return value is logged.
[Editor] Type:


function sub(a) {

return a - 1;

}


var result = sub(6);

console.log(result);

Next, let us learn about parameterized function.


In the main.js file, replace the code as shown.

[Editor] Highlight:


function sub(a) {

Here, we have created a function similar to the basic function.


The only difference is we are passing a parameter a.


The parameter can be used for a purpose in the function.

[Editor] Highlight:


return a - 1;

Here, we are subtracting the value and returning the subtracted value.
[Editor] Highlight:


var result = sub(6);

In this line, the function call is made passing 6 as the parameter.


The returned value is stored in the result variable.

[Editor] Highlight:

console.log(result);

Here, we are logging the value on the console.
Press: Ctrl + S Save the file.
Switch to Browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


5

The output is 5 because we have passed the number 6 as the parameter.


That value is being subtracted by 1 and returned.


After returning, we are catching the value in a variable and logging it.

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


var mul = function () {

return true;

};


var result = mul();

console.log(result);

Next, let us learn about the function as a value.


In the main.js file, replace the code as shown.

[Editor] Highlight:


var mul = function ()

Here, we have declared a variable with the name mul.


The variable mul is assigned to a function using the function keyword.


We don’t have to give the name of the function again, followed by the function keyword.


The name of the function becomes mul here.

[Editor] Highlight:


function ()

We call function () as an anonymous function.


If we wish to, we can even pass some parameters to this.

[Editor] Highlight:

return true;

This function just returns true.
[Editor] Highlight:


var result = mul();

The function call is similar to the basic and parameterized ones.


The returned value would be caught by the result variable.

[Editor] Highlight:


console.log(result);

Here, we are logging the result variable.
Press: Ctrl + S Save the file.
Switch to Browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


true

Here, as the function returns true, "True" is printed on the console.
Switch to Editor Switch back to the editor.
[Editor] Type:


function d1() {

console.log('Spoken');

}

function d2() {

console.log('Tutorials');

}

function d3() {

console.log('on JS');

}

function display(fn, fn1, fn2) {

fn();

fn1();

fn2();

}


display(d1, d2, d3);

Next, let us learn about function as a parameter.


In the main.js file, replace the code as shown.

[Editor] Highlight:


function d1() {

console.log('Spoken');

}


function d2() {

console.log('Tutorials');

}


function d3() {

console.log('on JS');

}

Here, we have declared three functions with names d1, d2 and d3 respectively.
[Editor] Highlight:


function display(fn, fn1, fn2)

Here, I have created another function named display.


To this, we are passing 3 parameters named fn, fn1 and fn2.

[Editor] Highlight:


fn();

fn1();

fn2();

Inside, the display function,we’re making function calls for the parameters.


This is because the parameters are functions.

[Editor] Highlight:


display(d1, d2, d3);

While making the display function call, we’re passing 3 functions d1, d2 and d3 respectively.


Here, as we’re passing d1,d2 and d3, these functions would be called callback functions.

Slide: callback function Callback function is defined as a function which is passed as a parameter to another function.
[Editor] Highlight:


display(d1, d2, d3);

d1, d2 and d3 will be taken as fn, fn1, fn2 in display function as the parameters.


On making the function call for fn, fn1 and fn2,


d1, d2 and d3 functions will be executed.

Press: Ctrl + S Save the file.
Switch to Browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Spoken

Tutorials

on JS

Here, if we see the output Spoken Tutorials on JS is being logged from the d1, d2 and d3 functions.
Switch to Editor Switch back to the editor.
[Editor] Type:


var student = {

marks: function () {

return 100;

},

};


var result = student.marks();

console.log(result);

Next, let us learn about function as a property.


In the main.js file, replace the code as shown.

[Editor] Highlight:

var student = {};

Here, student is the object.
[Editor] Highlight:


marks: function () {

return 100;

},

Here, marks is a property in the student object, which holds an anonymous function.
[Editor] Highlight:


return 100;

This function returns 100.
[Editor] Highlight:


var result = student.marks();

To make a function call, we need to call the property inside the student object.


Here, we access the marks as student.marks


To make a function call we add brackets similar to a function as a value


Here, we have named the function as marks.


The returned value is stored in variable result.

console.log(result); Here, we are logging the result.
Press: Ctrl + S Save the file.
Switch to Browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


100

Here, the output is 100 as the function returns 100.
Switch to Editor Switch back to the editor.
[Editor] Type:


function marks() {

for (var i = 0; i < arguments.length; i++) {

console.log(arguments[i]);

}

}


marks(87, 78, 90, 81);

Next, let us understand about function arguments.


In the main.js file, replace the code as shown.

[Editor] Highlight:


marks(87, 78, 90, 81);

So far, when we passed parameters to a function, we declared a parameter variable while creating the function.


This example helps us in a situation where we are not sure of the number of parameters to be passed.


In this case, we are passing 4 parameters.

[Editor] Highlight:


function marks() {}

And we have not declared any variables to catch the values passed in the marks function.
[Editor] Highlight:


for (var i = 0; i < arguments.length; i++) {

}

Using the keyword arguments, we can access the parameters being passed.


arguments.length, will give the number of the arguments being passed.


Here, we can loop over and get the values.


Please note here that the prototype of the arguments is array but the data structure is object.

[Editor] Highlight:


console.log(arguments[i]);

Here, we are just logging the value in the arguments.
Press: Ctrl + S Save the file.
Switch to Browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:

87

78

90

81

As we are passing 87, 78, 90, 81 as parameters, the output we get is 87, 78, 90, 81.
Switch to Editor Switch back to the editor.
[Editor] Type:


function Student(stuName, stuAge) {

this.name = stuName;

this.age = stuAge;

}


var s1 = new Student("S1", 10);

var s2 = new Student("S2", 11);

console.log(s1);

console.log(s2);

Next, let us understand the constructor function.


In the main.js file, replace the code as shown.

[Editor] Highlight:


function Student(stuName, stuAge)

Here, we have created a function named Student and passing the parameters stuName and stuAge.


Only in the constructor function, the name of the function starts with an uppercase letter.

[Editor] Highlight:


this.name = stuName;

this.age = stuAge;

Inside the function block we have assigned, this.name as stuName and this.age as stuAge.


Here, this refers to the variable name, where the function call is made.

[Editor] Highlight:


var s1 = new Student("S1", 10);

var s2 = new Student("S2", 11);

Here, we have made the function calls,


For the constructor function, new keyword has to be used while making the function call.


For the first function call, the variable name is s1, so this refers to s1.


For the second function call, the variable name is s2, so this refers to s2.

Only narration The constructor function creates a new object with help of parameters and returns the object.


The returned object will be stored in the respective variable.

[Editor] Highlight:


console.log(s1);

console.log(s2);

Here, we are logging s1 and s2
Press: Ctrl + S Save the file.
Switch to Browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Object { name: "S1", age: 10 }

Object { name: "S2", age: 11 }

Here, we see we have 2 objects printed.


One for s1 and other for s2, with the property names as name and age as mentioned in function block.


And the values are stuName and stuAge which are passed as parameters.

Only narration Hence, we conclude that the constructor function returns an object.


While making a function call, new keyword would be responsible for creating the new object.

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


Let’s summarize.

Slide: Summary In this tutorial, we have learnt about:
  • Functions
  • Different types of functions and
  • Function declarations in JS
Slide: Assignment As an assignment:
  • Open the file assignment.js which you have created earlier
  • Clear the existing code
  • Create an Employee function
  • Employee function accepts name and id as parameters
  • Create Object references to name and id parameter
  • Create two objects using the Employee function
  • Log the created objects in the console
  • 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 from IIT Bombay signing off.

Thank you for joining.

Contributors and Content Editors

Kr.jayesh, Nancyvarkey, Pravin1389