[go: up one dir, main page]

0% found this document useful (0 votes)
34 views172 pages

FSD - Unit 1 Part 1

Unit 1 covers JavaScript fundamentals and the basics of the MERN stack, including key concepts such as objects, DOM manipulation, and server setup. It discusses JavaScript's role in creating dynamic web pages, its data types, operators, and control structures. Additionally, it introduces the MERN components: MongoDB, Express, React, and Node.js, emphasizing the need for this technology stack in full-stack development.

Uploaded by

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

FSD - Unit 1 Part 1

Unit 1 covers JavaScript fundamentals and the basics of the MERN stack, including key concepts such as objects, DOM manipulation, and server setup. It discusses JavaScript's role in creating dynamic web pages, its data types, operators, and control structures. Additionally, it introduces the MERN components: MongoDB, Express, React, and Node.js, emphasizing the need for this technology stack in full-stack development.

Uploaded by

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

Unit 1 – Javascript and

Basics of MERN stack


V. Lathika
AP/CSE
U19CS602 / U19CSD603 - Full Stack Development
VI Sem 2024 - 2025
Unit 1 – Javascript and Basics of
MERN Stack
JavaScript Fundamentals – Objects – Generators,
advanced iteration – modules – DOM tree – Node
properties – browser events – Event delegation – UI
Events – Forms, controls – Document and resource
loading – Mutation observer – Event loop: micro-tasks
and macro-tasks – MERN Components – React – Node.js –
Express – MongoDB – Need for MERN – Server – Less
Hello World – Server Setup – nvm – Node.js - npm
Javascript fundamentals
Javascript
 Abbreviated as JS.
 JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming
language with first-class functions.
o first-class functions - A programming language is said to have First-class functions
when functions in that language are treated like any other variable. For example,
in such a language, a function can be passed as an argument to other functions,
can be returned by another function and can be assigned as a value to a variable.
 JavaScript is an interpreted language. The browser interprets the JavaScript code
embedded inside the web page, executes it, and displays the output. It is not compiled
to any other form to be executed.
 All major web browsers have a dedicated JavaScript engine to execute the code on
users' devices.
Javascript
 JavaScript is a high-level, often just-in-time compiled language that conforms to the ECMAScript
standard.
o ECMAScript is a JavaScript standard intended to ensure the interoperability of web pages
across different browsers. It is standardized
Year ECMA by ECMA International in the document ECMA-
Browser
262 – [European Computer1995 Manufacturers Association]
JavaScript was invented by Brendan Eich
1996 Netscape 2 was released with JavaScript 1.0
1997 JavaScript became an ECMA standard (ECMA-262)
1997 ES1 ECMAScript 1 was released
1998 ES2 ECMAScript 2 was released
1999 ES3 ECMAScript 3 was released
2008 ES4 ECMAScript 4 was abandoned
2009 ES5 ECMAScript 5 was released
2015 ES6 ECMAScript 6 was released
2016 ES7 ECMAScript 7 was released
2017 ES8 ECMAScript 8 was released
2018 ES9 ECMAScript 9 was released
2019 ES10 ECMAScript 10 was released
2020 ES11 ECMAScript 11 was released
2021 ES12 ECMAScript 12 was released
2022 ES13 ECMAScript 13 was released
Javascript

 JavaScript is the programming


language for web users to convert
static web pages to dynamic web
pages.
 Web page designed using HTML
and CSS is static.
Why Javascript?
• To implement the requirement of handling user action like a click of a button or link
and to respond to these requests by displaying the expected output, server-side
languages like Java/JSP can be used as shown in the below diagram.
• But server-side languages have certain limitations such as :-
• Multiple request-response cycles to handle multiple user requests
• More network bandwidth consumption
• Increased response time

• If client-side scripting language JavaScript is used then, this can be done without
consulting the server
Why Javascript?
Where to write Javascript?
 JavaScript code can be embedded within the HTML page or can be written
in an external file.
 There are three ways of writing JavaScript depending on the platform:
o Inline/Internal Scripting
o External Scripting
 When JavaScript code are written within the HTML file itself, it is called
internal scripting.
 Internal scripting, is done with the help of HTML tag : <script> </script>
 This tag can be placed either in the head tag or body tag within the HTML
file.
Sample code Javascript
• JavaScript code written inside <head> element is as shown below :
<html>
<head>
<script>
//internal script
</script>
</head>
<body>
</body>
</html>
• JavaScript code can be written in an external file also. The file containing JavaScript code is
saved with the extension *.js (e.g. fileName.js)
• To include the external JavaScript file, the script tag is used with attribute 'src' as shown in
the below-given code-snippet:
<html>
<head>
<!-- *.js file contain the JavaScript code -->
<script src="*.js"></script>
</head>
<body>
Demo.html :-
</body>
</html> <html>
<head>
Demo.js :
<script src="Demo.js"></script>
let firstName="Rexha"; </head>
let lastName ="Bebe"; <body>
</body>
console.log(firstName+" "+lastName);
</html>
Identifiers
• Identifiers should follow the following:
 The first character of an identifier should be letters of the alphabet or an
underscore (_) or dollar sign ($).
 Subsequent characters can be letters of alphabets or digits or underscores (_)
or a dollar sign ($).
 Identifiers are case-sensitive. Hence, firstName and FirstName are not the
same.
 Reserved keywords are part of programming language syntax and cannot be used
as identifiers.
Types of Identifiers

 An identifier declared using ‘let’ keyword has a block scope i.e., it is available only
within the block in which it is defined.
 The value assigned to the identifier can be done either at the time of declaration or
later in the code and can also be altered further.
 All the identifiers known so far vary in their scope and with respect to the data it
holds.
let firstName="William";
 Example: myScript.js console.log("Welcome to JS course, Mr."+ firstName);
const

const pi = 3.14;

console.log("The value of Pi is: "+pi);

pi = 3.141592; /* This will throw an error because the assignment to a const


needs to be done at the time of declaration and it cannot be re-initialized. */

console.log("The value of Pi is: "+pi);


var
• As a best practice, use the 'var' keyword for variable declarations for function
scope or global scope in the program.

var firstName = "William";

console.log("Welcome to JS course, Mr." + firstName);

var firstName = "Goth"; /* Here, even though we have redeclared

the same identifier, it will not throw any error.*/

console.log("Welcome to JS course, Mr." + firstName);


Scope of identifiers

Keyword Scope Declaration Assignment


Redeclaration not Re-assigning
let Block
allowed allowed
Redeclaration not Re-assigning not
const Block
allowed allowed
Redeclaration Re-assigning
var Function
allowed allowed
Exercise
Write a JavaScript program to find the area of a circle using:
 radius
 pi <body>
<script>
const pi = 3.14159265358979323846;
var r, Area;
r = 5;
Area = pi * r * r;
console.log("Area of Circle is: " + Area);
document.write("Area of Circle is: " + Area)
</script>
</body>
Data types
• Data type mentions the type of value assigned to a variable.
• In JavaScript, the type is not defined during variable declaration.
Instead, it is determined at run-time based on the value it is initialized
with.
• Hence, JavaScript language is
a loosely typed or dynamically typed language.
• Example:

• let age = 24; //number

• let name = "Tom" //string

• let qualified = true; //boolean


Types of Datatypes
Primitive data types
• JavaScript has three “primitive” types: number, string, and
boolean
• Everything else is an object
• Numbers are always stored as floating-point values
• Hexadecimal numbers begin with 0x
• Some platforms treat 0123 as octal, others treat it as decimal
• Strings may be enclosed in single quotes or double quotes
• Strings can contains \n (newline), \" (double quote), etc.
• Booleans are either true or false
– 0, "0", empty strings, undefined, null, and NaN are false , other
values are true
Operators
• Operators are categorized into unary, binary, and
ternary based on the number of operands on which they
operate in an expression.
• JavaScript supports the following types of operators:
Arithmetic operators
let sum = 5 + 3; // sum=8
let difference = 5 – 3; // difference=2
let product = 5 * 3; // product=15
let division = 5/3; // division=1
let mod = 5%3; // mod=2
let value = 5;
value++; // increment by 1, value=6
let value = 10;
value--; // decrement by 1, value=9
Assignment operators
let num = 30; // num=30
let num += 10; // num=num+10 => num=40
let num -= 10; // num=num-10 => num=20
let num *= 30; // num=num*30 => num=900
let num /= 10; // num=num/10 => num=3
let num %= 10; // num=num%10 => num=0
Relational Operators
• Relational operators are used for comparing values and the
result of comparison is always either true or false.
• Relational operators shown below do implicit data type
conversion of one of the operands before comparison.
• Relational operators shown below compares both the values and
the value types without any implicit type conversion.
• 10 > 10; //false
• 10 >= 10; //true
• 10 < 10; //false
• 10 <= 10; //true
• 10 == 10; //true
• 10 != 10; //false
Logical operators
• Logical operators allow a program to make a decision
based on multiple conditions. Each operand is
considered a condition that can be evaluated to true or
false.

!(10 > 20); //true
(10 > 5) && (20 > 20); //false
(10 > 5) || (20 > 20); //true
typeof operator
• The “typeof “ operator can be used to find the data type
of a JavaScript variable.
• The following are the ways in which it can be used and
the corresponding results that it returns.
typeof "JavaScript World" //string
typeof 10.5 // number
typeof 10 > 20 //boolean
typeof undefined //undefined
typeof null //Object
typeof {itemPrice : 500} //Object
Unary operators
let nr1 = 4;
nr1++;
console.log(nr1);
++nr1;
console.log(nr1);

let nr2 = 4;
nr2--;
console.log(nr2);
Quiz
1. What data type is the following variable?
const c = "5";
2. What data type is the following variable?
const c = 91; 3.
3. Which one is generally better, line 1 or line 2?
let empty1 = undefined; //line 1
let empty2 = null; //line 2
4. What is the console output for the following?
let a = "Hello";
a = "world"; console.log(a);
Quiz
5. What will be logged to the console?
let a = "world";
let b = `Hello ${a}!`;
console.log(b);
6. What is the value of a?
let a = "Hello";
a = prompt("world");
console.log(a);
Quiz
7. What is the value of b output to the console?
let a = 5;
let b = 70;
let c = "5";
b++;
console.log(b);
8. What is the value of result?
let result = 3 + 4 * 2 / 8;
Quiz
9. What is the value of total and total2?
let firstNum = 5;
let secondNum = 10;
firstNum++;
secondNum--;
let total = ++firstNum + secondNum;
console.log(total);
let total2 = 500 + 100 / 5 + total--;
console.log(total2);
Quiz
10. What is logged to the console here?
const a = 5;
const b = 10;
console.log(a > 0 && b > 0);
console.log(a == 5 && b == 4);
console.log(true ||false);
console.log(a == 3 || b == 10);
console.log(a == 3 || b == 7);
Statements
• Statements are instructions in JavaScript that have to be executed
by a web browser. JavaScript code is made up of a sequence of
statements and is executed in the same order as they are written.
• A Variable declaration is the simplest example of a JavaScript
statement.
• Syntax: var firstName = "Newton" ;
• Other types of JavaScript statements include conditions/decision-
making, loops, etc.
• White (blank) spaces in statements are ignored.
• It is optional to end each JavaScript statement with a semicolon. But
it is highly recommended to use it as it avoids possible
misinterpretation of the end of the statements by JavaScript engine.
Expression
Statements types
Conditional statements
• Conditional statements help you to decide based on
certain conditions.
• These conditions are specified by a set of conditional
statements having boolean expressions that are
evaluated to a boolean value true or false.
Example
let workingHours = 9.20;
let additionalHours;
(workingHours > 9.15) ? additionalHours = "You have positive
additional hours" : additionalHours = "You have negative
additional hours";
console.log(additionalHours);
Switch statement
The Switch statement is used to select and evaluate one of the many blocks of
code.

Syntax:
switch (expression) {
case value1: code block;
break;
case value2: code block;
break;
case valueN: code block;
break;
default: code block;
}
• Non-Conditional statements are those
statements that do not need any condition to
Non-conditional control the program execution flow.
statements • In JavaScript, it can be broadly classified into
three categories as follows:
Example – switch statement
var perfRating = 5;
switch (perfRating) {
case 5: case 2:
console.log("Very Poor"); console.log("Commendable");
break; break;
case 4: case 1:
console.log("Needs Improvement"); console.log("Outstanding");
break;
break;
default:
case 3: console.log("Sorry!! Invalid Rating.");
console.log("Met Expectations"); }
break;
Non-conditional statements -break
 While iterating over the block of code getting executed within the loop, the loop may be required to
be exited if certain condition is met.
The 'break' statement is used to terminate the loop and transfer control to the first statement
following the loop.
 Below example shows for loop with five iterations which increment variable "counter".
 When loop counter = 3, loop terminates.
 Also, shown below is the value of the counter and loopVar for every iteration of the loop.
• var counter = 0;
• for (var loop = 0; loop < 5; loop++) {
• if (loop == 3) loopVar counter
• break; 0 1
1 2
• counter++;
2 3
• } 3 Loop terminated. counter = 3.
Non-conditional statements -
continue
 Continue statement is used to terminate the current iteration of the loop and continue
execution of the loop with the next iteration.
 Below example shows for loop with five iterations which increment variable "counter".
 When loop counter = 3, the current iteration is skipped and moved to the next iteration.
 Also, shown below is the value of the counter and the variable loop for every iteration of
the loop.
loopVar counter
• var counter = 0; 0 1
• for (var loop = 0; loop < 5; loop++) { 1 2
• if (loop == 3) 2 3
Iteration terminated. Hence counter is
• continue; 3
not incremented.
• counter++; 4 4
• }
Comments
• Comments in JavaScript can be used to prevent the
execution of a certain lines of code and to
add information in the code that explains the
significance of the line of code being written.
• JavaScript supports two kinds of comments.
Exercise
Write a JavaScript code to make online booking of theatre tickets and calculate the total price based
on the below conditions:
• If seats to be booked are not more than 2, the cost per ticket remains $9.
• If seats are 5 or more, booking is not allowed.
• If seats to be booked are more than 2 but less than 5, based on the number of seats booked, do the
following:
o Calculate total cost by applying discounts of 5, 7, 9, 11 percent, and so on for customer 1,2,3
and 4.
o Try the code with different values for the number of seats.
Loops
for loop
• 'for' loop is used when the block of code is expected to
execute for a specific number of times. To implement it,
use the following syntax.

let counter = 0;
for (let loopVar = 0; loopVar < 5; loopVar++) {
counter = counter + 1;
console.log(counter);
}
while loop
• while' loop is used when the block of code is to be executed as long
as the specified condition is true.

let counter = 0;
let loopVar = 0;
while (loopVar < 5) {
console.log(loopVar);
counter++;
loopVar++;
console.log(counter);
}
do-while loop
let counter = 0;
let loopVar = 0;
do {
console.log(loopVar);
counter++;
loopVar++;
console.log(counter);
}
while (loopVar < 5);
Quiz
1. What will be outputted to the console in this instance?
const q = '1';
switch (q) {
case '1’: answer = "one"; break;
case 1: answer = 1; break;
case 2: answer = "this is the one"; break;
default: answer = "not working";
}
console.log(answer);
Quiz
2. What will be outputted to the console in this instance?
const q = 1;
switch (q)
{
case '1': answer = "one";
case 1: answer = 1;
case 2: answer = "this is the one"; break;
default: answer = "not working";
} console.log(answer);
Quiz
3. What will be outputted to the console in this instance?
let login = false;
let outputHolder = "";
let userOkay = login ? outputHolder = "logout" :
outputHolder = "login";
console.log(userOkay);
Quiz
4. What will be outputted to the console in this instance?
const userNames = ["Mike", "John", "Larry"];
const userInput = "John";
let htmlOutput = "";
if (userNames.indexOf(userInput) > -1)
{ htmlOutput = "Welcome, that is a user"; }
else { htmlOutput = "Denied, not a user "; }
console.log(htmlOutput + ": " + userInput);
Array in JS
• JavaScript Array is a data structure that allows you to
store and organize multiple values within a single
variable.
• It is a versatile and dynamic object.
• It can hold various data types, including numbers,
strings, objects, and even other arrays.
• Arrays in JavaScript are zero-indexed i.e. the first
element is accessed with an index 0, the second
element with an index of 1, and so forth
Arrays

var name = []; // empty array


var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS

var ducks = ["Huey", "Dewey", "Louie"];


var stooges = []; // stooges.length is 0
stooges[0] = "Larry"; // stooges.length is 1
stooges[1] = "Moe"; // stooges.length is 2
stooges[4] = "Curly"; // stooges.length is 5
stooges[4] = "Shemp"; // stooges.length is 5
JS
Array methods
var a = ["Stef", "Jason"]; // Stef, Jason
a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
a.sort(); // Jason, Stef
JS

 array serves as many data structures : list, queue,


stack, ...
 methods: concat, join, pop, push, reverse, shift, slice, sort,
splice, toString, unshift
 push and pop add / remove from back
 unshift and shift add / remove from front
 shift and pop return the element that is removed 55
OBJECTS
Objects
• An object is a set of properties (key-value entries).
• A property key can only be a string or a symbol.
const person = {
name: "Alice",
age: 25,
greet: function () {
console.log(`Hello, my name is ${this.name}.`);
},
};

person.greet(); // Hello, my name is Alice.


Objects
• Objects are not too dissimilar to real-world objects.
• They have properties and they can perform actions, methods.
• An object is a chance to group multiple variables into one.
• This is done with curly brackets: { and }

let dog = { dogName: "JavaScript",


weight: 2.4,
let dogColor1 = dog["color"];
color: "brown",
let dogColor2 = dog.age;
breed: "chihuahua",
age: 3,
burglarBiter: true };
Objects in objects
let company = { companyName: "Healthy Candy",
activity: "food manufacturing",
address: {
street: "2nd street",
number: "123",
zipcode: "33116",
city: "Miami",
state: "Florida"
},
yearOfEstablishment: 2021
};
To access or modify one of the properties of the address here, we can use two
approaches:
company.address.zipcode = "33117";
company["address"]["number"] = "100";
Arrays in objects

let activity =
company.activities[1]; -> ??
Objects in arrays

let streetName = addresses[0].stre


Quiz
1. What is the output in the console?
const myArr1 = [1,3,5,6,8,9,15];
console.log(myArr1.indexOf(0));
console.log(myArr1.indexOf(3));

2. How do you replace the second element in an array


myArr = [1,3,5,6,8,9,15] with the value 4?
Quiz
3. What is the output in the console?
const myArr2 = [];
myArr2[10] = 'test’;
console.log(myArr2);
console.log(myArr2[2]);

4. What is the output in the console?


const myArr3 = [3,6,8,9,3,55,553,434];
myArr3.sort();
myArr3.length = 0;
console.log(myArr3[0]);
Quiz
5. What is the output in the console?
let car =
{ model: "Golf",
make: "Volkswagen",
year: 1999,
color: "black", };
let arrKeys = Object.keys(car);
console.log(arrKeys);
Exercise
• In this project, you will implement a data structure for a
product catalog and create queries to retrieve data.
• Create an array to hold an inventory of store items.
• Create three items, each having the properties of name,
model, cost, and quantity.
• Add all three objects to the main array using an array method,
and then log the inventory array to the console.
• Access the quantity element of your third item, and log it to
the console. Experiment by adding and accessing more
elements within your data structure.
Functions
 The JavaScript engine can execute JavaScript code in two
different modes:
 Immediate mode - As soon as the webpage loads on the browser,
JavaScript code embedded inside it, executes without any delay.
 Deferred mode - Execution of JavaScript code is deferred or
delayed until any user action like data input, button click, drop-
down selection, etc. occurs.
 Functions are one of the integral components of JavaScript.
A JavaScript function is a set of statements that performs a
specific task. They become a reusable unit of code.
Functions
• JavaScript has two types of functions.
• User-defined functions - JavaScript allows to write
own functions called as user-defined functions.
The user-defined functions can also be created
using a much simpler syntax called arrow
functions.
• Built-in functions - JavaScript provides several
predefined functions that perform tasks such as
displaying dialog boxes, parsing a string
argument, timing-related operations, and so on.
Writing functions
Parameters and arguments
Exercise

Create a basic calculator that takes two numbers and one


string value indicating an operation. If the operation
equals add, the two numbers should be added. If the
operation equals subtract, the two numbers should be
subtracted from one another. If there is no option
specified, the value of the option should be add.
Default or unsuitable parameters
Spread operator
• The spread operator is a special operator. It consists of
three dots used before a referenced expression or
string, and it spreads out the arguments or elements of
an array.
Quiz - Functions
Built-in
Description Example
functions
It throws an alert box and is often used when
alert() user interaction is required to decide whether alert("Let us proceed");
execution should proceed or not.
It throws a confirm box where user can click let decision =
confirm() "OK" or "Cancel". If "OK" is clicked, the function confirm("Shall we
returns "true", else returns "false". proceed?");
It produces a box where user can enter an
input. The user input may be used for some let userInput =
prompt() processing later. This function takes parameter prompt("Please enter
of type string which represents the label of the your name:");
box.
This function checks if the data-type of given isNaN(30); //false
isNaN() parameter is number or not. If number, it
returns "false", else it returns "true". isNaN('hello'); //true
It determines if the number given as parameter
is a finite number. If the parameter value is isFinite(30); //true
isFinite()
NaN,positive infinity, or negative infinity, this isFinite('hello'); //false
method will return false, else will return true.
Built-in
functio Description Example
ns
This function parses string and returns an integer number.
parseInt("10"); //10
It takes two parameters. The first parameter is the string to be parsed.
The second parameter represents radix which is an integer between 2 parseInt("10 20 30"); //10, only
and 36 that represents the numerical system to be used and is optional. the integer part is returned
parseInt()
The method stops parsing when it encounters a non-numerical character parseInt("10 years"); //10
and returns the gathered number.
parseInt("years 10"); //NaN, the
It returns NaN when the first non-whitespace character cannot be first character stops the parsing
converted to number.

This function parses string and returns a float number. parseFloat("10.34"); //10.34
The method stops parsing when it encounters a non-numerical character parseFloat("10 20 30"); //10
parseFloat
and further characters are ignored.
() parseFloat("10.50 years"); //10.50
It returns NaN when the first non-whitespace character cannot be
converted to number.
eval("let num1=2; let
It takes an argument of type string which can be an expression,
eval() num2=3;let result= num1 *
statement or sequence of statements and evaluates them.
num2;console.log(result)");
Built-in functions Description

It executes a given function after waiting for the specified number of milliseconds.
setTimeout() It takes 2 parameters. First is the function to be executed and the second is the
number of milliseconds after which the given function should be executed.

It cancels a timeout previously established by calling setTimeout().

clearTimeout() It takes the parameter "timeoutID" which is the identifier of the timeout that can
be used to cancel the execution of setTimeout(). The ID is returned by the
setTimeout().
It executes the given function repetitively.

setInterval() It takes 2 parameters, first is the function to be executed and second is the
number of milliseconds. The function executes continuously after every given
number of milliseconds.

It cancels the timed, repeating execution which was previously established by a


call to setInterval().
clearInterval() It takes the parameter “intervalID” which is the identifier of the timeout that can
be used to cancel the execution of setInterval(). The ID is returned by the
setInterval().
Scopes
• Variable declaration in the JavaScript program can be done
within the function or outside the function. But the
accessibility of the variable to other parts of the same
program is decided based on the place of its declaration.
This accessibility of a variable is referred to as scope.
• JavaScript scopes can be of three types:
• Global scope
• Local scope
• Block scope
• Variables defined outside function have Global Scope and
they are accessible anywhere in the program.
Exercise – Functions - Problem
Statement
• Write a JavaScript code to do online booking of theatre tickets
and calculate the total price based on the below conditions:
1. If seats to be booked are not more than 2, the cost per ticket remains
$9.
2. If seats are 6 or more, booking is not allowed.
3. If seats to be booked are more than 2 but less than 5, based on the
number of seats booked, do the following:
• Calculate total cost by applying a discount of 5, 7, 9, 11 percent, and so on for
customer 1,2,3 till 5
• Try the code with different values for the number of seats.
• Write the following custom functions to implement given
requirements:
1. calculateCost(seats): Calculate and display the total cost to be paid by
the customer for the tickets they have bought.
2. calculateDiscount(seats): Calculate discount on the tickets bought by
the customer. Implement using arrow functions.
Classes & Objects
Classes
• Classes in JavaScript was introduced in the
ES6/ECMAScript2015.
• A class is a type of function with keyword class.
• Class is executed in strict mode, So the code containing
the silent error or mistake throws an error.
• JavaScript classes can have a constructor method,
which is a special method that is called each time when
the object is created.
• Constructor methods are usually used to set initial
values for the objects.
Class example
Constructors
• The constructor method is a special method that we use
to initialize objects with our class blueprint.
• There can only be one constructor in a class.
• This constructor contains properties that will be set
when initiating the class.
Methods

• Functions on a class are


called methods.
• When defining these
methods, we don't use the
function keyword.
Inheritance
• It is the concept that classes can have child classes
that inherit the properties and methods from the parent
class.
Exercise – Classes and Objects
• Create an Employee class extending from a base class
Person.
• Approach to the solution:
• Create a class Person with name and age as attributes
• Add a constructor to initialize the values
• Create a class Employee extending Person with additional
attributes role and contact
• The constructor of the Employee to accept the name, age, role
and contact where name and age are initialized through a call
to super to invoke the base class constructor
• Add a method getDetails() to display all the details of
Employee.
Generators
Generators
• A generator function is a special type of function that
can pause its execution at any point and resume later.
• They are defined using the function* syntax and use the
yield keyword to pause execution and return a value.
• Generators allow you to pause the execution of a
function and resume it later, which can be helpful for
tasks like iterating over large data sets, asynchronous
programming, or managing state over time.
Asynchronous programming
• Asynchronous programming is a programming paradigm that
allows a program to handle long-running tasks, like fetching
data from the internet or accessing a database, without
blocking the execution of other tasks.
• Instead of waiting for a task to finish, the program can
continue running and handle the result of the task when it's
ready.
• Benefits of Asynchronous Programming
• Improved Performance: Allows multiple tasks to run concurrently,
utilizing resources more effectively.
• Responsive Applications: Prevents applications from freezing or
becoming unresponsive during long-running tasks.
Example
function* generate() {
yield 'Hello';
yield 'World';
return 'Done';
}
const generator = generate();

• The next() method is used to resume execution and retrieve the next
value.
• The done property indicates whether the generator has finished
executing.
• The yield operator is used to pause and resume a generator function.
Example
function* myGenerator() {
yield “Sona”;
Guess the
yield 2; Output?
yield “Tech”;
}

const gen = myGenerator(); // Create a generator object

console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
console.log(gen.next().value); // undefined (no more yields)
for loop – generator function
function* numbers()
{ Guess the
Output?
yield 10;
yield 20;
yield 30;
}
for (const num of numbers())
{ console.log(num); // 10, 20, 30 }
Generator methods

Method Description
next() Returns a value of yield
Returns a value and terminates
return()
the generator
Throws an error and terminates
throw()
the generator
JavaScript return Vs yield Keyword

return Keyword yield Keyword


Returns the value and Returns the value and
terminates the function. halts the function but
does not terminate the
function.
Available in both the Available only in
normal functions and generator functions.
generator functions.
Generators and
advanced iterations
Looping & Iterations
• Looping is when we want to run through the same block of code
a specific number of times, or repeatedly until a condition is
met.
• Common looping methods are ‘for’ loops, ‘while’ loops and
‘do…while’ loops.
• We specify this condition within the loop.
• Iteration occurs when we want to execute code once for each
item in a collection, usually elements in an array or properties
of an object.
• Iteration, where our code only executes on each element or
piece of data in a collection, looping can run as many times as
specified in our condition.
Looping vs Iteration
Arrow function
• Arrow functions were introduced in ES6.
• Arrow functions allow us to write shorter function syntax:
let myFunction = (a, b) => a * b;
document.getElementById("demo").innerHTML = myFunction(4, 5);
hello = () => {return "Hello World!";}
document.getElementById("demo").innerHTML = hello("Universe!");
hello = () => "Hello World!";
document.getElementById("demo").innerHTML = hello("Universe!")
let hello = "";
hello = (val) => "Hello " + val;
document.getElementById("demo").innerHTML = hello("Universe!");
Iterators
• The Iterators are objects with a special structure in
JavaScript.
• They must have a next() method that returns an object with
the value and done properties.
• The value property represents the next value in the
sequence and the done property indicates whether there are
more values to be iterated.
• The Iterators are commonly used for iterating over data
structures like arrays, maps, and sets.
• The iterable protocol mentions that an iterable should have
the Symbol.iterator key.
Iterables and iterators
• The data structures that have the Symbol.iterator() method
are called iterables. For example, Arrays, Strings, Sets, etc.
• An iterator is an object that is returned by the
Symbol.iterator() method.
• Syntax for creating an Iterable
const iterable = {
[Symbol.iterator]: function() {
// Return an iterator object
}
};
JavaScript next() Method
• The iterator object has a next() method that returns the
next item in the sequence.
• The next() method contains two properties: value and
done.
• value
• The value property can be of any data type and represents the
current value in the sequence.
• done
• The done property is a boolean value that indicates whether the
iteration is complete or not. If the iteration is incomplete, the
done property is set to false, else it is set to true.
Example - Iterator
const colors = ['red', 'green', 'blue']; OUTPUT
const GFG = colors[Symbol.iterator](); { value: 'red', done: false }
{ value: 'green', done:
console.log(GFG.next()); false }
console.log(GFG.next()); { value: 'blue', done: false }
{ value: undefined, done:
console.log(GFG.next()); true }
console.log(GFG.next());
Advanced Iterations
const range = {
*[Symbol.iterator](start = 0, end = 10, step = 1) {
for (let i = start; i < end; i += step) {
Guess the
yield i; Output?

} }, };

for (const num of range[Symbol.iterator](1, 5)) {


console.log(num);
}
Example - Iterator
const myNumbers = {
[Symbol.iterator]: function () {
let n = 0;
return {
Guess the
next() { Output?
n += 10;
return { value: n, done: n > 100 };
}
};
}
};
[...myNumbers].forEach (num => console.log(num));
Infinite Iterators
function* infiniteSequence() {
let num = 0;
while (true) {
yield num++; Guess the
Output?
}
}

const iterator = infiniteSequence();


console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
Fibonacci sequence – Generators &
Iterators
function* fibonacci() {
let [prev, curr] = [0, 1];
while (true) {
yield curr;
[prev, curr] = [curr, prev + curr]; Guess the
} Output?

const fib = fibonacci();


console.log(fib.next().value);
console.log(fib.next().value);
console.log(fib.next().value);
console.log(fib.next().value);
console.log(fib.next().value);
MODULES
Modules
• JavaScript modules allow you to break up your code into separate
files.
• This makes it easier to maintain a code-base.
• Modules are imported from external files with the import statement.
• Modules also rely on type="module" in the <script> tag.
• Modules with functions or variables can be stored in any external
file.
• There are two types of exports: Named Exports and Default Exports.
• Example
<script type="module">
import message from "./message.js";
</script>
Simple example - Modules
index.js
import * as p from people.js
index.html
"/people.js"; const fighters=[
<!DOCTYPE html>
{name:"Nathan", born:2019
<html>
{name:"Devi", born:2020},
<head> console.log(p.fighters[0]);
{name:"Harinikaa", born:20
<title></title>
console.log(p.person); ];
</head>
<body> console.log(p.king); let person = "AAA";
<script src="index.js" let king = " BBB";
type=""module"></script> export {fighters, person, kin
</body>
</html>
DOM tree
Docume
nt object
model

• It is a programming interface that allows us to create, change, or remove


elements from the document.
• The W3C DOM standard is separated into 3 different parts:
• Core DOM - standard model for all document types
• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents
<html>
<head>
<title>Tab in the
browser</title>
</head>
<body>
<h1>DOM</h1>
<div>
<p>Hello web!</p>
<a
href="https://google.c
om">Here's a link!</a>
</div>
</body>
</html>
The DOM programming interface
• The HTML DOM can be accessed with JavaScript (and
with other programming languages).
• In the DOM, all HTML elements are defined as objects.
• The programming interface is the properties and
methods of each object.
• A property is a value that you can get or set (like
changing the content of an HTML element).
• A method is an action you can do (like add or deleting
an HTML element).
DOM tree
• All these objects are accessible using JavaScript, and we
can use them to modify the page.
• For example, document.body is the object representing
the <body> tag.
Example
<html>
<body>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello
World!";
</script>

</body>
</html>
Select elements in the document
• getElementById() – select an element by id.
• getElementsByName() – select elements by name.
• getElementsByTagName() – select elements by a tag name.
• getElementsByClassName() – select elements by one or more
class names.
• querySelector() –to select the first element that matches the
query.
• querySelectorAll() - select all the elements that match the
query
• innerHTML - getting or replacing the content of HTML elements.
Example DOM tree
<!DOCTYPE html>
<html>
<body>
<h2>Finding HTML Elements Using document.images</h2>
<img src="pic_htmltree.gif" width="486" height="266"> Guess the
<img src="pic_navigate.gif" width="362" height="255">Output?
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Number of images: " + document.images.length;
</script>
</body>
</html> Ref : https://www.w3schools.com/js/tryit.asp?
filename=tryjs_doc_images
Example
<h1>JavaScript getElementsByTagName() Demo</h1>
<h2>First heading</h2>
<p>This is the first paragraph.</p>
<h2>Second heading</h2> Guess the
Output?
<p>This is the second paragraph.</p>
<h2>Third heading</h2>
<p>This is the third paragraph.</p>
<script>
let headings = document.getElementsByTagName('h2');
console.log(`The number of H2 tags: ${headings.length}`);
</script>
Browser events
HTML events
• An HTML event can be something the browser does, or something a user
does.
• An event is a signal that something has happened.
• All DOM nodes generate such signals (but events are not limited to DOM).
• Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
• Often, when events happen, you may want to do something.
• JavaScript lets you execute code when events are detected.
• HTML allows event handler attributes, with JavaScript code, to be added
to HTML elements.
Interactive content
• Interactive content is content that responds to the actions of
a user.
• For example, of a web app in which you can create postcards
dynamically, or play a game on a website in a web browser.
• This interactive content is made possible by changing the
DOM based on user interactions.
• These interactions could be anything: entering text in an
input field, clicking somewhere on the page, hovering over a
certain element with the mouse, or a certain input with the
keyboard.
• All these are called events.
Specifying events
• There are three ways to specify events.
• Specifying events with HTML
• <p id="unique" onclick="magic()">Click here for magic!
</p>
• Specifying events with JavaScript
• document.getElementById("unique").onclick = function()
{ magic(); };
• Specifying events with event listeners
• document.getElementById("unique").addEventListener("click",
magic);
• document.getElementById("unique").addEventListener("click",
function() { magic(arg1, arg2) });
Mouse events
• ondblclick: when the mouse is double-clicked
• onmousedown: when the mouse clicks on top of an element
without the click being released
• onmouseup: when the mouse click on top of an element is
released
• onmouseenter: when the mouse moves onto an element
• onmouseleave: when the mouse leaves an element and all of its
children
• onmousemove: when the mouse moves over an element
• onmouseout: when the mouse leaves an individual element
• onmouseover: when the mouse hovers over an element
Keyboard events
• keydown and keyup – when a keyboard key is pressed
and released.

Form element events


• submit – when the visitor submits a <form>.
• focus – when the visitor focuses on an element, e.g. on
an <input>.
Document events
• DOMContentLoaded – when the HTML is loaded and
processed, DOM is fully built.

CSS events
• submit – when the visitor submits a <form>.
Unit 1 – Javascript and Basics of
MERN Stack
JavaScript Fundamentals – Objects – Generators,
advanced iteration – modules – DOM tree – Node
properties – browser events – Event delegation – UI
Events – Forms, controls – Document and resource
loading – Mutation observer – Event loop: micro-tasks
and macro-tasks – MERN Components – React – Node.js –
Express – MongoDB – Need for MERN – Server – Less
Hello World – Server Setup – nvm – Node.js - npm
Event delegation
Event bubbling
• Event bubbling in JavaScript is a mechanism where an event triggered
on a child element propagates upward through its ancestors in the
DOM.

• It allows parent elements to respond to events triggered by their child


elements.
• Propagation Direction: In event bubbling, the event starts at the target element
and propagates upward through its parent elements to the root of the DOM.

• Default Behavior: Event bubbling is enabled by default in JavaScript.

• Event Listeners: If multiple event listeners are attached in the bubbling phase,
they are executed in sequence, starting from the innermost target element.
Event bubbling and capturing
• Bubbling - When an event happens on a component, it
first runs the event handler on it, then on its parent
component, then all the way up on other ancestors’
components. By default, all event handles through this
order from center component event to outermost
component event.
• Capturing - The event handler is first on its parent
component and then on the component where it was
actually wanted to fire that event handler. In short, it
means that the event is first captured by the outermost
element and propagated to the inner elements. It is also
called trickle down.
Event bubbling and capturing
<!DOCTYPE html> <script>
<html>
function showMessage(event) {
<body>
<style> alert(`Clicked: ${this.id}`);
Exampl div { }
e
border: 2px solid black;
padding: 20px;
document.getElementById("outer").addEventList
margin: 10px;
ener("click", showMessage);
cursor: pointer;
}
</style> document.getElementById("middle").addEventLis
<div id="outer"> tener("click", showMessage);
Outer Div
<div id="middle"> document.getElementById("inner").addEventListe
Middle Div ner("click", showMessage);
<div id="inner">
</script>
Inner Div (Click me)
</div> </body>
</div> </html>
</div>
Event delegation
• Event Delegation is basically a pattern to handle events efficiently.
• Instead of adding an event listener to each and every similar element,
we can add an event listener to a parent element and call an event on
a particular target using the .target property of the event object.
• Example
const div = document.getElementsByTagName("div")[0]
div.addEventListener("click", (event) => {
if(event.target.tagName == 'BUTTON') {
console.log("button was clicked")
}
})
Event delegation
document.getElementById("btn1").addEventListener("click", () => alert("Button 1 clicked"));
document.getElementById("btn2").addEventListener("click", () => alert("Button 2 clicked"));
document.getElementById("btn3").addEventListener("click", () => alert("Button 3 clicked"));

document.getElementById("button-
container").addEventListener("click", function(event) {
if (event.target.tagName === "BUTTON") {
alert(`${event.target.textContent} clicked`);
}
});
<html lang="en">
<body>
<head>
<h2>Event Delegation Example</h2>
<meta charset="UTF-8"> <div id="button-container">
<meta name="viewport" <button>Button 1</button>
ampl
content="width=device-width, initial-
scale=1.0">
<button>Button 2</button>
<button>Button 3</button>
<title>Event Delegation
Example</title> </div>
#button-container { <script>
<style>
margin: 20px; document.getElementById("button-
body { padding: 10px; container").addEventListener("click", function(ev
font-family: Arial, sans-serif;border: 2px solid #333;if (event.target.tagName === "BUTTON"
text-align: center; display: inline-block; alert(`${event.target.textContent} clic
} }
margin-top: 50px;
button {
});
} margin: 5px;
</script>
padding: 10px;
</body>
font-size: 16px;
</html>
cursor: pointer;
}
</style>
UI events and
forms
UI events
• UI events – occur when a user interacts with the
browser’s user interface (UI) – work with window object
Forms
• A form is a container/holder • The HTML <form> element can contain
that can hold several elements. one or more of the following form
elements:
• In JavaScript, the concept of
forms is used to collect user’s 1. <input>
input using different elements 2. <label>
such as input fields, buttons, 3. <select>
labels, fieldsets, text fields, and 4. <textarea>
so on. 5. <button>
6. <fieldset>
• JavaScript can be used to 7. <legend>
interact with the forms, to 8. <datalist>
validate the forms, to process 9. <output>
the forms, etc. 10. <option>
11. <optgroup>
Example
<body>
<p id="details"> </p>
<form>
Name: <input type="text" id="name"/>
<br><br>
Age: <input type="text" id="age"/>
<br><br>
<input type="button" value="Show Details" onclick="showDetails()"/>
</form>
<script>
function showDetails(){
var empDetails = document.getElementById('details');
var empName = document.getElementById('name');
var empAge = document.getElementById('age');
empDetails.innerHTML = "Name: " + empName.value + "<br>" + " Age:
" + empAge.value;
}
</script>
</body>
addEventListener()
• The addEventListener() method of the EventTarget interface sets up a
function that will be called whenever the specified event is delivered
to the target.
• addEventListener(type, listener)
• addEventListener(type, listener, options)
• addEventListener(type, listener, useCapture)
• Type - A case-sensitive string representing the event type to listen for.
• Listener - The object that receives a notification (an object that
implements the Event interface) when an event of the specified type
occurs.
• useCapture - A boolean indicating whether the event should be
captured during the capture phase (true) or the bubbling phase (false).
Example addEventListener()
document.getElementById("myButton").addEventListener("click",
function() {
Basic Click Event
alert("Button clicked!");
});

const myElement = document.getElementById("myElement");


myElement.addEventListener("mouseenter", () => {
console.log("Mouse entered the element");
});
myElement.addEventListener("mouseleave", () => {
console.log("Mouse left the element");
});
Handling Multiple Event
Example addEventListener()
assing a Named Function
function handleClick() {
console.log("Element clicked!");
}
document.getElementById("clickableDiv").addEventListener("click", handleClick);

Using Event Object


document.addEventListener("keydown", function(event) {
console.log(`Key pressed: ${event.key}`);
});
Document and
resource loading
Document and resource loading
• The browser provides events to track the loading
process.
• The lifecycle of an HTML page has three important
events:
• DOMContentLoaded – the browser fully loaded HTML, and the
DOM tree is built, but external resources like pictures <img>
and stylesheets may not yet have loaded.
• load – not only HTML is loaded, but also all the external
resources: images, styles etc.
• beforeunload/unload – the user is leaving the page.
Document and resource loading
• Each event may be useful:
• DOMContentLoaded event – DOM is ready, so the
handler can lookup DOM nodes, initialize the interface.
• load event – external resources are loaded, so styles
are applied, image sizes are known etc.
• beforeunload event – the user is leaving: we can check
if the user saved the changes and ask them whether
they really want to leave.
• unload – the user almost left, but we still can initiate
some operations, such as sending out statistics.
DOMContentLoaded
<script>
function ready()
• The {
DOMContentLoaded alert('DOM is ready’);
event happens on alert(`Image size: ${img.offsetWidth}x$
{img.offsetHeight}`);
the document }
object.
• We must use document.addEventListener("DOMContentLoaded
", ready);
addEventListener to </script>
catch it:
document.addEventLi <img id="img"
stener("DOMContentL src="https://en.js.cx/clipart/train.gif?
speed=1&cache=0">
oaded", ready);
Load event
• Find all resources (images, CSS, scripts) have finished
loading

window.addEventListener("load", function() {
console.log("Page and all resources loaded");
});
beforeunload and unload Events
• Fired when a user is leaving the page.

window.addEventListener("beforeunload", function(event)
{
event.preventDefault();
event.returnValue = "Are you sure you want to
leave?";
});
event.preventDefault()
• The event.preventDefault() method prevents the default
behavior of an event from occurring.
• It is commonly used to stop actions like form
submission, link navigation, and right-click context
menus.
Mutation observer
Mutation Observer
• Mutation Observer is a Web API provided by modern
browsers for detecting changes in the DOM.
• Using Mutation Observer, when something in the DOM
changes, we can invoke a callback function to react to
those changes.
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
1. callback – A function executed when mutations are
detected.
2. targetNode – The DOM element to observe.
3. config – An object specifying the types of mutations to
How does it works? Step 1
• Create MutationObserver instance by passing it a function that
would be called every time a mutation has occurred.
• The first argument (i.e “mutations”) of the function is a
collection of all mutations which have occurred in a single batch.
• Each mutation provides information about its type and the
changes which have occurred.
var mutationObserver = new
MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation);
});
});
How does it works? Step 2
• Use observe() method to start observing the DOM
changes. The targetNode is the root of the subtree of
nodes to monitor for changes.
• The observerOptions parameter contains properties we
want to observe eg. childList, attributes..etc.var

mutationObserver.observe(targetNode, observerOptions);
How does it works? Step 3

• Use the disconnect() method anytime to stop observing


for the specified DOM changes.

mutationObserver.disconnect();
Mutation Observer - Options
• childList: It is used to observe the mutation in the target node’s child
elements.
• attributes: It is used to observe the mutation of the target node’s attributes.
• characterData: It is used to observe the mutation of the target node’s data.
• subtree: It is used to observe the mutation of the target and the target’s
descendants.
• attributeOldValue: It is used to observe the target’s attribute value before
the mutation. It is set to true if the attribute value is set to true.
• characterDataOldValue: It is used to observe the target’s data before the
mutation needs to be recorded. It is set to true if the characterData is set to
true.
• attributeFilter: If not all attribute mutations need not be observed, set the
attributeFilter to an array of attribute local name
Example - Observing Attribute
Changes
• Detect when an attribute (e.g., class, id, style) changes.

const target = document.getElementById("myElement");

const observer = new MutationObserver((mutations) => {


mutations.forEach((mutation) => {
console.log(`Attribute ${mutation.attributeName} changed!`);
});
});

observer.observe(target, { attributes: true });


Example – Observing Child Node
Changes
• Detect when elements are added or removed inside a container.

const container = document.getElementById("container");

const observer = new MutationObserver((mutations) => {


mutations.forEach((mutation) => {
console.log("Child nodes changed:", mutation);
});
});

observer.observe(container, { childList: true });


Example - Observing Text Content
Changes
• Detect when text inside an element is modified.

const textElement = document.getElementById("text");

const observer = new MutationObserver((mutations) => {


mutations.forEach((mutation) => {
console.log("Text content changed:", mutation.target.textContent);
});
});

observer.observe(textElement, { characterData: true, subtree: true });


<!DOCTYPE html>
<html>

<head>
<title>
MutationObserver Example
</title>
<style>
#colorDiv {
width: 100px;
height: 100px;

/* Giving red color initially to the box */


background-color: red;
}
</style>
</head>

<body>

<!-- Created a box having red color initially -->


<div id="colorDiv"></div>
<script> // Start observing the target
function mutationCallback(entries, observer) { // node for attribute changes
const mutation = entries[0]; const config = {
if (mutation.type === 'attributes' attributes: true, attributeFilter: ['style']
&& mutation.attributeName === 'style') { };
const colorDiv = document observer.observe(colorDiv, config);
.getElementById('colorDiv');
const computedStyle = // Simulate changing the color after 3 secon
getComputedStyle(colorDiv); setTimeout(() => {
const currentColor = colorDiv.style
computedStyle.backgroundColor; .backgroundColor = 'blue';
console.log('Color changed to:', currentColor); }, 4000);
} setTimeout(() => {
} colorDiv.style
// Create a mutation observer object .backgroundColor = 'black';
const observer = }, 6000);
new MutationObserver(mutationCallback); </script>
</body>
</html>
Unit 1 – Javascript and Basics of
MERN Stack
JavaScript Fundamentals – Objects – Generators,
advanced iteration – modules – DOM tree – Node
properties – browser events – Event delegation – UI
Events – Forms, controls – Document and resource
loading – Mutation observer – Event loop: micro-tasks
and macro-tasks – MERN Components – React – Node.js –
Express – MongoDB – Need for MERN – Server – Less
Hello World – Server Setup – nvm – Node.js - npm
Event loop
Event loop
• Event loop is simply an infinite loop.
• JavaScript is not the first place where event loop
concept is being used.
• Asynchronous programming
• Some examples of asynchronous functions are
setTimeout, callbacks, promises, handling events,
network requests, etc…
• JavaScript uses an event loop to handle all these kinds
of asynchronous tasks using a single thread.
• Event loop involves Call stack, Macro tasks and Micro
tasks.
Event loop
• The JavaScript event loop is a mechanism that allows
the execution of JavaScript code to be non-blocking.
• It works by continuously executing tasks one by one
from the task queue and allowing other codes to run
between them.
• This means that a code can continue to run even if
there is a long-running task being executed.
Call stack
• The call stack is a mechanism that is responsible for keeping
tracking off calling different functions.
• When a function is called, the JavaScript interpreter will add it to
the call stack and run it.
• If this function calls another function (which happens a lot),
Interpreter will add the called function to the call stack.
• We know that a stack is a LIFO Data Structure.
• LIFO stands for Last in, First out.
• So, the called function will be processed and after finishing the
process, the interpreter takes it off the stack and resumes the
execution of the previous function.
• This cycle will be repeated until the entire function gets processed.
Micro-tasks and Macro-tasks
• Microtasks are small, high-priority tasks that are
executed before any other tasks. Examples of
microtasks include Promises, MutationObserver,
queueMicrotask, and process.nextTick in Node.js.
Microtasks are executed immediately after the currently
executing task has been completed.
• Macrotasks are larger, lower-priority tasks that are
executed after all microtasks have been completed.
Examples of macrotasks include setTimeout, setInterval,
and UI rendering. Macrotasks are executed only after all
microtasks have been completed.
Example micro and macro tasks
console.log("Start"); Start
Timeout
setTimeout(function() { Promise
console.log("Timeout");
End
}, 0);

Promise.resolve().then(function() {
console.log("Promise"); // microTask! Start
End
}); Promise
Timeout
console.log("End");

You might also like