[go: up one dir, main page]

0% found this document useful (0 votes)
73 views116 pages

It Te V WD Week 1 Adjs

This document outlines a syllabus for a course on web development using technologies like HTML5, CSS3, JavaScript, and Flask framework. The course aims to teach students front-end and back-end web development skills, as well as mobile web development and web application deployment. It covers topics like JavaScript, Angular, React, Node.js, Express, MongoDB, jQuery Mobile, and cloud deployment on AWS. The syllabus details 6 modules that map to the course outcomes, with topics covered in each module and their credit hours.

Uploaded by

Saquibh Shaikh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views116 pages

It Te V WD Week 1 Adjs

This document outlines a syllabus for a course on web development using technologies like HTML5, CSS3, JavaScript, and Flask framework. The course aims to teach students front-end and back-end web development skills, as well as mobile web development and web application deployment. It covers topics like JavaScript, Angular, React, Node.js, Express, MongoDB, jQuery Mobile, and cloud deployment on AWS. The syllabus details 6 modules that map to the course outcomes, with topics covered in each module and their credit hours.

Uploaded by

Saquibh Shaikh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

ITCDLO5011: Web Development

Module 1 : Introduction to JavaScript

Mrs. Sujata Oak


Assistant Professor
Department of IT
Syllabus

2 Syllabus
Course Description

✓This course provides an in-depth knowledge of web-development


technologies that uses HTML5, CSS3 and advanced JavaScript.

✓It also explores students with both front-end and back-end


technologies, to learn mobile web development and also how to
deploy web applications.

✓This course also makes students to understand how to build web


applications quickly with less code using Flask Framework.

3 Syllabus
Course Objectives

1) To learn and understand Web scripting languages.

2) To explore the Front -end web development skills.

3) To explore the Back-end web development skills.

4) To understand and learn Mobile web development.

5) To understand and learn Web application deployment.

6) To build web applications quickly and with less code using Flask

framework.

4 Syllabus
Course Outcomes

1) Demonstrate the use of web scripting languages

2) Develop web application with Front End Technologies.

3) Develop web application with Back End Technologies.

4) Develop mobile website using JQuery Mobile.

5) Deploy web application on cloud using AWS.

6) Apply Flask web development framework to build web applications with

less code.

5 Syllabus
Module 1 : Advanced JavaScript [CO1] [6H]

JSON –

JSON Create, Key-Value Pair, JSON Access,

JSON Array,

JS Arrow Functions,

JS Callback Functions,

JS Promises,

JS Async-Await Functions,

JS Error Handling

6 Syllabus
Module 2 : Front End Technologies [CO2] [8H]

Front-End Frameworks:

What is web framework?

Why Web Framework?

Web Framework Types.

MVC: What is MVC,

MVC Architecture,

MVC in Practical,

MVC in Web Frameworks.

7 Syllabus
Module 2 : Front End Technologies [CO2] [8H]

AngularVersion 10+: Angular CLI, Angular Architecture, Angular Project Structure,


Angular Lifecycle, Angular Modules, Angular Components, Angular Data Binding,
Directives and Pipes, Angular Services and Dependency Injections (DI), Angular Routers,
Angular Forms.

ReactJS: Introduction to ReactJS, React Components, Inter Components Communication,


Components Styling, Routing, Redux- Architecture, Hooks- Basic hooks, useState() hook,
useEffect() hook, useContext() hook.

8 Syllabus
Module 3 : Back End Technologies [CO3] [8H]

Node.JS: Introduction to Node.JS, Environment Setup, Node.JS Events, Node.JS


Functions, Node.JS Built-in Modules, File System, NPM, Install External Modules,
Handling Data I/O in Node.JS, Create HTTP Server, Create Socket Server,
Microservices- PM2.
ExpressJS: Introduction to ExpressJS, Configure Routes, Template Engines,
ExpressJS as Middleware, Serving Static Files, REST HTTP Method APIs, Applying
Basic HTTP Authentication, Implement Session Authentication.

MongoDB: NoSQL and MongoDB Basics, MongoDB-Node.JS Communication,


CURD Operations using Node.JS, Mongoose ODM for Middleware, Advanced
MongoDB

9 Syllabus
Module 4 : Mobile Web Development [CO4] [7H]

Mobile-First: What is Mobile-First? What is Mobile Web? Understanding Mobile

Devices and Desktop.

JQuery Mobile: Introduction to the jQuery Mobile Framework, Set-up jQuery

Mobile, Pages, Icons, Transitions, Layouts Widgets, Events, Forms, Themes,

Formatting Lists, Header and Footer, CSS Classes, Data Attributes, Building a Simple

Mobile Webpage.

10 Syllabus
Module 5 : Web ApplicationDeployment [CO5] [5H]

Cloud: AWS Cloud, AWS Elastic Compute, AWS Elastic Load Balancer and its types,

AWS VPC and Component of VPC, AWS storage, Deploy Website or Web Application

on AWS, Launch an Application with AWS Elastic Beanstalk.

11 Syllabus
Module 6 : Flask [CO6] [5H]

Flask: Introduction, Flask Environment Setup, App Routing, URL Building, Flask

HTTP Methods, Flask Request Object, Flask cookies, File Uploading in Flask

12 Syllabus
Contents

Lecture 1 – Introduction to JavaScript 4

Lecture 2 – Advanced JavaScript 16

Lecture 3 –JS Callback Function, JS Arrow Function, JSON, JS Promise, 21

Lecture 4 –JS Async-await, JS Error Handling 27

Lecture 5 –Introduction to Web Framework, types


33

Lecture 6 –MVC In Practical 38

Module 1 : Advanced Javascript


13
https://javascript.info/intro

Lecture 1

Introduction to JavaScript
Module 1 : Introduction to JavaScript

JavaScript is a very powerful client-side


scripting language.

JavaScript is used mainly for enhancing the


interaction of a user with the webpage.

In other words, you can make your webpage


more lively and interactive, with the help of
JavaScript.

JavaScript is also being used widely in game


development and Mobile application
development.

15 Module 1 : Advanced JavaScript


Module 1 : JavaScript History

JavaScript was developed by Brendan Eich in 1995, which


appeared in Netscape, a popular browser .

The language was initially called LiveScript and was later


renamed JavaScript.
There are many programmers who think that JavaScript
and Java are the same. In fact, JavaScript and Java are very
much unrelated.

Java is a very complex programming language whereas


JavaScript is only a scripting language.

The syntax of JavaScript is mostly influenced by the


programming language C.

16 Module 1 : Advanced JavaScript


Module 1 : Features of JavaScript

✓ It is a Scripting Language and has


nothing to do with Java. Initially, It was
named Mocha, then changed
to LiveScript and finally it was named
as JavaScript.

✓ JavaScript is an object-
based programming language that
supports polymorphism,
encapsulation, and inheritance as well.

✓ You can run JavaScript not only in


the browser but also on
the server and any device which has a
JavaScript Engine.

17 Module 1 : Advanced JavaScript


Module 1 : JavaScript Stats

18 Module 1 : Advanced JavaScript


What can JavaScript do?

Module 1 : JavaScript
19
Mrs. Sujata Oak
What can JavaScript do?

1. JavaScript is used to create beautiful web pages and applications. It is


mostly used to make your web look alive and adds variety to the page.

2. It is also used in smartwatches. An example of this is the popular


smartwatch maker called Pebble that has created a small JavaScript
Framework called Pebble.js.

3. JavaScript is also used to make Games. A lot of developers are building


small-scale games and apps using JavaScript.

4. Most popular websites like Google, Facebook, Netflix, Amazon, etc make use
of JavaScript to build their websites.

Module 1 : JavaScript
20
Mrs. Sujata Oak
JavaScript Framework

Module 1 : JavaScript
21
Mrs. Sujata Oak
The Big Picture : HTML, CSS and JavaScript

Module 1 : JavaScript
22
Mrs. Sujata Oak
HTML vs CSS vs JavaScript

HTML (HyperText Markup Language) is more like the skeleton of the web. It
is used for displaying the web.

CSS is like our clothes. It makes the web look better. It uses CSS which stands
for Cascading Style Sheets for styling purpose.

JavaScript is used to add life to a web page. Just like how kids move around
using the skateboard, the web also motions with the help of JavaScript.

Module 1 : JavaScript
23
Mrs. Sujata Oak
Top Website Built Using JavaScript

Module 1 : JavaScript
24
Mrs. Sujata Oak
Benefits of JavaScript

Module 1 : JavaScript
25
Mrs. Sujata Oak
Benefits of JavaScript

Module 1 : JavaScript
26
, Mrs. Sujata Oak
Benefits of JavaScript

Module 2 : JavaScript
27
TE-B, Mrs. Sujata Oak
Benefits of JavaScript

1. It is Easy to learn and implement.

2. JavaScript is a fast client-side programming language.

3. It has a rich set of Frameworks such as AngularJS ,ReactJS, JQuery,

and MeteorJS

4. This is used to build beautifully designed, interactive websites.

5. It is a platform-independent programming language.

Module 1 : JavaScript
28
Mrs. Sujata Oak
WEB DEVELOPEMENT IDEs

Integrated Development
Environments (IDEs) are the
tools that are extremely
important when it comes to
coding. In today’s market,
you’d find an enormous
number of IDEs that serve
different purposes.
As a result, it gets really
confusing to select one IDE
that will serve all your
requirements.
Below are the Top IDEs for
Web Development

Module 1 : JavaScript
29
Mrs. Sujata Oak
Introduction to ES6

✓ ECMAScript (ES) is a scripting language specification standardized by


ECMAScript International.

✓ It is used by applications to enable client-side scripting.

✓ The specification is influenced by programming languages like Perl, Python,


Java etc.

✓ Languages like JavaScript, Jscript and ActionScript are governed by this


specification.

✓ ECMAScript 2015 was the second major revision to JavaScript.

✓ ECMAScript 2015 is also known as ES6 and ECMAScript 6.

Module 1 : JavaScript
30
Mrs. Sujata Oak
Version of JavaScript

1. The Original JavaScript ES1 ES2 ES3 (1997-1999)

2. The First Main Revision ES5 (2009)

3. The Second Revision ES6 (2015)

4. The Yearly Additions (2016, 2017, 2018)

Module 1 : JavaScript
31
Mrs. Sujata Oak
Module 1 : How to Run JavaScript?

32 Module 1 : Advanced JavaScript


Module 1 : How to Run JavaScript?

JavaScript cannot run on its own. In fact, the browser is responsible for running
JavaScript code.

When a user requests an HTML page with JavaScript in it, the script is sent to the
browser and it is up to the browser to execute it.

The main advantage of JavaScript is that all modern web browsers


support JavaScript.

JavaScript runs on any operating system including Windows, Linux or Mac.

33 Module 1 : Advanced JavaScript


Module 1 : A Simple JavaScript Program

You should place all your JavaScript code within <script> tags (<script> and </script>)
if you are keeping your JavaScript code within the HTML document itself.

This helps your browser distinguish your JavaScript code from the rest of the code.

You have to use the type attribute within the <script> tag and set its value to
text/javascript like this:

<script type="text/javascript">

DEMO: Firstjs.html

34 Module 1 : Advanced JavaScript


Module 1 : JavaScript Console

35 Module 1 : Advanced JavaScript


Module 1 : JavaScript Console

For Chrome users, if you don't see


for (var i = 0; i < 10; i++) the output, click “Default levels” in
{ the console and make sure
that "Info" is checked.
console.log(i);
}

36 Module 1 : Advanced JavaScript


Module 1 : JavaScript Console

For Chrome users, if you don't see


for (var i = 0; i < 10; i++) the output, click “Default levels” in
{ the console and make sure
that "Info" is checked.
console.log(i);
}

37 Module 1 : Advanced JavaScript


Module 1 : Summary

•JavaScript is a client-side scripting language developed by Brendan Eich.

•JavaScript can be run on any operating systems and almost all web

browsers.

•You need a text editor to write JavaScript code and a browser to display your

web page.

38 Module 1 : Advanced JavaScript


Module 1 : JavaScript Variable: Declare, Assign a Value with Example

Variables are used to store values (name = “Praful”)


or expressions (sum = x + y).

Declare Variables in JavaScript


Before using a variable, you first need to declare it. You have to use the
keyword var to declare a variable like this:
var name;
Assign a Value to the Variable
You can assign a value to the variable either while declaring the variable or after
declaring the variable. var name = “Praful";
OR
var name;
name = “Praful";

39 Module 1 : Advanced JavaScript


Module 1 : JavaScript Variable: Declare, Assign a Value with Example

It is a good
programming variable names
practice to give should start with
descriptive and a letter and they
meaningful are case sensitive
names to the
variables. studentname
and
studentName are
different

DEMO: Variabl.html

40 Module 1 : Advanced JavaScript


Module 1 : JavaScript Array Methods: Create with Example

An array is an object that can store a collection of items.

Arrays become really useful when you need to store large amounts of data of the
same type.

Suppose you want to store details of 500 employees.

If you are using variables, you will have to create 500 variables whereas you can do
the same with a single array.

You can access the items in an array by referring to its indexnumber and the index of
the first element of an array is zero.

var students = ["John", "Ann", "Kevin"];

41 Module 1 : Advanced JavaScript


Module 1 : JavaScript Array Methods: Create with Example

var students = ["John", "Ann", "Kevin"];


you are initializing your array as and when it is created with values “John”, “Ann”
and “Kevin”. The index of “John”, “Ann” and “Kevin” is 0, 1 and 2 .

If you want to add more elements to the students array, you can do it like this:

students[3] = "Emma"; students[4] = "Rose";

42 Module 1 : Advanced JavaScript


Module 1 : JavaScript Array Methods: Create with Example

You can also create an array using Array constructor like this:

var students = new Array("John", "Ann", "Kevin");

OR

var students = new Array();


students[0] = "John";
students[1] = "Ann";
students[2] = "Kevin";

43 Module 1 : Advanced JavaScript


Module 1 : JavaScript Array Methods: Create with Example

The Array object has many properties and methods which help developers to handle
arrays easily and efficiently.
You can get the value of a property by specifying arrayname.property and the output of
a method by specifying arrayname.method().

1.length property –> If you want to know the number of elements in an array, you can
use the length property.
2.reverse method –> You can reverse the order of items in an array using a reverse
method.
3.sort method –> You can sort the items in an array using sort method.
4.pop method –> You can remove the last item of an array using a pop method.
5.shift method –> You can remove the first item of an array using shift method.
6.push method –> You can add a value as the last item of the array.

Demo: Array.html

44 Module 1 : Advanced JavaScript


Lecture1

ES6 Decision-Making
if, if---else, if--else if—else,switch

ES6 Looping
Definite Loops : for , for—in , for-of
Indefinite Loops : while , do-while
Loops are useful when you have to execute the same lines of
ES6 Loops code repeatedly, for a specific number of times or as long as a
specific condition is true.

For-of

Definite Loops :
For(;;)
For…in
For…of

InDefinite Loops :
While
Do-while

Module 1 : JavaScript
46
Mrs. Sujata Oak
ES6 Loops

Module 1 : JavaScript
47
Mrs. Sujata Oak
ES6 While Loops

Module 1 : JavaScript
48
Mrs. Sujata Oak
ES6 While Loops

The do…while loop is very similar to while loop.


The only difference is that in do…while loop, the
block of code gets executed once even before
checking the condition.
Module 1 : JavaScript
49
Mrs. Sujata Oak
ES6 For Loop

Module 1 : JavaScript
50
Mrs. Sujata Oak
ES6 Decision-making : Conditional Statements : If

Module 1 : JavaScript
51
Mrs. Sujata Oak
ES6 Decision-making : Conditional Statements : ElseIf

Module 1 : JavaScript
52
Mrs. Sujata Oak
ES6 Decision-making : Conditional Statements : Switch Case Statement

Module 1 : JavaScript
53
Mrs. Sujata Oak
JavaScript Define & Call Functions with Example

What is Function in JavaScript?

Functions are very important and useful in any programming language as they make
the code reusable .

A function is a block of code which will be executed only if it is called.

If you have a few lines of code that needs to be used several times, you can create a
function including the repeating lines of code and then call the function wherever you
want.

Module 1 : JavaScript
54
Mrs. Sujata Oak
JavaScript Define & Call Functions with Example

How to Create a Function in JavaScript?

1.Use the keyword function followed by the name of the function.


2.After the function name, open and close parentheses.
3.After parenthesis, open and close curly braces.
4.Within curly braces, write your lines of code.

Syntax:
function functionname()

{
lines of code to be executed
}
DEMO:simplefunc.html

Module 1 : JavaScript
55
Mrs. Sujata Oak
JavaScript Define & Call Functions with Example

Function with Arguments

You can create functions with arguments as well. Arguments should be specified
within parenthesis

Syntax: function functionname(arg1, arg2)


{
lines of code to be executed
}

DEMO:argfunc.html

Module 1 : JavaScript
56
Mrs. Sujata Oak
JavaScript Define & Call Functions with Example

JavaScript Return Value

You can also create JS functions that return values. Inside the function, you need to
use the keyword return followed by the value to be returned.

Syntax:
function functionname(arg1, arg2)
{
lines of code to be executed
return val1;
}

DEMO:returnfunc.html

Module 1 : JavaScript
57
Mrs. Sujata Oak
Practical Code Examples using JavaScript

Example#1: JavaScript Multiplication Table


Create a simple multiplication table asking the user the number of rows and columns
he wants.
Example#2: JS Forms Example:
Create a sample form program that collects the first name, last name, email, user id,
password and confirms password from the user. All the inputs are mandatory and email
address entered should be in correct format. Also, the values entered in the password
and confirm password textboxes should be the same. After validating using JavaScript,
In output display proper error messages in red color just next to the textbox where there
is an error.
Example#3: POPUP Message using Event:
Display a simple message “Welcome!!!” on your demo webpage and when the user
hovers over the message, a popup should be displayed with a message “Welcome to my
WebPage!!!”.

DEMO:Example1.html DEMO:Example2.html
DEMO:Example3.html
Module 1 : JavaScript
58
Mrs. Sujata Oak
Application of JavaScript

✓ Dynamic Single-Page Applications (SPAs)

✓ Front-End technologies like jQuery, AngularJS, Ember.js, ReactJS are based on

Java Script

✓ Server-Side technologies like Node.js, Express.js, MongoDB are based on Java

Script.

✓ Mobile App Development using PhoneGap, React Native, etc.

Module 1 : JavaScript
59
Mrs. Sujata Oak
At A Glance!!!

HTML and CSS are markup languages. Markup languages are used to describe
and define elements within a document. JavaScript is a programming language.
Programming languages are used to communicate instructions to a machine.
Programming languages can be used to control the behavior of a machine and to
express algorithms.

https://en.wikipedia.org/wiki/JavaScript#History

Module 1 : JavaScript
60
Mrs. Sujata Oak
HOW TO WRITE JAVASCRIPT CODE?

1. Inline JavaScript: Include JS Code directly within


certain HTML attributes (inline.html)

2. Embedded JS: Place JS code within <script> element


(embedded.html)

1. External JS: JS is written in separate file, having


extension .js (external.html)

Module 1 : JavaScript
61
Mrs. Sujata Oak
Questions

What is Inline, Embedded and External Javascript? Explain with Example

Module 1 : JavaScript
62
Mrs. Sujata Oak
Lecture 2

ADVANCED JAVASCRIPT
Introduction to JSON

JSON is a file format used to store information in an organized and easy-to-


access manner.

Its full form is JavaScript Object Notation.

It offers a human-readable collection of data that can be accessed logically.

Its filename extension for written programming code is .json.

Module 1 : JavaScript
64
Mrs. Sujata Oak
Why use JSON?

1. Provide support for all browsers


2. Easy to read and write
3. Straightforward syntax
4. You can natively parse in JavaScript using eval() function
5. Easy to create and manipulate
6. Supported by all major JavaScript frameworks
7. Supported by most backend technologies
8. JSON is recognized natively by JavaScript
9. It allows you to transmit and serialize structured data using a network connection.
10. You can use it with modern programming languages.
11. JSON is text which can be converted to any object of JavaScript into JSON and send
this JSON to the server.
Module 1 : JavaScript
65
Mrs. Sujata Oak
History of JSON

1. Douglas Crockford specified the JSON format in the early 2000s.

2. The official website was launched in 2002.

3. In December 2005, Yahoo! starts offering some of its web services in JSON.

4. JSON became an ECMA international standard in 2013.

5. The most updated JSON format standard was published in 2017.

Module 1 : JavaScript
66
Mrs. Sujata Oak
Features of JSON

1. Easy to use – JSON API offers high-level facade, which helps you to simplify
commonly used use-cases.
2. Performance – JSON is quite fast as it consumes very less memory space, which is
especially suitable for large object graphs or systems.
3. Free tool – JSON library is open source and free to use.

4. Dependency – JSON library does not require any other library for processing.

Module 1 : JavaScript
67
Mrs. Sujata Oak
Rules for JSON Syntax

1. Data should be in name/value pairs

2. Data should be separated by commas

3. Curly braces should hold objects

4. Square brackets hold arrays

Module 1 : JavaScript
68
Mrs. Sujata Oak
Data Types in JSON

Module 1 : JavaScript
69
Mrs. Sujata Oak
JSON Object

A JSON Object is an entity in JSON which is enclosed in curly


brackets.

It is written in the unordered set of name and value pairs in which


the name should be followed by “:” (colon), and the name/value
pairs need to be separated using “,” (comma).

It can be used when key names are arbitrary strings.


Syntax:
{
"id": 110,
{ "language": "Python",
string : value,
….. }
"price": 1900,
}
Module 1 : JavaScript
70
Mrs. Sujata Oak
Example defines how to use JSON to store
Example of JSON information related to programming books along
with edition and author name.

{
"book": [{
"id": "444",
"language": "C",
"edition": "First",
"author": "Dennis Ritchie "
},
{
"id": "555",
"language": "C++",
"edition": "second",
"author": " Bjarne Stroustrup "
}
]
Link: https://jsonformatter.curiousconcept.c
}
om/
Link: https://jsonlint.com
Module 1 : JavaScript
71
Mrs. Sujata Oak
Creation of JSON Object with JavaScript

In JavaScript we can write JSON Object and store it in some variables.

Ex:

var stud = {
“name”:”Sujata”,
“Roll_No”:799,
“city”:”thane”
};

Here the object name stud is created.

Jojs.html

Module 1 : JavaScript
72
Mrs. Sujata Oak
JSON ARRAY Jsonarr.html

✓ It is an ordered collection of values.


✓ You should use an array when the key names are sequential integers.
✓ It should be enclosed inside square brackets which should be separated by ‘,’ (comma)
{
"eBooks": [{
"language": "Pascal",
"edition": "third" Syntax:
},
[value, .......]
{
"language": "Python",
"edition": "four"
},
{
"language": "SQL",
"edition": "second"
}
]
} Module 1 : JavaScript
73
Mrs. Sujata Oak
JS Arrow Functions / ES6 Arrow Function

✓ Arrow functions are introduced in ES6, which provides you a more accurate way
to write the functions in JavaScript.

✓ They allow us to write smaller function syntax.


✓ Arrow functions make your code more readable and structured.
✓ Arrow functions are anonymous functions (the functions without a name and not
bound with an identifier).
✓ They don't return any value and can declare without the function keyword.

Module 1 : JavaScript
74
Mrs. Sujata Oak
JS Arrow Functions / ES6 Arrow Function

✓ Arrow functions cannot be used as the constructors.


✓ They are also called as Lambda Functions in different languages.

Syntax for defining the arrow function

const functionName = (arg1, arg2, ..) => {


//body of the function
}
There are three parts to an Arrow Function or Lambda Function:
•Parameters: Any function may optionally have the parameters.
•Fat arrow notation/lambda notation: It is the notation for the arrow
(=>).
•Statements: It represents the instruction set of the function.

Module 1 : JavaScript
75
Mrs. Sujata Oak
Arrowfunc.html

// function expression
var myfunc1=function show(){
console.log("It is a Function Expression");
}

// Anonymous function
var myfunc2=function(){
console.log("It is an Anonymous Function");}

//Arrow function
var myfunc3 = () => {
console.log("It is an Arrow Function");
};

myfunc1();
myfunc2();
myfunc3();

Module 1 : JavaScript
76
Mrs. Sujata Oak
JS Arrow Functions / ES6 Arrow Function

Syntactic Variations

•Optional parentheses for the single parameter


var num=x=>{
console.log(x);
}
num(140);
•Optional braces for single statement and the empty braces if there is not any
parameter required.

var show = () => console.log("Hello World");


show();

Module 1 : JavaScript
77
Mrs. Sujata Oak
JS Arrow Functions / ES6 Arrow Function

Arrow Function with Parameters


If you require to pass more than one parameter by using an arrow function, then you
have to pass them within the parentheses.

var show=(a,b,c) => {


console.log(a + "" + b +"" +c);
}
show(100,200,300);

Module 1 : JavaScript
78
Mrs. Sujata Oak
JS Arrow Functions / ES6 Arrow Function

Arrow function with default parameters


In ES6, the function allows the initialization of parameters with default values, if there is no
value passed to it, or it is undefined. You can see the illustration for the same in the
following code:

var show=(a,b,c=600) => {


console.log(a + "" + b +"" +c);
}
show(100,200);

Module 1 : JavaScript
79
Mrs. Sujata Oak
JavaScript CallBack Function

A function is a block of code that


performs a certain task when called.
function greet(name) {
console.log('Hi' + ' ' + name);
}

greet('Kajol'); // Hi Kajol
In the above program, a string value is passed as an argument to the greet() function.

Module 1 : JavaScript
80
Mrs. Sujata Oak
JavaScript CallBack Function

In JavaScript, you can also pass a function as an argument to a


function. This function that is passed as an argument inside of
another function is called a callback function. For example,
function greet(name, callback) {
console.log('Hi' + ' ' + name);
callback();
}
// callback function
function callMe() {
console.log('I am callback function');
}
// passing function as an argument
greet('Kajol', callMe);
There are two functions. While calling the greet() function, two arguments (a string value and a
function) are passed.
The callMe() function is a callback function.

Module 1 : JavaScript
81
Mrs. Sujata Oak
JavaScript CallBack Function
<head>
<title>JS Callback Function</title>
<script>
// function
function mul(a,b,callback) {
res=a*b
document.write("Result Is:"+res);
callback();
}
function display(){
document.write("<br/> Welcome to session on JS Callback
Function");
}
</script>
</head>
<body>
<script>
mul(10,20,display);
</script>
</body>
</html>Module 1 : JavaScript
82
Mrs. Sujata Oak
Benefit of Callback Function

You can wait for the result of a previous function call and then
execute another function call.

Program with setTimeout()


setTimeout() method executes a block of code after the specified time.

Module 1 : JavaScript
83
Mrs. Sujata Oak
Program with setTimeout()

// program that shows the delay in greet() function is called


execution after 5000 milliseconds
function greet() { (5 seconds).
console.log('Hello world');
} During this wait,
function sayName(name) { the sayName(‘Prathemesh');
console.log('Hello' + ' ' + name); is executed.
}

// calling the function That is why Hello


setTimeout(greet, 5000); Prathemesh is printed
sayName('Prathemesh'); before Hello world
The above code is executed asynchronously
(the second function; sayName() does not wait for the first function; greet() to complete)

Module 1 : JavaScript
84
Mrs. Sujata Oak
JavaScript Synchronous Programming

function myfun(){
console.log("Inside
Function")
}
console.log("start")
myfun()
console.log("end")

Module 1 : JavaScript
85
Mrs. Sujata Oak
JavaScript Asynchronous Programming

Module 1 : JavaScript
86
Mrs. Sujata Oak
JavaScript Asynchronous Programming

Module 1 : JavaScript
87
Mrs. Sujata Oak
JavaScript Asynchronous Programming

console.log("start")
setTimeout(()=>{
console.log("Inside setTimeOut")
},5000)
console.log("end")

Module 1 : JavaScript
88
Mrs. Sujata Oak
JavaScript CallBack Function can be Synchronous

console.log("start")
const roll=[1,2,3,4,5]
roll.forEach(r=>{
console.log(r)
})
console.log("End")

Module 1 : JavaScript
89
Mrs. Sujata Oak
JavaScript Promises

✓ In JavaScript, a promise is a good way to


handle asynchronous operations.

✓ It is used to find out if the asynchronous operation is


successfully completed or not.

✓ A promise may have one of three states.


•Pending
•Fulfilled
•Rejected

Module 1 : JavaScript
90
Mrs. Sujata Oak
JavaScript Promises

A promise starts in a pending state.


That means the process is not complete.

If the operation is successful,


the process ends in a fulfilled state.

And, if an error occurs,


the process ends in a rejected state.

Module 1 : JavaScript
91
Mrs. Sujata Oak
JavaScript Promises

For example,

when you request data from the server by using a


promise, it will be in a pending state. When the data
arrives successfully, it will be in a fulfilled state. If an
error occurs, then it will be in a rejected state.

Module 1 : JavaScript
92
Mrs. Sujata Oak
JavaScript Promises

Create a Promise:
To create a promise object, we use the Promise() constructor.

let promise = new Promise(function(resolve, reject)


{ The Promise() constructor takes a function as an
//do something argument. The function also accepts two
functions resolve() and reject().
} If the promise returns successfully,
); the resolve() function is called. And, if an error occurs,
the reject() function is called.

Module 1 : JavaScript
93
Mrs. Sujata Oak
Example 1: Program with a Promise
JavaScript Promises
Prom2.js , external.html

const count = true;


let countValue = new Promise(function (resolve, reject) {
if (count)
{ resolve("There is a count value.");
} else
{ reject("There is no count value"); }
});
console.log(countValue);
resolve() is used if the process is successful and reject() is used when an
error occurs in the promise.

The promise is resolved if the value of count is true.


Module 1 : JavaScript
94
Mrs. Sujata Oak
Example 1: Program with a Promise
JavaScript Promises
Prom2.js , external.html

Working of JavaScript promise

Module 1 : JavaScript
95
Mrs. Sujata Oak
JavaScript Promises

When the Promise gets resolved, something will happen next that
depends on what we want to do with the resolved Promise.

myPromise.then();

".then();" method is only called when the Promise is resolved(


completed successfully), and what we passed in it will be displayed.

myPromise.then((message)=>{
console.log(message);
});

Module 1 : JavaScript
96
Mrs. Sujata Oak
JavaScript Promises
Prom.html

.catch(); method

This method is called when the promise is rejected (or failed). And
we can also pass a message in it for the user. We can write the catch
method just after the "then ()" method.

myPromise.then((message)=>{
console.log(message);
}).catch((message)=>{
console.log(message);
});

Module 1 : JavaScript
97
Mrs. Sujata Oak
JavaScript Promises : Conclusion

Module 1 : JavaScript
98
Mrs. Sujata Oak
JavaScript Promises : Conclusion

Module 1 : JavaScript
99
Mrs. Sujata Oak
JavaScript Promises : Conclusion

Module 1 : JavaScript
100
Mrs. Sujata Oak
JavaScript Promises : Conclusion

Module 1 : JavaScript
101
Mrs. Sujata Oak
JavaScript Promises : Conclusion

Module 1 : JavaScript
102
Mrs. Sujata Oak
JavaScript Promises : Conclusion

Module 1 : JavaScript
103
Mrs. Sujata Oak
JavaScript Promises : Conclusion

Module 1 : JavaScript
104
Mrs. Sujata Oak
JavaScript Promises : Conclusion

Module 1 : JavaScript
105
Mrs. Sujata Oak
JavaScript Promises : Conclusion

Module 1 : JavaScript
106
Mrs. Sujata Oak
JavaScript Async/Await

Module 1 : JavaScript
107
Mrs. Sujata Oak
JavaScript Async/Await

Async/Await is an extension of promises

We use the async keyword with a function to represent that the


function is an asynchronous function.

The async function returns a promise.

SYNTAX:
async function name(parameter1, parameter2, ...paramaterN)
{
// statements
}
Module 1 : JavaScript
108
Mrs. Sujata Oak
JavaScript Async/Await : Example: Async Function

async function fun() {


console.log('Async function.’);
return Promise.resolve(1);
}
fun();

OUTPUT: Async function


Since this function returns a promise, you can use the
chaining method then() like this:

Module 1 : JavaScript
109
Mrs. Sujata Oak
JavaScript Async/Await : Example: Async Function

async function fun() {


console.log('Async function.');
return Promise.resolve(1);
}

fun().then(function(result) {
console.log(result)
});

In the above program, the fun() function is resolved and


then() method gets executed.

Module 1 : JavaScript
110
Mrs. Sujata Oak
JavaScript Async/Await : Example: Await Function

Module 1 : JavaScript
111
Mrs. Sujata Oak
JavaScript Async/Await : Example: Await Function

The await keyword is used inside the async function to wait for
the asynchronous operation.

The syntax to use await is:

let result=await promise;


The use of await pauses the async function until the
promise returns a result (resolve or reject) value.

Module 1 : JavaScript
112
Mrs. Sujata Oak
JavaScript Async/Await : Example: Await Function

// a promise
let promise = new Promise(function (resolve, reject) {
setTimeout(function () { resolve('Promise resolved')}, 4000); }); //
async function async function asyncFunc() { // wait until the promise
resolves let result = await promise; console.log(result);
console.log('hello'); } // calling the async function asyncFunc();

The use of await pauses the async function until the


promise returns a result (resolve or reject) value.

Module 1 : JavaScript
113
Mrs. Sujata Oak
JavaScript Async/Await

Benefits of Using async Function


•The code is more readable than using
a callback or a promise.
•Error handling is simpler.
•Debugging is easier.

http://localhost:9191/async_await2.html

Module 1 : JavaScript
114
Mrs. Sujata Oak
JavaScript Error Handing

https://www.programiz.com/javascript/async-await

Module 1 : JavaScript
115
Mrs. Sujata Oak
116

You might also like