You are on page 1of 49

10.

Introduction to Javascript

Table of Content
1. Basics of Javascript

2. Variables & Data Types

3. Javascript Type Conversion

4. Javascript Arithmetic Operators

5. Conditional Statements in Javascript

1. Basics of Javascript
JavaScript is a scripting language that enables you to create dynamically updating
content, control multimedia, animate images, and much more.

Where to put
In HTML, JavaScript code is inserted between <script> and </script> tags.

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

You can place any number of scripts in an HTML document.


Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in
both.

We can also create separate External Javascript.

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

10. Introduction to Javascript 1


Keywords
In JavaScript you cannot use these reserved words as variables, labels, or function
names:

Javascript Statements
A computer program is a list of "instructions" to be "executed" by a computer.

In a programming language, these programming instructions are called statements.


A JavaScript program is a list of programming statements.

let a, b, c; // Declare 3 variables


a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c

2. Variables & Data Types

10. Introduction to Javascript 2


Variables
Variables are containers for storing data (storing data values). We can declare a
variable by using these keywords.

Using var for declaring function-scoped variables (old)

Using let for declaring block-scoped variables (new)

Using const for declaring constant variables

Note: It is recommended we use let instead of var. However, there are a few
browsers that do not support let.

Rules for naming variables:

1. Variable names must start with either a letter, an underscore _ , or the dollar
sign $ . For example,

//valid
let a = 'hello';
let _a = 'hello';
let $a = 'hello';

2. Variable names cannot start with numbers. For example,

//invalid
Let 1a = 'hello'; // this gives an error

3. JavaScript is case-sensitive. For example,

let y = "hi";
let Y = 5;

console.log(y); // hi
console.log(Y); // 5

4. Keywords cannot be used as variable names. For example,

10. Introduction to Javascript 3


//invalid
let new = 5; // Error! new is a keyword.

Data Types
A data type, in programming, is a classification that specifies which type of value a
variable has and what type of mathematical, relational or logical operations can be
applied to it without causing an error.

A string, for example, is a data type that is used to classify text and an integer is a
data type used to classify whole numbers.
Some Common Data Types in Javascript are:

String for “Hello”, ‘hi’ etc.

Number for 45, -12 etc.

Boolean for true and false

undefined for un-initialized variables

Object key-value pairs of collection of data

typeof operator

To find the type of a variable, you can use the typeof operator. For example,

const name = 'ram';


typeof(name); // returns "string"

const number = 4;
typeof(number); //returns "number"

const valueChecked = true;


typeof(valueChecked); //returns "boolean"

3. Javascript Type Conversion


We use these functions to convert types:

10. Introduction to Javascript 4


Number()

String()

Boolean()

Note:

1. JavaScript considers 0 as false and all non-zero numbers as true. And, if true is
converted to a number, the result is always 1.

2. String() takes null and undefined and converts them to string.

3. In JavaScript, undefined , null , 0 , NaN , '' converts to false. All other values give
true .

Use this table for reference:

10. Introduction to Javascript 5


4. Javascript Arithmetic Operators
As with algebra, you can do arithmetic with JavaScript variables, using operators like =
and +

const number = 3 + 5; // 8

We have Arithmetic Operators : +, -, /, *, ++, — and **

5. Conditional Statements in Javascript


Javascript Comparison Operators

10. Introduction to Javascript 6


ternary Operator
A ternary operator evaluates a condition and executes a block of code based on the
condition.

Its syntax is:

condition ? expression1 : expression2


let result = (marks >= 40) ? 'pass' : 'fail';

The ternary operator evaluates the test condition.

If the condition is true , expression1 is executed.

If the condition is false , expression2 is executed.

The ternary operator takes three operands, hence, the name ternary operator. It is
also known as a conditional operator.

If-else, else-if
In computer programming, there may arise situations where you have to run a block
of code among more than one alternatives. For example, assigning
grades A, B or C based on marks obtained by a student.
In such situations, you can use the JavaScript if...else statement to create a
program that can make decisions.

if (condition) {
// block of code if condition is true
} else {
// block of code if condition is false
}

You can also write multiple else if in between the if and the else blocks.

logical Operators

10. Introduction to Javascript 7


Switch Statements

The JavaScript switch statement is used in decision making.


The switch statement evaluates an expression and executes the corresponding
body that matches the expression's result.

// program using switch statement


let a = 2;

switch (a) {
case 1:
a = 'one';
break;
case 2:
a = 'two';
break;
default:
a = 'not found';
break;
}
console.log(`The value is ${a}`);

Assignments
1. Build a Calculator Application (without the UI) using Arithmetic operators

2. Build an Average Marks Generator. using Arithmetic operators

10. Introduction to Javascript 8


3. Build a BMI calculator using Arithmetic operators

4. Build a Grading System based on Marks using Switch-case statements.

10. Introduction to Javascript 9


11. Loops, Arrays, and Functions
in Javascript
Table of Content
1. Loops in Javascript

2. Arrays in Javascript

3. Functions in Javascript

1. Loops in Javascript
In programming, loops are used to repeat a block of code. For example, if you want to
show a message 100 times, then you can use a loop.

Javascript for loop


The syntax of the for loop is:

for (initialExpression; condition; updateExpression) {


// for loop body
}

Here,

1. The initialExpression initializes and/or declares variables and executes only


once.

2. The condition is evaluated.

If the condition is false , the for loop is terminated.

If the condition is true , the block of code inside of the for loop is
executed.

3. The updateExpression updates the value of initialExpression when the


condition is true .

11. Loops, Arrays, and Functions in Javascript 1


4. The condition is evaluated again. This process continues until the condition
is false .

// program to display text 5 times


const n = 5;

// looping from i = 1 to 5
for (let i = 1; i <= n; i++) {
console.log(`I love JavaScript.`);
}

Javascript while loop


The syntax of the while loop is:

while (condition) {
// body of loop
}

Here,

1. A while loop evaluates the condition inside the parenthesis () .

2. If the condition evaluates to true , the code inside the while loop is executed.

3. The condition is evaluated again.

4. This process continues until the condition is false .

5. When the condition evaluates to false , the loop stops.

Javascript do-while loop

The syntax of do...while loop is:

do {
// body of loop
} while(condition)

11. Loops, Arrays, and Functions in Javascript 2


Here,

1. The body of the loop is executed at first. Then the condition is evaluated.

2. If the condition evaluates to true , the body of the loop inside the do statement
is executed again.

3. The condition is evaluated once again.

4. If the condition evaluates to true , the body of the loop inside the do statement
is executed again.

5. This process continues until the condition evaluates to false . Then the loop
stops.

Note: do...while loop is similar to the while loop. The only difference
is that in do…while loop, the body of loop is executed at least once.

break and continue


The break statement is used to terminate the loop immediately when it is
encountered.
The continue statement is used to skip the current iteration of the loop and the
control flow of the program goes to the next iteration.

Javascript for…in loop

The for..in loop in JavaScript allows you to iterate over all property keys of an
object.
The syntax of the for...in loop is:

for (key in object) {


// body of for...in
}

In each iteration of the loop, a key is assigned to the key variable. The loop
continues for all object properties.

You can use for…in with Strings, Arrays and Objects in Javascript.

11. Loops, Arrays, and Functions in Javascript 3


2. Arrays in Javascript
An array is an object that can store multiple values at once. For example,

const words = ['hello', 'world', 'welcome'];

Here, words is an array. The array is storing 3 values.

Creating an Array:

The easiest way to create an array is by using an array literal [] . For example,

const array1 = ["eat", "sleep"];

You can also create an array using JavaScript's new keyword.

const array2 = new Array("eat", "sleep");

Note: Array's index starts with 0, not 1.

We can use the length property to find the length of the array.

Some Common Array Methods

push()adds a new element to the end of an array and returns the new length of
an array

pop() : removes the last element of an array and returns the removed element

forEach() : calls a function for each element

sort() : sorts the elements alphabetically in strings and in ascending order

includes() : checks if an array contains a specified element

indexOf() : searches an element of an array and returns its position

splice() : removes or replaces existing elements and/or adds new elements

11. Loops, Arrays, and Functions in Javascript 4


3. Functions in Javascript

A function is a block of code that performs a specific task. Dividing a complex problem
into smaller chunks makes your program easy to understand and reusable.

Declaring a Function
The syntax to declare a function is:

function nameOfFunction () {
// function body
}

A function is declared using the function keyword.

Calling a Function

function nameOfFunction () {
// function body
}

nameOfFunction(); //calling the function

Function Parameters

// program to print the text


// declaring a function
function greet(name) {
console.log("Hello " + name + ":)");
}

function add(a, b) {
console.log(a + b);
}

Function Return
The return statement can be used to return the value to a function call.

11. Loops, Arrays, and Functions in Javascript 5


The return statement denotes that the function has ended. Any code
after return is not executed.

If nothing is returned, the function returns an undefined value.

Function Expressions

In Javascript, functions can also be defined as expressions. For example,

let x = function (num) { return num * num };


console.log(x(4));

let y = x(3);
console.log(y);

Output

16
9

In the above program, variable x is used to store the function. Here the function is
treated as an expression. And the function is called using the variable name.
The function above is called an anonymous function.

Arrow Functions
The arrow function is one of the features introduced in the ES6 version of
JavaScript. It allows you to create functions in a cleaner way compared to regular
functions. For example,This function

// function expression
let multiply = function(x, y) {
return x * y;
}

can be written as

// using arrow functions


let multiply = (x, y) => x * y;

11. Loops, Arrays, and Functions in Javascript 6


using an arrow function.

let sum = (a, b) => {


let result = a + b;
return result;
}

let result1 = sum(5,7);

Assignment
1. Write a JavaScript function that checks whether a passed string is palindrome or
not.

2. Write a JavaScript function that returns a passed string with letters in alphabetical
order.

3. Write a JavaScript function to calculate the average of marks passed in an array.

4. Learn about various String methods in Javascript:


https://www.programiz.com/javascript/library/string

5. Learn about various Math methods in Javascript:


https://www.programiz.com/javascript/library/math

11. Loops, Arrays, and Functions in Javascript 7


12. DOM and Event Listeners

Table of Content
1. The HTML DOM

2. Event Listeners in Javascript

1. The HTML DOM (Document Object Model)


Introduction
When a web page is loaded, the browser creates a Document Object Model of the
page.
The HTML DOM model is constructed as a tree of Objects:

12. DOM and Event Listeners 1


With the object model, JavaScript gets all the power it needs to create dynamic
HTML:

JavaScript can change all the HTML elements in the page

JavaScript can change all the HTML attributes in the page

JavaScript can change all the CSS styles in the page

JavaScript can remove existing HTML elements and attributes

JavaScript can add new HTML elements and attributes

JavaScript can react to all existing HTML events in the page

JavaScript can create new HTML events in the page

The HTML DOM document object is the owner of all other objects in your web page.
The document object represents your web page. If you want to access any element
in an HTML page, you always start with accessing the document object.

Finding the HTML Elements

Finding HTML elements by id


This example finds the element with id="intro"

const element = document.getElementById("intro");

Finding HTML elements by tag name

This example finds all <p> elements:

const element = document.getElementsByTagName("p");

Finding HTML elements by class name


This example returns a list of all elements with class="intro" .

const x = document.getElementsByClassName("intro");

12. DOM and Event Listeners 2


Finding HTML elements by CSS selectors
If you want to find all HTML elements that match a specified CSS selector (id,
class names, types, attributes, values of attributes, etc), use the
querySelectorAll() method.

This example returns a list of all <p> elements with class="intro" .

const x = document.querySelectorAll("p.intro");

Changing HTML

changing HTML Content using innerHTML

To change the content of an HTML element, use this syntax:

document.getElementById(id).innerHTML = new HTML

changing HTML attributes value


To change the value of an HTML attribute, use this syntax:
document.getElementById( id ). attribute = new value

This example changes the value of the src attribute of an <img> element:

document.getElementById("myImage").src = "landscape.jpg";

adding a class in HTML

using the classList property of Elements, we can add, remove or toggle


classes from HTML

const element = document.getElementById("myDIV");


element.classList.add("mystyle");
element.classList.remove("mystyle");
element.classList.toggle("mystyle");

creating and appending new HTML

12. DOM and Event Listeners 3


We can create a new Element using the createElement () method of the
document. We can append this new Element (node) inside any other element.

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);

const element = document.getElementById("div1");


element.appendChild(para);
</script>

Changing HTML Style

To change the style of an HTML element, use this syntax:

document.getElementById(id).style.property = new style


document.getElementById("p2").style.color = "blue";

2. Event Listeners in Javascript


What is an Event?

Events allow you to write JavaScript code that reacts to certain situations. Examples
of events include:

The user clicks the mouse button

The Web page loading

A form field being changed

How to use Event Listeners?

12. DOM and Event Listeners 4


As the name suggests, the event listener listens for events and gets triggered when
an event occurs.

addEventListener(type, listener, useCapture)

const button = document.querySelector(".btn")

button.addEventListener("click", () => {
console.log("Button clicked.");
})

The addEventListener() method attaches an event handler to an element without


overwriting existing event handlers.
You can add many event handlers to one element.

You can add many event handlers of the same type to one element, i.e two "click"
events.

A complete list of all HTML DOM Events:


https://www.w3schools.com/jsref/dom_obj_event.asp

Assignments
1. Build a NavBar that changes the background color after the page is scrolled 100px

2. Build a Toggle NavBar Menu with a Hamburger menu like this one
(https://www.w3schools.com/howto/howto_js_mobile_navbar.asp)

3. Build a working calculator Application.

4. Build an Image Slider With Two Buttons for the Left and Right Slide like this one
(https://www.w3schools.com/howto/howto_js_slideshow.asp)

12. DOM and Event Listeners 5


12.5 String & Maths Functions +
DOM Navigation

Table of Content
1. String Methods

2. Maths Methods

3. DOM Navigation

String Methods
You can find all the useful string methods here:
https://www.programiz.com/javascript/library/string

Maths Methods
You can find all the useful string methods here:
https://www.programiz.com/javascript/library/math

DOM Navigation

12.5 String & Maths Functions + DOM Navigation 1


The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships.

In a node tree, the top node is called the root (or root node)

Every node has exactly one parent, except the root (which has no parent)

A node can have a number of children

Siblings (brothers or sisters) are nodes with the same parent

Navigating between Nodes

You can use the following node properties to navigate between nodes with
JavaScript:

parentNode

childNodes[ nodenumber ]

firstChild

lastChild

nextSibling

previousSibling

12.5 String & Maths Functions + DOM Navigation 2


Node Values

<title id="demo">DOM Tutorial</title>

The element node <title> (in the example above) does not contain text.

It contains a text node with the value "DOM Tutorial".


The value of the text node can be accessed by the node's innerHTML property:

myTitle = document.getElementById("demo").innerHTML;

Accessing the innerHTML property is the same as accessing the nodeValue of the
first child:

myTitle = document.getElementById("demo").firstChild.nodeValue;

Document Body and Element

There are two special properties that allow access to the full document:

document.body - The body of the document (returns the <body> element)

document.documentElement - The full document (returns the <html> element)

12.5 String & Maths Functions + DOM Navigation 3


13. Javascript Objects, Classes &
JSON

Table of Content
1. Javascript Objects

2. Javascript Classes

3. JSON

1. Javascript Objects
JavaScript object is a non-primitive data type that allows you to store multiple
collections of data. If you are familiar with other programming languages, JavaScript
objects are a bit different. You do not need to create classes in order to create objects.

// object
const student = {
firstName: 'ram',
class: 10
};

In JavaScript, "key: value" pairs are called properties. For example,

You can also create values with nested objects, arrays, functions, etc.

13. Javascript Objects, Classes & JSON 1


Accessing Object Properties

1. Using dot Notation

const person = {
name: 'John',
age: 20,
};

// accessing property
console.log(person.name); // John

2. Using bracket Notation

const person = {
name: 'John',
age: 20,
};

// accessing property
console.log(person["name"]); // John

for…in loop with Object

const student = {
name: 'Monica',
grade: 7,
age: 12
}

// using for...in
for ( let key in student ) {

// display the properties


console.log(`${key} => ${student[key]}`);
}

Object Destructuring

The destructuring assignment introduced in ES6 makes it easy to assign array


values and object properties to distinct variables. For example,

13. Javascript Objects, Classes & JSON 2


// assigning object attributes to variables
const person = {
name: 'Sara',
age: 25,
gender: 'female'
}

// destructuring assignment
let { name, age, gender } = person;

console.log(name); // Sara
console.log(age); // 25
console.log(gender); // female

Javascript Object Methods

You can create functions as values inside an object.

// object containing method


const person = {
name: 'John',
greet: function() { console.log('hello'); }
};

Javascript this keyword


To access a property of an object from within a method of the same object, you
need to use the this keyword. Let's consider an example.

const person = {
name: 'John',
age: 30,

// accessing name property by using this.name


greet: function() { console.log('The name is' + ' ' + this.name); }
};

person.greet();

2. Javascript Classes

13. Javascript Objects, Classes & JSON 3


Classes are one of the features introduced in the ES6 version of JavaScript. A class is a
blueprint for the object. You can create an object from the class.

// creating a class
class Person {
constructor(name) {
this.name = name;
}
}

// creating an object
const person1 = new Person('John');
const person2 = new Person('Jack');

Javascript Class Methods

class Person {
constructor(name) {
this.name = name;
}

// defining method
greet() {
console.log(`Hello ${this.name}`);
}
}

let person1 = new Person('John');

// accessing property
console.log(person1.name); // John

// accessing method
person1.greet(); // Hello John

Note: JavaScript class is a special type of function. And the typeof operator
returns function for a class.

For example,

class Person {}
console.log(typeof Person); // function

13. Javascript Objects, Classes & JSON 4


3. JSON
JSON stands for Javascript Object Notation. JSON is a text-based data format that is
used to store and transfer data. For example,

// JSON syntax
{
"name": "John",
"age": 22,
"gender": "male",

In JSON, the data are in key/value pairs separated by a comma , .

JSON was derived from JavaScript. So, the JSON syntax resembles JavaScript object
literal syntax.

JSON is the most commonly used format for transmitting data (data interchange) from a
server to a client and vice-versa. JSON data are very easy to parse and use. It is fast to
access and manipulate JSON data as they only contain texts.

JSON is language independent. You can create and use JSON in other programming
languages too.

JSON JavaScript Object

The key in key/value pair should be in double The key in key/value pair can be without double
quotes. quotes.
JSON cannot contain functions. JavaScript objects can contain functions.

JSON can be created and used by other JavaScript objects can only be used in
programming languages. JavaScript.

Converting JSON to Javascript Object

You can convert JSON data to a JavaScript object using the built-
in JSON.parse() function. For example,

// json object
const jsonData = '{ "name": "John", "age": 22 }';

// converting to JavaScript object


const obj = JSON.parse(jsonData);

13. Javascript Objects, Classes & JSON 5


// accessing the data
console.log(obj.name); // John

Converting JavaScript Object to JSON

You can also convert JavaScript objects to JSON format using the JavaScript built-
in JSON.stringify() function. For example,

// JavaScript object
const jsonData = { "name": "John", "age": 22 };

// converting to JSON
const obj = JSON.stringify(jsonData);

// accessing the data


console.log(obj); // "{"name":"John","age":22}"

Assignments
1. Create a Class called Vehicle with the properties of a Vehicle like wheels, isDeisel

and functions like drive(), break() etc.

a. Make multiple objects of these class with different properties.

b. Iterate through the object using the for loops

c. Convert the objects to JSON Strings.

13. Javascript Objects, Classes & JSON 6


14. Error Handling, Modules, Map
& Filters and ES6 Concepts

Table of Content
1. Error Handling

2. Javascript Modules

3. Array Map & Filter

4. Javascript ES6 Concepts

1. Error Handling
In programming, there can be two types of errors in the code:

1. Syntax Error

2. Runtime Error

These errors that occur during runtime are called exceptions.

JavaScript try...catch Statement

try {
// body of try
}
catch(error) {
// body of catch
}

The main code is inside the try block. While executing the try block, if any error
occurs, it goes to the catch block. The catch block handles the errors as per the
catch statements.

14. Error Handling, Modules, Map & Filters and ES6 Concepts 1
If no error occurs, the code inside the try block is executed and the catch block is
skipped.

JavaScript try...catch...finally Statement


You can also use the try...catch...finally statement to handle exceptions.
The finally block executes both when the code runs successfully or if an error
occurs.
The syntax of try...catch...finally block is:

try {
// try_statements
}
catch(error) {
// catch_statements
}
finally() {
// codes that gets executed anyway
}

2. Javascript Modules
As our program grows bigger, it may contain many lines of code. Instead of putting
everything in a single file, you can use modules to separate codes in separate files
according to their functions. This makes our code organized and easier to maintain.

Benefits of Using Modules:

The code base is easier to maintain because different codes having different
functionalities are in different files.

Makes code reusable. You can define a module and use it numerous times as per
your needs.

export and import

// exporting a function
export function greetPerson(name) {
return `Hello ${name}`;
}

14. Error Handling, Modules, Map & Filters and ES6 Concepts 2
// importing greetPerson from greet.js file
import { greetPerson } from './greet.js';

// using greetPerson() defined in greet.js


let displayName = greetPerson('Jack');

Rename export and import

export {
function1 as newName1,
function2 as newName2
};

import { function1 as newName1, function2 as newName2 } from './module.js';

Default export

// default export
export default function greet(name) {
return `Hello ${name}`;
}

export const age = 23;

import random_name from './greet.js';

While performing default export,

random_nameis imported from greet.js . Since, random_name is not in greet.js , the


default export ( greet() in this case) is exported as random_name .

You can directly use the default export without enclosing curly brackets {} .

Note: A file can contain multiple exports. However, you can only have one default
export in a file.

14. Error Handling, Modules, Map & Filters and ES6 Concepts 3
3. Filter, Map & Find
All these are higher-order functions. A higher-order function is a function that either
takes other functions as arguments or returns a function.

Array filter method


The filter () method returns a new array with all elements that pass the test
defined by the given function.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// function to check even numbers


function checkEven(number) {
if (number % 2 == 0)
return true;
else
return false;
}

// create a new array by filter even numbers from the numbers array
let evenNumbers = numbers.filter(checkEven);
console.log(evenNumbers);

// Output: [ 2, 4, 6, 8, 10 ]

filter() does not change the original array.

filter() does not execute callback for array elements without values

Array map method

The map () method creates a new array with the results of calling a function for every
array element.

let numbers = [2, 4, 6, 8, 10];

// function to return the square of a number


function square(number) {
return number * number;
}

// apply square() function to each item of the numbers list


let square_numbers = numbers.map(square);
console.log(square_numbers);

// Output: [ 4, 16, 36, 64, 100 ]

14. Error Handling, Modules, Map & Filters and ES6 Concepts 4
map() does not change the original array.

map() executes callback once for each array element in order.

map() does not execute callback for array elements without values.

Array find method

const emp = [
{
name: "Ram",
empID: 101
},
{
name: "Sham",
empID: 102
},
{
name: "Mohan",
empID: 103
}
];

const res = emp.find(el => el.empID === 102);

console.log("res is: ", res); // res is: {name: 'Sham', empID: 102}

4. Javascript ES6 Concepts


JavaScript ES6 (also known as ECMAScript 2015 or ECMAScript 6) is the newer
version of JavaScript that was introduced in 2015.

We have already seen some ES6 concepts like Arrow functions, Javascript Classes,
Template literals, Javascript Destructuring, etc. Some useful ES6 concepts are
mentioned below:

Default Parameter Values

In the ES6 version, you can pass default values in the function parameters. For
example,

14. Error Handling, Modules, Map & Filters and ES6 Concepts 5
function sum(x, y = 5) {

// take sum
// the value of y is 5 if not passed
console.log(x + y);
}

sum(5); // 10
sum(5, 15); // 20

In the above example, if you don't pass the parameter for y , it will take 5 by default.

JavaScript Spread Operator

function show(a, b, ...args) {


console.log(a); // one
console.log(b); // two
console.log(args); // ["three", "four", "five", "six"]
}

show('one', 'two', 'three', 'four', 'five', 'six')

You use the spread syntax ... to copy the items into a single array. For example,

let arr1 = ['one', 'two'];


let arr2 = [...arr1, 'three', 'four', 'five'];
console.log(arr2); // ["one", "two", "three", "four", "five"]

Assignments
1. Create a Filter Function for a String Array that takes a condition function to filter.
Also, create the condition functions mentioned below:

a. Filter out all the values with less than 3 characters.

b. Filter out all the values that contain the expression “hi”.

c. Filter out all the values that are palindrome.

14. Error Handling, Modules, Map & Filters and ES6 Concepts 6
2. Create a Map function for Number Array that takes the following modification
functions. Also, create the modification functions.

a. Modify and return an array with square roots.

b. Modify the Numbers and make them String and return an array.

3. Use the following array:

let users = [
{firstName : "Susan", lastName: "Steward"},
{firstName : "Daniel", lastName: "Longbottom"},
{firstName : "Jacob", lastName: "Black"}
];

a. Filter the users whose firstName is “Susan”.

b. Filter out the users whose lastName starts with the letter L.

c. Map and return an array called fullName with full name values like “Susan
Steward”

14. Error Handling, Modules, Map & Filters and ES6 Concepts 7
15. Callback, Promises & async-
await

Table of Content
1. setTimeOut and setInterval methods

2. Promises in Javascript

3. async-await in Javascript

1. setTimeOut and setInterval methods

setTimeOut() method
The setTimeout() method calls a function after a number of milliseconds. The
setTimeout() method executes a block of code after the specified time. The method

executes the code only once.


The commonly used syntax of JavaScript setTimeout is:

setTimeout(function, milliseconds);

Its parameters are:

function - a function containing a block of code

milliseconds - the time after which the function is executed

The setTimeout() method returns an intervalID, which is a positive integer.

clearTimeOut() method

15. Callback, Promises & async-await 1


You generally use the clearTimeout () method when you need to cancel the
setTimeout () method call before it happens.

// program to stop the setTimeout() method

let count = 0;

// function creation
function increaseCount(){

// increasing the count by 1


count += 1;
console.log(count)
}

let id = setTimeout(increaseCount, 3000);

// clearTimeout
clearTimeout(id);
console.log('setTimeout is stopped.');

Output

setTimeout is stopped.

setInterval() method

The setInterval () method is useful when you want to repeat a block of code
multiple times. For example, showing a message at a fixed interval.

The commonly used syntax of JavaScript setInterval is:

setInterval(function, milliseconds);

Its parameters are:

function - a function containing a block of code

milliseconds - the time interval between the execution of the function

15. Callback, Promises & async-await 2


The setInterval() method returns an intervalID which is a positive integer.

clearInterval() method
The syntax of clearInterval() method is:

clearInterval(intervalID);

Here, the intervalID is the return value of the setInterval() method.

2. Promises in Javascript

Callback Functions
A callback function is passed as an argument to another function. It helps us to
notify about certain events from the called function.

// function
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('Peter', callMe);

If we have a long chain of such callback functions, it can create a chain of nested
function calls aka the callback hell.

15. Callback, Promises & async-await 3


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

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.

Create a Promise

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

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


//do something
});

The Promise() constructor takes a function as an 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.

15. Callback, Promises & async-await 4


Promises Chaining

Promises are useful when you have to handle more than one asynchronous
task, one after another. For that, we use promise chaining.

You can perform an operation after a promise is resolved using


methods then() , catch() and finally() .

JavaScript then() method

The then() method is used with the callback when the promise is
successfully fulfilled or resolved.

The syntax of then() method is:

promiseObject.then(onFulfilled, onRejected);

Javascript catch() method


The catch () method is used with the callback when the promise is rejected
or if an error occurs.

Promise vs Callback

JavaScript Promise

15. Callback, Promises & async-await 5


1. The syntax is user-friendly and easy to read.

2. Error handling is easier to manage.

3. Example:

api().then(function(result) {
return api2() ;
}).then(function(result2) {
return api3();
}).then(function(result3) {
// do work
}).catch(function(error) {
//handle any error that may occur before this point
});

JavaScript Callback

1. The syntax is difficult to understand.

2. Error handling may be hard to manage.

3. Example:

api(function(result){
api2(function(result2){
api3(function(result3){
// do work
if(error) {
// do something
}
else {
// do something
}
});
});
});

3. async-await in Javascript

15. Callback, Promises & async-await 6


We use the async keyword with a function to represent that the function is an
asynchronous function. The async function returns a promise.

The syntax of async function is:

async function name(parameter1, parameter2, ...paramaterN) {


// statements
}

Here,

name - name of the function

parameters - parameters that are passed to the function

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. For example,

Benefits of async-await

The code is more readable than using a callback or a promise.

Error handling is simpler.

Debugging is easier.

Note: These two keywords async/await were introduced in the newer version of
JavaScript (ES8). Some older browsers may not support the use of async/await.

15. Callback, Promises & async-await 7


Assignments
1. Create a process for cart checkout Page using callback & Promises with async-
await with the following steps. Here each step can contain a setTimeOut with 2
seconds to mimic the asynchronous delay.

a. getOrderInfo

b. checkIfAvailable

c. placeOrder

d. returnSuccess

2. Create a process for user signup using callback & Promises with async-await with
the following steps. Here each step can contain a setTimeOut with 2 seconds to
mimic the asynchronous delay.

a. getUserInfo

b. checkIfAlreadyPresent

c. createAccount

d. sendSignUpEmail

e. and returnSuccess

15. Callback, Promises & async-await 8


16. fetch APIs and DOM
Manipulation Revisited

Table of Content
1. fetch API

2. DOM Manipulation

1. Fetch API
The fetch() method starts the process of fetching a resource from a server.
The fetch() method returns a Promise that resolves to a Response object.

const data = await fetch('https://dummyjson.com/products/1');

const jsonData = await data.json();

or

fetch(url)
.then(response => {
// handle the response
})
.catch(error => {
// handle the error
});

Handling the status codes of the Response


The Response object provides the status code and status text via the status and
statusText properties. When a request is successful, the status code is 200 and status

16. fetch APIs and DOM Manipulation Revisited 1


text is OK:

async function fetchText() {


let response = await fetch('/readme.txt');

console.log(response.status); // 200
console.log(response.statusText); // OK

if (response.status === 200) {


let data = await response.text();
// handle data
}
}

fetchText();

We also have headers and other options in Fetch API, but we will learn more about
them later in this course (while learning NodeJS)

2. DOM Navigation

16. fetch APIs and DOM Manipulation Revisited 2


The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships.

In a node tree, the top node is called the root (or root node)

Every node has exactly one parent, except the root (which has no parent)

A node can have a number of children

Siblings (brothers or sisters) are nodes with the same parent

Navigating between Nodes


You can use the following node properties to navigate between nodes with
JavaScript:

parentNode

childNodes[ nodenumber ]

firstChild

lastChild

nextSibling

previousSibling

Node Values

<title id="demo">DOM Tutorial</title>

The element node <title> (in the example above) does not contain text.

It contains a text node with the value "DOM Tutorial".


The value of the text node can be accessed by the node's innerHTML property:

myTitle = document.getElementById("demo").innerHTML;

16. fetch APIs and DOM Manipulation Revisited 3


Accessing the innerHTML property is the same as accessing the nodeValue of the
first child:

myTitle = document.getElementById("demo").firstChild.nodeValue;

Document Body and Element

There are two special properties that allow access to the full document:

document.body - The body of the document (returns the <body> element)

document.documentElement - The full document (returns the <html> element)

Assignments
1. Build a Random Joke Generator whenever the Next Joke Button is Clicked. Use
API: https://icanhazdadjoke.com/slack

2. Add the bottom navigational dots in the Image Slider.

3. Build a List of Quotes along with the author names. Use API:
https://dummyjson.com/quotes

16. fetch APIs and DOM Manipulation Revisited 4

You might also like