[go: up one dir, main page]

0% found this document useful (0 votes)
33 views1,126 pages

Web Merge PDF

Uploaded by

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

Web Merge PDF

Uploaded by

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

The Complete Lecture 1:

Javascript Course
Basics of
Javascript
-Bhavesh Bansal

@newtonschool
1
Table of Contents
● What is Javascript?
● Variable Declaration: var, let and const
● Differences between let, var and const
● Example of variable usages in real world scenarios

2
Considerations before we start... 🚀
In first few sections don’t stress about why code works and how to write efficient
code, or clean code. Just start learning and eventually you will understand
everything.

3
Let’s Start

4
What is Javascript?
Animate elements and
make pages dynamic.

A S CRIPT
JAV
Run
back-end
The language that makes web code with
Node.js.
Create web, pages come alive. 🤯
mobile, or desktop
apps.

Fetch and process data dynamically.


5
Javascript Role in Web Development
Javascript adds logic to our web pages:-

NOUNS
CONTENT
<p>Data</p>

means “paragraph”
ADJECTIVES
p {color: red}

means “the
paragraph text is VERBS
red” p.hide();

PRESENTATION PROGRAMMING
means “hide the
LANGUAGE: BUILDING paragraph”
WEB APPLICATIONS
6
Features of Javascript
JavaScript is a programming language that makes websites interactive, like adding
buttons, animations, and live updates.

JavaScript is
Lightweight Used both in frontend single-threaded,
and backend meaning it
processes one
task at a time in
Single-threaded
a sequential
Easy to Write
order.

Language of Web

7
Comparing with other languages
Let’s compare javascript with other languages:-

A S CRIPT
JAV

8
Challenges in Javascript
JavaScript's dynamic typing can cause bugs, and browser inconsistencies
require extra effort for compatibility.

Challenges

Browser
Dynamic Typing
Inconsistency
“1” + 2 => 12
1 + 2 => 3 Behaviour of javascript code
varies depending on which
Such issues due to dynamic browser is loading your web
typing leads unpredictable page.
code behaviour
9
The Origin of JavaScript

10
A Browser Ahead of Its Time
In the 1990s, Netscape Navigator changed the web. It was the first widely-used
browser, capable of beautifully displaying HTML and CSS

A S CRIPT
JAV

NetScape Browser Early HTML/CSS website


11
A World of Static Websites
But there was a problem — web pages were static. They couldn’t respond
dynamically to user actions

12
Brainchild: Brendan Eich
To solve the issue, Brendan Eich was tasked with creating a Java-like scripting
language for the web, and amazingly, he accomplished it in just 10 days!
A S CRIPT
JAV

13
JavaScript Revolutionizes the Web
With Brendan Eich's creation of JavaScript, websites transformed from static
pages into dynamic, interactive experiences.

A S CRIPT
JAV

14
Advancements in Javascript
1995 Brendan Eich creates the very first version of
JavaScript in just 10 days.
1996 Mocha changes to LiveScript and then to JavaScript, in
order to attract Java developers.`
ECMA releases ECMAScript 1 (ES1), the first official
1997
standard for JavaScript

2009 ES5 (ECMAScript 5) is released with lots of great new


features; Javascript
2015 ES6/ES2015 (ECMAScript 2015) was released: the was named
biggest update to the language ever! ‘Mocha’
2016 – ∞ Release of ES2016 / ES2017 / ES2018 / ES2019 / earlier.
ES2020 / ES2021 / … / ES2089
15
ECMA: Architect Behind Javascript
ECMA(European computer manufacturers association) plays a vital role in
standardizing and advancing JavaScript for modern development.

ECMA is a Committee
which regularly releases
standards for JavaScript
updates making
javascript more powerful
and efficient.

16
ES6: The Game Changer for JavaScript
ES6 introduced modern features like classes, modules, arrow functions, and
promises, making JavaScript more structured, concise, and easier to work with. And
not to forget let and const.

Most of the
javascript which we
use today is ES6.

17
How to run Javascript code?
You can run JavaScript directly in a browser using the Developer Console or by
embedding it in an HTML file with <script> tags.
A S CRIPT
JAV
1. Developer Console
2. Embedding in HTML( <script>...</script> tags)

18
Running javascript in Developer Console
Open the Developer Console in Chrome on Mac using Cmd + Option + J. Type
your JavaScript code in the Console tab and press Enter to execute it.
A S CRIPT
JAV
While on any
webpage, Press
Cmd + Option + J

In Console
you can write
javascript
code
19
Run javascript: script tag
We use script tag to either embed code inside it or link code:-

A S CRIPT
JAV

Embedding Code Linking External Code

20
Let’s Start Learning
Javascript Syntax

21
Variables in Javascript
Variables in JavaScript are containers for storing data values. They allow
developers to label and reference data in their programs,

PRIMITIVES

22
Storing Values in Javascript
JavaScript provides three keywords to declare variables: let, var, and const.
These can be used to declare and store values.

PRIMITIES

23
Syntax for variable declaration
Variables in JavaScript are declared using let, const, or var, followed by a
variable name.

Keyword used to declare a variable:-

PRIMITIVES

24
Similarly we can declare for let and const
Variables in JavaScript are declared using let, const, or var, followed by a
variable name, let is an better alternative of var

Once assigned,
the value of a
const variable
cannot be
changed or
PRIMITIVES
reassigned.

25
Why three keywords to store values?
Why does JavaScript need three different ways—var, let, and const—just to
store values? Is there really a big difference between them?

PRIMITIVES

26
Difference between var and let
let is the newer and preferred way to declare variables in JavaScript, offering
better control and safety compared to the older var.

Values
declared with
var and let can
be changed
PRIMITIVES

27
Understood!! But what about let and const
let lets you change the value later, while const keeps the value fixed once set.

28
But, how can we check the stored values?
We can check stored values in variables using console.log().

PRIMITIVES

29
Understanding console.log in javascript
console.log() is a JavaScript method that outputs messages or data, helping
developers debug and monitor code execution.

PRIMITIVES

30
Comments: The Footnotes of Code
Comments are like notes in a book, offering explanations without affecting the
code. Always comment your code, not just for others, but for your future self
too.

Comments helps you


understand the code
better later one.

31
Types of Comments
You can use either single line comments or multi-line comments in javascript.

Single Line Comments

Multi Line Comments

32
Comments: Single Line
Single-line comments are used to add brief explanations or notes within a
single line of code.

Single line comments start with // and end within the line.

33
Comments: Multi-Line
Multi-line comments are used to add longer explanations or comment out
multiple lines of code, enclosed between /* and */.

Use multi-line
comments for longer
explanations,
commenting out
blocks of code, or
providing detailed
documentation.

34
Some Real World Examples

35
Temperature Changes Over a Day
The temperature of a room or a city changes throughout the day.

In Programming:

PRIMITIVES

36
Bank Account Balance
Your bank account balance fluctuates with deposits and withdrawals.

In Programming:

PRIMITIVES

37
Speed of a Car
A car’s speed changes depending on driving conditions and actions.

In Programming:

PRIMITIVES

38
In Class Questions

39
References
1. MDN Web Docs - JavaScript: Comprehensive and beginner-friendly documentation for
JavaScript.
https://developer.mozilla.org/en-US/docs/Web/JavaScript
2. Eloquent JavaScript: A free online book covering JavaScript fundamentals and advanced topics.
https://eloquentjavascript.net/
3. JavaScript.info: A modern guide with interactive tutorials and examples for JavaScript learners.
https://javascript.info/
4. freeCodeCamp JavaScript Tutorials: Free interactive lessons and coding challenges to learn
JavaScript.
https://www.freecodecamp.org/learn/

40
Did you know?

JavaScript powers over


98% of websites,
making it most popular
programming
language! 🌐✨

41
Thanks
for
watching!

42
The Complete Lecture 1:
Javascript Course
Basics of
Javascript
-Bhavesh Bansal

@newtonschool
1
Table of Contents
● What is Javascript?
● Variable Declaration: var, let and const
● Differences between let, var and const
● Example of variable usages in real world scenarios

2
Considerations before we start... 🚀
In first few sections don’t stress about why code works and how to write efficient
code, or clean code. Just start learning and eventually you will understand
everything.

3
Let’s Start

4
What is Javascript?
Animate elements and
make pages dynamic.

A S CRIPT
JAV
Run
back-end
The language that makes web code with
Node.js.
Create web, pages come alive. 🤯
mobile, or desktop
apps.

Fetch and process data dynamically.


5
Javascript Role in Web Development
Javascript adds logic to our web pages:-

NOUNS
CONTENT
<p>Data</p>

means “paragraph”
ADJECTIVES
p {color: red}

means “the
paragraph text is VERBS
red” p.hide();

PRESENTATION PROGRAMMING
means “hide the
LANGUAGE: BUILDING paragraph”
WEB APPLICATIONS
6
Features of Javascript
JavaScript is a programming language that makes websites interactive, like adding
buttons, animations, and live updates.

JavaScript is
Lightweight Used both in frontend single-threaded,
and backend meaning it
processes one
task at a time in
Single-threaded
a sequential
Easy to Write
order.

Language of Web

7
Comparing with other languages
Let’s compare javascript with other languages:-

A S CRIPT
JAV

8
Challenges in Javascript
JavaScript's dynamic typing can cause bugs, and browser inconsistencies
require extra effort for compatibility.

Challenges

Browser
Dynamic Typing
Inconsistency
“1” + 2 => 12
1 + 2 => 3 Behaviour of javascript code
varies depending on which
Such issues due to dynamic browser is loading your web
typing leads unpredictable page.
code behaviour
9
The Origin of JavaScript

10
A Browser Ahead of Its Time
In the 1990s, Netscape Navigator changed the web. It was the first widely-used
browser, capable of beautifully displaying HTML and CSS

A S CRIPT
JAV

NetScape Browser Early HTML/CSS website


11
A World of Static Websites
But there was a problem — web pages were static. They couldn’t respond
dynamically to user actions

12
Brainchild: Brendan Eich
To solve the issue, Brendan Eich was tasked with creating a Java-like scripting
language for the web, and amazingly, he accomplished it in just 10 days!
A S CRIPT
JAV

13
JavaScript Revolutionizes the Web
With Brendan Eich's creation of JavaScript, websites transformed from static
pages into dynamic, interactive experiences.

A S CRIPT
JAV

14
Advancements in Javascript
1995 Brendan Eich creates the very first version of
JavaScript in just 10 days.
1996 Mocha changes to LiveScript and then to JavaScript, in
order to attract Java developers.`
ECMA releases ECMAScript 1 (ES1), the first official
1997
standard for JavaScript

2009 ES5 (ECMAScript 5) is released with lots of great new


features; Javascript
2015 ES6/ES2015 (ECMAScript 2015) was released: the was named
biggest update to the language ever! ‘Mocha’
2016 – ∞ Release of ES2016 / ES2017 / ES2018 / ES2019 / earlier.
ES2020 / ES2021 / … / ES2089
15
ECMA: Architect Behind Javascript
ECMA(European computer manufacturers association) plays a vital role in
standardizing and advancing JavaScript for modern development.

ECMA is a Committee
which regularly releases
standards for JavaScript
updates making
javascript more powerful
and efficient.

16
ES6: The Game Changer for JavaScript
ES6 introduced modern features like classes, modules, arrow functions, and
promises, making JavaScript more structured, concise, and easier to work with. And
not to forget let and const.

Most of the
javascript which we
use today is ES6.

17
How to run Javascript code?
You can run JavaScript directly in a browser using the Developer Console or by
embedding it in an HTML file with <script> tags.
A S CRIPT
JAV
1. Developer Console
2. Embedding in HTML( <script>...</script> tags)

18
Running javascript in Developer Console
Open the Developer Console in Chrome on Mac using Cmd + Option + J. Type
your JavaScript code in the Console tab and press Enter to execute it.
A S CRIPT
JAV
While on any
webpage, Press
Cmd + Option + J

In Console
you can write
javascript
code
19
Run javascript: script tag
We use script tag to either embed code inside it or link code:-

A S CRIPT
JAV

Embedding Code Linking External Code

20
Let’s Start Learning
Javascript Syntax

21
Variables in Javascript
Variables in JavaScript are containers for storing data values. They allow
developers to label and reference data in their programs,

PRIMITIVES

22
Storing Values in Javascript
JavaScript provides three keywords to declare variables: let, var, and const.
These can be used to declare and store values.

PRIMITIES

23
Syntax for variable declaration
Variables in JavaScript are declared using let, const, or var, followed by a
variable name.

Keyword used to declare a variable:-

PRIMITIVES

24
Similarly we can declare for let and const
Variables in JavaScript are declared using let, const, or var, followed by a
variable name, let is an better alternative of var

Once assigned,
the value of a
const variable
cannot be
changed or
PRIMITIVES
reassigned.

25
Why three keywords to store values?
Why does JavaScript need three different ways—var, let, and const—just to
store values? Is there really a big difference between them?

PRIMITIVES

26
Difference between var and let
let is the newer and preferred way to declare variables in JavaScript, offering
better control and safety compared to the older var.

Values
declared with
var and let can
be changed
PRIMITIVES

27
Understood!! But what about let and const
let lets you change the value later, while const keeps the value fixed once set.

28
But, how can we check the stored values?
We can check stored values in variables using console.log().

PRIMITIVES

29
Understanding console.log in javascript
console.log() is a JavaScript method that outputs messages or data, helping
developers debug and monitor code execution.

PRIMITIVES

30
Comments: The Footnotes of Code
Comments are like notes in a book, offering explanations without affecting the
code. Always comment your code, not just for others, but for your future self
too.

Comments helps you


understand the code
better later one.

31
Types of Comments
You can use either single line comments or multi-line comments in javascript.

Single Line Comments

Multi Line Comments

32
Comments: Single Line
Single-line comments are used to add brief explanations or notes within a
single line of code.

Single line comments start with // and end within the line.

33
Comments: Multi-Line
Multi-line comments are used to add longer explanations or comment out
multiple lines of code, enclosed between /* and */.

Use multi-line
comments for longer
explanations,
commenting out
blocks of code, or
providing detailed
documentation.

34
Some Real World Examples

35
Temperature Changes Over a Day
The temperature of a room or a city changes throughout the day.

In Programming:

PRIMITIVES

36
Bank Account Balance
Your bank account balance fluctuates with deposits and withdrawals.

In Programming:

PRIMITIVES

37
Speed of a Car
A car’s speed changes depending on driving conditions and actions.

In Programming:

PRIMITIVES

38
In Class Questions

39
References
1. MDN Web Docs - JavaScript: Comprehensive and beginner-friendly documentation for
JavaScript.
https://developer.mozilla.org/en-US/docs/Web/JavaScript
2. Eloquent JavaScript: A free online book covering JavaScript fundamentals and advanced topics.
https://eloquentjavascript.net/
3. JavaScript.info: A modern guide with interactive tutorials and examples for JavaScript learners.
https://javascript.info/
4. freeCodeCamp JavaScript Tutorials: Free interactive lessons and coding challenges to learn
JavaScript.
https://www.freecodecamp.org/learn/

40
Did you know?

JavaScript powers over


98% of websites,
making it most popular
programming
language! 🌐✨

41
Thanks
for
watching!

42
The Complete Lecture 2:
Javascript Course
Data Types and
Operators
-Vishal Sharma

@newtonschool
Table of Contents
● Primitive and Non-Primitive Data Types
● Types of primitive data types
● Type checking using typeof
● Arithmetic Operators
● Comparison Operators
● Logical Operators
● Assignment Operators
● Practical Usage and Examples
What are Data Types in javascript?
In JavaScript, data types are the classification of data values that tell the type of
data being dealt with.

Data types indicate


whether data is a
Object number, string, boolean,
etc.

Don't worry if you're


unfamiliar with them
yet.
Primitive and Non-Primitive
Data Types
Categories of Data Types
In JavaScript, data types are primitives (simple, immutable) and
non-primitives (complex, mutable, and multi-valued).

Data Types

Non-Primitives PRIMITIVE
PRIMITIVES
Let’s start with primitives
Primitive data types in JavaScript are simple, immutable values like
numbers, strings, booleans, symbols.

PRIMITIVES
Declaring Primitive Data types
Primitive data types in JavaScript are simple, immutable values like
numbers, strings, booleans, undefined, null etc. Let’s have a look:-

In JavaScript, the data type of a


variable is implicitly determined
by the value assigned to it, such
as a Number for numbers, a
String for text, and a Boolean
for true/false values
PRIMITIVES
Declaring Primitive Data types
Primitive data types in JavaScript are simple, immutable values like
numbers, strings, booleans, symbols.

If a variable has no value, it's


automatically undefined. To
intentionally keep it empty,
assign it null.

PRIMITIVES
Sounds overwhelming! Don’t worry
We all find it difficult when we start but it gets easier as we go along

Ask questions when you're


unsure, code when things feel
confusing, and remember—the
more you code, the better you'll
understand!

PRIMITIVES
Understanding Data types
Today, we begin our journey through data types, starting with the
most common and progressing to the more complex and powerful.

PRIMITIVES
Meet the Numbers
They represent quantities, from counting objects to calculating
complex formulas. It could be either simple integers or decimals.

They could either


be integers or
fractions.

PRIMITIVES
Declaration and Assignment
Let’s declare and assign some numbers:-

PRIMITIVES
Number methods
Number methods in JavaScript help manipulate numeric values efficiently. For
instance, ceil() rounds fractional value to nearest smaller integer, while floor()
rounds the number to nearest integer.

PRIMITIVES
Number Methods
JavaScript provides a variety of built-in methods and operations for
working with numbers. Let’s start with rounding and converting:-

PRIMITIVES
Number Methods
Let’s look at few more:-

PRIMITIVES
Interactive Activity

Using Math.random() find a number


between 2 and 8

16
Enter the Strings
They are the storytellers of JavaScript. They carry text, allowing us to
write messages, descriptions, and even dialogue for our characters.

They could either


be integers or
fractions.

PRIMITIVES
Declaration and Assignment
Let’s declare and print some strings:-

Single Quotes

PRIMITIVES

Double Quotes
Declaration and Assignment
Let’s learn how to use backticks and how it is different from ‘...’ and “...”

Backticks
Quotes

PRIMITIVES
Backticks: for template literals
Template literals use backticks (````) instead of single or double quotes for
defining strings. With them we can embed variables inside the string. Let’s see
how:-

Here name and


color are
variables.
Backticks: for template literals
Template literals use backticks (````) instead of single or double quotes for
defining strings. With them we can embed variables inside the string. Let’s see
how:-

With the help of


template literals we
embedded variables
in the string.
Accessing character values in string
Each character in the string is indexed starting from 0. Consider string
as row of mailboxes where each mailbox can hold a character.
Strings are indexed
Let’s try to access these character values using index.

We stored codechef in str


variable and extracted
each character using their
respective indexes.

charAt() function achieves


the same using index
values.
Is that it! There is so much more!
Strings in JavaScript come with a toolbox full of powerful methods to
explore, manipulate, and transform them.
1. toString()

2. includes()

JavaScript
Strings 3. indexOf()

4. replace()
String method: toString()
The toString() method in JavaScript converts a value (such as a number, array,
or object) into a string representation.

Here we are converting


numbers and arrays to
strings. Observer how they
are being converted.

Converting different data types to strings


String method: trim()
The trim() method in JavaScript removes whitespace from both ends of a string
without affecting the spaces in between words.

Can you observe the little


white spaces and how they
have gotten trimmed?

Trimming down the white spaces


String method: replace()
The replace() method in JavaScript is used to replace a specified substring or
pattern within a string with another substring.

We have successfully
replaced the word.
Repeat it in your code
editor.
String method: toString()
The toString() method in JavaScript converts a value (such as a number, array,
or object) into a string representation.

Can you observe the


little white spaces and
how they have gotten
trimmed?
String method: includes()
The includes() method in JavaScript checks if a string contains a specified
substring. It returns true if the substring is found, otherwise false.

It is checking if string
includes the word and
giving out boolean.
Observer the last one,
why is it false??
String method: indexOf()
The indexOf() method in JavaScript returns the index of the first occurrence of a
substring in a string or -1 if not found. It is case-sensitive.

Last one returns -1 since


Java word is not available
after 5th index.
Unraveling the Basics:
boolean, null, and undefined
boolean
Think of it as a switch—only two states: true or false.

Assigning boolean values


null
This represents "nothing" or "empty". You can assign it intentionally when a
variable is meant to have no value.
undefined
n JavaScript, undefined means a variable has been declared but has not been
assigned a value yet. It also represents the default value of uninitialized
variables.

undefined defined undefined vs defined


Any difference in null & undefined??
Even though they look similar but they are not same at all. You have fallen in
same trap like everyone else:-
Understanding differences
Let’s understand difference between zero, null and undefined
Truthy and Falsy values
Any value which is not falsy is considered true.

Apart from these values all the


values are considered true.
How to check truthy/falsy values??
We can check truthy/falsy values using Boolean function.

Here we used:-

1. “Hello”: Evaluated as true


2. “”: Evaluated as false

Try few other examples by your


own.
How to check data type: typeof
The typeof operator is used to determine the type of a given variable or value. It
returns a string indicating the type
Operators
What are operators?
In JavaScript, operators are special symbols used to perform operations on
values

Types

Arithmetic Comparison Logical Assignment


Arithmetic Operators
Arithmetic operators in JavaScript are used to perform mathematical
operations on numbers.
Arithmetic Operators: Example
Here’s are few examples of arithmetic operations in JavaScript:
Unexpected results we get sometimes
There are few anomalies which we face due to impermissible operations. Let’s
understand with code:-

Here you can observe


that not all mathematical
operations go as
expected.
Data type of infinity
In previous slide you can observer that divide by zero provides infinity, but if
infinity is a number. Want to check? Use isNaN().

You can observer infinity


is a number.
Comparison Operators
Comparison operators in JavaScript are used to compare two values and
return a Boolean value (true or false), helping to evaluate relationships between
values.
Comparison Operators: example
Here’s a simple code example to demonstrate the use of comparison operators
in JavaScript:

Pay caution while choosing


‘==’ over ‘===’ as they have
different outcomes
sometimes.
Comparison Operators: example
Continued…

The correct
placement of < or >
before = is important
for clarity.

Incorrect:- =<
Correct: <=
Logical Operators
Logical operators in JavaScript are used to perform logical operations on
values, typically boolean values (true or false).
Now how are you feeling??
You must be having love-hate relationship now. Don’t worry, you will feel at
home more you practice:-
Some Real World Examples
Calculating Discounts and Special Offers
When shopping, it's crucial to calculate the best price after discounts. For
example, if an item costs $100 and has a 20% discount.

Using arithmetic
operators to determine
the discount amount
and the final price.
Job Offers: Making Right Choice
To choose the better job offer, you can use comparison operators to evaluate
salaries.

Using a greater-than and


smaller than to help you
quickly see which offer
provides a higher salary.
Practice! Practice! And become boss
More you practice more you find easy way outs and more you will become
confident in writing javascript code. Practice is the key…
In Class Questions

55
Thanks
for
watching!

56
The Complete Lecture 3:
Javascript Course
conditionals and
loops
-Vishal Sharma

@newtonschool
Table of Contents

• Conditional Statements

• Ternary Operator

• Assignment Operator

• Loops

• Loops control statements

• Arrays and Objects

• Practical examples: basic examples with conditionals and loops

02
Conditional Statements
in Javascript

3
What are conditional statements?

Conditional statements help


determine the flow of execution in a
program based on specific
conditions.

PRIMITIVES
Types of conditional statements

Here are the main types of Conditional


Statements
conditional statements:-

if-else-if
if if-else switch
else
if statement

if statement is the most basic form of


conditional statement. Body of if
statement runs if test condition is
true.
if statement: Syntax

Let’s have a look at if statement syntax.


if statement: Example
Let’s understand with an example:-

I am an adult.

condition
if-else: Building on if statement

If you understand the if statement, adding the else part is straightforward. It simply
provides an alternative action when the condition is false.

if(condition) {

// body of if
if statement + else = }
else {

// body of else
}
if-else: Building on if statement

In the previous example, we checked


if a person is under 18 using only an
if statement." Modify the code to false true
include an else condition that prints
"You are not eligible." when the
person age is less than 18 years.
if-else: Example
Here age is less than 18 so else statement is executed:-

I am a minor.
Going beyond: if-else-if-else ladder
The if-else-if-else ladder helps the program check multiple conditions one by one
and take an action based on the first condition that’s true.
Going beyond: if-else-if-else ladder

Think of it like making plans: Plan A,


then Plan B if A fails, then Plan C, and
only facing the worst if all fail. The
if-else-if-else ladder works the same
way.
If-else-if-else: example
Let’s write code for delivering salutations at different parts of day:-
switch statement
switch statement is one among many tools for condition based execution of
statements.
switch statement

It selects one among many cases


whichever matches with value
passed inside switch.
switch statement: syntax
Let’s have a look at its syntax:-

We pass a variable inside switch


and whichever case matches that
variable value gets executed.
switch statement: example
Here switch checks fruit against each case. If no match is found, the default block
runs as a fallback.

Since case ‘apple’ matches the


fruit variable, “This is an
apple.” gets printed.

But what is the break


statement just after every test
case end??
switch statement: break
In this example we have added break after every test case. Do you know why?

Whenever a case matches


statements under it run and to
avoid other cases to run we
break its execution by just
adding break at the end of it.
Ternary Operator: A Shortcut for If-Else

The ternary operator is a concise way to write an if-else statement in a single line. It
evaluates a condition and returns one value if true, and another if false.
Ternary Operator: example

The ternary operator simplifies if-else code when only one condition is involved.
Ternary Operator: Comparison with if..else

Compared to if-else, the ternary operator offers smoother flow, improving


readability and understanding.

Now, after comparison you will


appreciate ternary operator.
Assignment Operators
Assignment operators are used to assign values to variables. The basic assignment
operator is =, but there are also shorthand operators like +=, -=, *= etc.

Usually we use shorthand


notations in writing javascript, it
saves time and energy

/
Assignment Operators: Example
Let’s have a look at an example:-

First one is the basic


assignment and rest of it are
shorthands.

We need not to write


shorthands necessarily, but it
saves time
Loops in real life

Every day we follow certain routine


which we repeat all over the week,
like brushing your teeth, taking
shower etc.
Loops in real life

We wake up, go for a walk, take a


shower, then take lunch and so on.
And next day we repeat the same
process.
Loops in Programming

Just like we repeat several tasks in


daily like, we need some tasks to be
repeated in programming and we
Types of loops
repeat those tasks with the help of
loops.

for while do-while


for loop
A for loop in JavaScript repeats a block of code a set number of times, typically
when the number of iterations is known in advance.
for loop: syntax
for loop has three parts, initial state, increment/decrement and end condition.

let
for loop: example
Let’s see an example:-

Here console.log
statement is printed
5 times as loop runs
for exact 5 times.
while loop
A while loop in JavaScript repeatedly executes a block of code as long as the
condition remains true, making it ideal when the number of iterations depends
on dynamic conditions.
while loop: syntax
for loop has just end condition, increment/decrement is done in body and
initialization is done before the loop starts.
while loop: example
Let’s see an example:-

Here console.log statement


is printed 5 times as loop
runs for exact 5 times. But
we did increment/decrement
inside body and initialization
before the loop
do-while loop
A do-while loop is a control flow statement that ensures a block of code runs at
least once, regardless of the condition.

It runs at least once because at start


body is run before actually checking
the test condition but only for the
first time.
do-while loop: syntax
Let’s have a look at it’s syntax:-

It is same as while loop


with only difference that
condition is checked at
the end.
do-while loop: example
Let’s see an example:-

Here condition got


checked at the end of
the loop.
Difference: while and do-while loop
The while loop checks the condition before execution, potentially skipping the
loop entirely if false. The do-while loop runs at least once before checking the
condition.
Difference: while loop
Here while loop will not run at all since test condition fails before first iteration.
Difference: do-while loop
Here do-while loop will run since body gets executed before it can run test
condition for the first time.
Control Statements:
break and continue

40
Control statement: break

The break statement stops a loop or


switch case from running further,
allowing you to exit early when a
condition is met.
Control statement: break

When the specified condition is met, the break statement immediately terminates
the loop and transfers control to the next statement after the loop.
Control statement: break (with)

Let’s understand with example:-

Here we broke out of loop


when condition i === 3 was
true

Output:
1
2
Control statement: break (without)

Outcome without break would be different

Since there is no break


statement all the values got
printed

Output:
1
2
3
4
5
Control statement: continue

The continue statement skips the


current iteration of a loop and moves
to the next one.
Control statement: continue example

In this example, the continue


statement skips the iteration when i
is 3, so 3 is not printed, but the loop
continues with the next values.

Go back in the previous


slides and compare it
with break statement.
Difference: break vs continue

The break statement exits the loop


entirely, while the continue
statement skips the current iteration
and moves to the next one.
Difference: break vs continue

Let’s compare the break and


continue examples: In the break
example, the loop stops entirely
before reaching 3, while in the
continue example, only 3 is skipped,
and the loop continues until 5.

break
Arrays and Objects

49
What are arrays?

Arrays are one of the best data structures for storing multiple values in a single
variable. Loops, such as for, while, or do-while are commonly used with arrays to
process or manipulate their elements efficiently.
Using array with for loop
Let’s use arrays along with loop. Here we will iterate array elements using for loop:-
Objects: Real world dictionary
Think of an object as a real-world dictionary, where the key is the word you're
looking up (e.g., "name" or "age"), and the value is the definition or meaning of that
word (e.g., "Alice" or 20).

Key Value

name Alice

age 20

In Javascript
Objects: Practical Example
When you have data that involves key-value pairs, objects are the most appropriate
choice. Here is an example:-

Here, title, author, year,


and genre are the keys
(or properties) of the
book object.
Storing Objects in array
You can store several objects inside an array too:-

We often store
multiple objects in
an array is to keep
things organized.
Object Array: Iterating using for loop
And then iterate over them using for loop:-
Object Array: Iterating using for…in loop
It would be lot simpler if we use for…in loop instead:-

In for…in loop we get keys


and in this case ‘i’ is the
key. And then we use use
that key to access the
object in the array.
Object Array: Iterating using for…of loop
If we want to access objects directly then we can use for…of loop

for…of loop directly


provides values stored in
the array.

Which iteration method


would you prefer?
Object: for…in vs for…of
The main difference between them with respect to objects is that for…in is iterable
over the keys of an object, whereas for…of can only iterate over an array.
Some Real World Examples
Calculating Discounts
When shopping, it's crucial to calculate the best price after discounts. For example,
if an item costs $100 and has a 20% discount, arithmetic operators can help us
determine the discount amount and the final price.
Job Offers: Making Right Choice
To choose the better job offer, you can use comparison operators to evaluate
salaries. For example, using a greater-than operator helps you quickly see
which offer provides a higher salary.
Shopping Cart: Calculating Bill
You are creating a shopping cart where each item has a price. You want to
calculate the total cost of all items in the cart.

Arrays, objects, and for loops


(and their variations) are
commonly used together to
solve many programming
problems.
In Class Questions

63
Thanks
for
watching!

64
The Complete
Javascript Course Lecture 4:
Functions
-Vishal Sharma

@newtonschool
Table of Contents
● Function Declaration and Syntax
● Parameters vs Arguments
● Spread and Rest Operator
● Function Return Values
● Higher Order Functions and Callback Functions
Function Declaration and
Syntax
What is a Function?
Function is a block of code made out of set of steps which result in a single
specific action.

What does it mean??


Let’s understand with an
analogy
Set of
Instructions
PRIMITIVES
Functions: Like Tying your shoes
A function is like tying your shoes—once you learn how, you can repeat the steps
whenever needed without rethinking the process

Functions = Tying your shoes

PRIMITIVES
Similarly we use functions in our programs
Let us define a tie shoes function and reuse it multiple times:-

PRIMITIVES
Naming a function
A programmer can give function a name and be used again and again.

PRIMITIVES
Challenge:

Write a Function to Display


Hello World
Were you able to do it??
Let’s start writing:-

How simple it is!!

PRIMITIVES
Think of a more complex task/function
Your dad wants you to calculate your daily expenses but you find it
difficult to do manually, you are crying for help!!
Your Rescue: Write an add function
Don’t worry functions are here for rescue.

But how to tell the function


what to add??
Function: parameters
We can define parameters in function to receive values.

Function Parameters
Here “num1” and
“num2” are
function
parameters.
Function: using parameters to add
Let’s use parameters to calculate the sum. And print it:-

Using parameters to
perform addition
Function: calling using arguments
Let’s just call the function by passing values inside it:-

Arguments are the values


passed to a function and
assigned to its parameters.

Actual values passed to


function are called arguments
Parameters vs Arguments
Difference: parameters and arguments
Now can you tell me the difference between these two??
Difference: parameters and arguments
Parameters are placeholders in a function declaration, while arguments
are the actual values passed during a function call.
Function Return Values
Function: return values
Wherever you assign some task to someone, you expect them to return something
which is could be final outcome/status of task etc.
Function: return values
Similarly function do return values on completion.
Function: return value syntax
Similarly function do return values on completion.

We want to return result


value to where function
was called from.
Function: return values with Example
Let’s reuse the add function again but this time we will return values instead of printing.
Function: return values with Example
Displaying returned values by calling the function and storing result in a variable.

Returning values is preferred over


displaying the result inside the
function.
Functions: Arrow Functions
Arrow functions are a shorter syntax for writing functions in JavaScript. They use the =>
syntax and are often more concise than traditional function expressions.

They not only make


function earlier to
write but also easier
to read and debug.
Functions: Arrow Function example
Let’s look at an example:-

Can you observe that


arrow function syntax is
simpler, easier and
more readable
compared to traditional
function.
Arrow Functions: Shortcut to Simplicity
Arrow functions make coding faster and cleaner, like taking a shortcut.

Feeling awesome,
right??
Higher Order Functions and
Callbacks
Values we can pass/return in a function
You can pass variety of values in a function. Let’s have a look:-

values Functions did I


heard correct??

Primitive Data
Objects Functions Others
Types
Higher-Order Functions
A higher-order function is a function either accepts a function as an argument or
returns a function.

But why do we
need function to
receive and accept
values??
Advantage of Higher-Order Functions
We receive or return functions as values to make our code flexible and reusable, allowing
us to define behavior dynamically and build more modular, maintainable programs.

Don’t worry? Let’s


Understood?? understand it with an
example in next slides.
Understanding HOF with example
Let’s create a greet function which takes name and function as input and returns a greeting.

This might seem of no


use, but when we will
read arrays methods like
map, filter etc, you will get
to know helpful the higher
order functions are.
Few popular higher order functions
Here are few most popular higher order functions:-

Don’t worry we will


learn these higher
order functions in
later lectures.
Understanding Callbacks
A callback is a function passed as an argument to another function, which is then
executed inside that function. You can name callback function as you wish.

Callback function
Rest and Spread Operator
Rest operator: team player of javascript
You are tasked to form a cricket team. First, pick your favourite duo to open the
batting, then select the captain. The rest make up the team.
Rest operator: team player of javascript
Let’s write a code for it:-
rest operator
grouping rest of
the values in
variable team

Output:

Captain: Virat Kohli


Team: [“Jasprit Bumrah”, “Hardik
Pandya”, “Ravindra Jadeja”,
“Others”]
Rest operator: team player of javascript
Let’s pass values to the function:-

Team members are grouped


together in receiving function
using rest operator
Spread Operator: The Team Promoter
The spread operator (...) takes values from a group (like an array or object) and
spreads them out into individual pieces, just like a promoter showing off each team
member one by one.
Spread Operator: The Team Promoter

Player 1 Player 2 Player 3 Player 4 Player 5 Others


Spread Operator: The Team Promoter
Let’s understand it with a code:-

Here We are using spread


operator to spread out
individual player names in
player 1, player 2, …etc.
In Class Questions

41
Thanks
for
watching!

42
The Complete
Javascript Course Lecture 4:
Functions
-Vishal Sharma

@newtonschool
Table of Contents
● Function Declaration and Syntax
● Parameters vs Arguments
● Spread and Rest Operator
● Function Return Values
● Higher Order Functions and Callback Functions
Function Declaration and
Syntax
What is a Function?
A function is a block of code made out of a set of steps that result in a
single specific action.

What does it mean??


Let’s understand with an
analogy
Set of
Instructions
PRIMITIVES
Functions: Like Tying your shoes
A function is like tying your shoes—once you learn how, you can repeat the steps
whenever needed without rethinking the process

Functions = Tying your shoes

PRIMITIVES
Similarly we use functions in our programs
Let us define a tie-shoe function and reuse it multiple times:

PRIMITIVES
Naming a function
A programmer can give a function a name and be used again and again.

PRIMITIVES
Challenge:

Write a Function to Display


Hello World
Were you able to do it??
Let’s start writing:

How simple it is!!

PRIMITIVES
Think of a more complex task/function
Your dad wants you to calculate your daily expenses, but you find it
difficult to do manually. You are crying for help!!
Your Rescue: Write an add function
Don’t worry, functions are here for rescue.

But how to tell the function


what to add??
Function: parameters
We can define parameters in a function to receive values.

Function Parameters
Here “num1” and
“num2” are
function
parameters.
Function: using parameters to add
Let’s use parameters to calculate the sum. And print it:

Using parameters to
perform addition
Function: calling using arguments
Let’s just call the function by passing values inside it:

Arguments are the values


passed to a function and
assigned to its parameters.

Actual values passed to


function are called arguments
Parameters vs Arguments
Difference: parameters and arguments
Now, can you tell me the difference between these two??
Difference: parameters and arguments
Parameters are placeholders in a function declaration, while arguments
are the actual values passed during a function call.
Function Return Values
Function: return values
You expect someone to return something whenever you give them a task; this could
be the task's status or final result, among other things.
Function: return values
Similarly, functions do return values on completion.
Function: return value syntax
Similarly, functions do return values on completion.

We want to return the


result value to where the
function was called from.
Function: return values with Example
Let’s reuse the add function again, but this time we will return values instead of printing.
Function: return values with Example
Displaying returned values by calling the function and storing the result in a variable.

Returning values is preferred over


displaying the result inside the
function.
Functions: Arrow Functions
Arrow functions are a shorter syntax for writing functions in JavaScript. They use the =>
syntax and are often more concise than traditional function expressions.

They not only make


functions easier to
write but also easier
to read and debug.
Functions: Arrow Function example
Let’s look at an example:

Can you observe that


arrow function syntax is
simpler, easier, and
more readable
compared to traditional
functions?
Arrow Functions: Shortcut to Simplicity
Arrow functions make coding faster and cleaner, like taking a shortcut.

Feeling awesome,
right??
Higher Order Functions and
Callbacks
Values we can pass/return in a function
You can pass variety of values in a function. Let’s have a look:

values Functions did I


hear correct??

Primitive Data
Objects Functions Others
Types
Higher-Order Functions
A higher-order function is a function either accepts a function as an argument or
returns a function.

But why do we
need function to
receive and accept
values??
Advantage of Higher-Order Functions
We receive or return functions as values to make our code flexible and reusable, allowing
us to define behavior dynamically and build more modular, maintainable programs.

Don’t worry? Let’s


Understood?? understand it with an
example in next slides.
Understanding HOF with example
Let’s create a greet function which takes name and function as input and returns a greeting.

This might seem of no


use, but when we will
read arrays methods like
map, filter etc, you will get
to know helpful the higher
order functions are.
Few popular higher order functions
Here are few most popular higher order functions:-

Don’t worry we will


learn these higher
order functions in
later lectures.
Understanding Callbacks
A callback is a function passed as an argument to another function, which is then
executed inside that function. You can name callback function as you wish.

Callback function
Rest and Spread Operator
Rest operator: team player of javascript
You are tasked to form a cricket team. First, pick your favourite duo to open the
batting, then select the captain. The rest make up the team.
Rest operator: team player of javascript
Let’s write a code for it:
rest operator
grouping rest of
the values in
variable team

Output:

Captain: Virat Kohli


Team: [“Jasprit Bumrah”, “Hardik
Pandya”, “Ravindra Jadeja”,
“Others”]
Rest operator: team player of javascript
Let’s pass values to the function:-

Team members are grouped


together in receiving function
using rest operator
Spread Operator: The Team Promoter
The spread operator (...) takes values from a group (like an array or object) and
spreads them out into individual pieces, just like a promoter showing off each team
member one by one.
Spread Operator: The Team Promoter

Player 1 Player 2 Player 3 Player 4 Player 5 Others


Spread Operator: The Team Promoter
Let’s understand it with a code:-

Here We are using spread


operator to spread out
individual player names in
player 1, player 2, …etc.
In Class Questions

41
Thanks
for
watching!

42
The Complete
Javascript Course Lecture 5:
Introduction to
Arrays
-Vishal Sharma

@newtonschool
Table of Contents
● What are Arrays?
● Javascript Arrays vs Python Lists
● Common methods:-
● Common methods
○ push ○ find
○ pop ○ includes
○ shift ○ sort
○ unshift

● Bonus Methods: join and split


● Call by Value vs Call by Reference
Arrays
Planning a party
Imagine you are organizing a party, for that you need to purchase lot of
items.

You will need, cake,


music player, food
and decorative items.
So you might want to
make a list out of it!!
PRIMITIVES
Planning a party: making lists
Let’s make lists, separate list for separate group of items:-

Lists help us to
keep our tasks
organized!!!

PRIMITIVES
Planning a party: making lists
Just like lists help you keep your tasks organized. Lists are very helpful in
programming too:-

PRIMITIVES
Array: Lists in javascript
Lists in javascript are called “Array”.

Definition: An array in JavaScript is a special object used to store multiple values in


a single variable.

PRIMITIVES
Why do we need array?
Variables store data, but managing many of them is hard. Arrays simplify
this by organizing multiple values in one place.

PRIMITIVES
Array: Definition and Syntax
An array in JavaScript is a special object used to store multiple values in a single
variable.

c MyArray

Add array values


Array Name PRIMITIVES inside these
brackets
Array: Storing values in arrays
We can declare array as well as store values at the same time.

MyArray true

Array Name You can use mixed data


type in arrays
PRIMITIVES
Array: Accessing the array values
We can access values stored in array by using indexes.

true If we just type


MyArray in console,
entire array would get
printed
true
Array Manipulation
Array manipulation
Often, we need to manipulate arrays by adding, removing, updating, or
extracting elements. Array methods make this process easy and efficient.

We achieve it using array


methods.
Common Javascript Methods
Here are some commonly used array methods:

push pop find

unshift shift includes

Add Items Remove items Search


Add Items: push
Adds one or more items to the end of the array. Initially there was 10, however we
could have started with empty array
Add Items: unshift
Instead of adding items at the end of the array we can add items to the beginning
of the array.
Difference: push and unshift
Let’s understand the difference between them two:-
Remove Items: pop
Removes the last item from an array.
Remove Items: pop
Let’s write javascript code for it:-
Remove Items: shift
Removes the first item from an array.
Difference: pop and shift
Let’s understand the difference between these two:-
Let’s quickly recap what we learned
Here’s a quick recap of the array methods we've covered:
Search Methods: find()
The find method helps you search through an array and find the first item that
matches a specific condition. Once it finds the item, it stops searching and returns
that item.

Since only two values i.e. 65


and 85 is greater than 50, but
since 65 is the first occurrence,
65 gets returned.
find(): Syntax
Let’s have a look at the syntax of find method.
Syntax:

find method logic, you can decide it


as per as the problem statement

Based on method logic we decide it


match is found or not, if found then
we return true
find() example 1
You are given an array of integers and your task is to find the first occurrence of a
number which is more than 10. Let’s use find() method for this purpose:-

Since 12 is the first number


which is more than 10,
output is 12.
find() example 2
Given an array having data of different people find out the person with exact age of
30 yrs. Let’s use an arrow function to shorten the code this time:-

We searched the array and


printed the information of the
person whose age is exactly
30.
Search Methods: includes()
The includes method checks if a certain value exists in an array. It returns true if the
value is found, and false if it’s not.
includes() example
Given an array of months, check if particular month is present in the array or not.

We haven’t stored
April in lowercase,
i.e., "apr”, so we got
false in the second
instance.
Copying the array and
modifying it directly
Copying the Array: slice() method
As the name suggests, the slice method cuts out a section of an array and returns a
new array containing that section, without modifying the original array.
slice(): Example
Let's take an initial array [1, 3, 5, 6, 7], and use the slice(0, 3) method to get a portion
of it.

Not the end index


is not included in
the slice!!
Modifying the Array: splice() method
The splice method changes the contents of an array by removing, replacing, or
adding elements at a specified index, modifying the original array.

Removing Items Adding Items


splice(): Example
splice(0, 3) removes 3 elements starting from index 0, modifying the original array to
[4, 5].

Here instead of
modifying the original
array splice method
modified the original
array.
Sort method
Organizing array: sort()
The sort() method allows us to arrange array elements in a specific order, making
data easier to understand and work with.

Unsorted Array

Sorting an array
organizes data,
improves readability
and speeds up
searches.

Sorted Array
sort(): How it works?
By default sort() method sorts in alphabetical and ascending order:-

We can pass compare


function as a callback
function to sort() to change
it’s default behaviour.
sort(): How it works?
To sort an array we need to use sort() method and pass a compare function to it:-
sort(): Example Ascending
Let’s sort the array in ascending order:-

If a - b is positive (a > b):

● Action: b is placed before a


because b is smaller.
● Reason: The sort() function
swaps the two elements to
ensure the smaller value comes
first.

Vice-versa if is a - b is negative (a < b)


sort(): Example Descending
Let’s sort the array in descending order:-

If b - a is positive (b > a):

● Action: b is placed before a


because b is larger.
● Reason: The sort function keeps
b first, ensuring the larger value
comes first.

Vice-versa if b - a is negative (b < a):


Bonus:
split and join methods
Array to String: join() method
The join() method is used to concatenate the array elements into a string.

We can pass separator


arguments in join method.

Let’s say we did


arr.join(‘|’)

C++|Java|Python
join(): Example
Let’s understand join method with few examples:-

When we don’t pass any


argument in the join() method
we get comma(,) as an
separator.
String to Array: split() method
We can reverse the join method i.e. we can create array from string by using split()
method:-

We need delimiters
inside the split() method.
Here in this case we use
whitespace:-
split(“ “)

split(“ “);
split(): Example
Let’s understand split method with few examples:

If we don’t pass delimiter, it by default Here we splitted the array using whitespace a
returns the whole text delimiter
Call by value vs call by reference
Call by Value vs Call by Reference
Understanding how JavaScript handles primitives and reference types in functions

Understood?? Don’t worry, let’s


jump into next slides and then
come back, to understand.
Primitive vs Non-primitive
Primitive data types (like numbers and strings) are passed by value (a copy), while
non-primitive data types (like objects) are passed by reference (a link to the original).

Called Called by
by Value Reference
Call by Value
Whenever primitive value is assigned to another variable or passed to a function a
new copy of it is generate.

Here 21224 and 21228


are memory locations
where num1 and num2
21224 are stored respectively.
21228
Call by Value: example
Let’s understand how it happens with an example.

Memory

num1 = 10 num1 value:10


21224

num2 = num1 num2 value:10


21228

num2 stored in
new location

num1 passed to num2 num2 = num2 + 5 num2 Value:10 + 5


21228
Call by Reference
Whereas in call by reference, the original variable and the function parameter point
to the same memory location.

3005 is their common


memory location.
Call by Reference: example
Let’s understand how it happens with an example. Here obj1 and obj2 are pointing
to same address.
Memory

obj1 = {...} obj1 {name: “Alice”, age: 25}


3005

obj2 {name: “Alice”, age: 25}


obj2 = obj1
3005

obj2 stored in
same location

obj2 got modified, obj2 {name: “Bob”, age: 30}


and so values in obj1
too 3005
Quick Recap
Let’s have a quick recap how values are passed based on its type.
In Class Questions

53
Thanks
for
watching!

54
The Complete
Javascript Course Lecture 6:
Array and Array
Methods
-Vishal Sharma

@newtonschool
Table of Contents
● Common methods:-
○ forEach
○ map
○ filter
○ reduce
● Iterating through arrays with loops
● Real-world Examples using array methods
Array Traversal and
Manipulation Methods
What are these methods??
We need these advanced array methods because they provide a concise, readable,
and efficient way to work with arrays. We can broadly classify them as:-

Search/Filter
Iteration Methods Reduction Methods
Methods

● forEach ● filter ● reduce


● map
PRIMITIVES
Pre-discussed: Loops in real life
Every day we follow certain routine which we repeat all over the week, like
brushing your teeth, taking shower etc.
Pre-discussed: Loops in Programming
Just like we repeat several tasks in daily like, we need some tasks to be repeated
in programming and we repeat those tasks with the help of loops.

Types of loops

for while PRIMITIVES do-while


Why do we need newer
methods?
Need for newer methods
We need newer iteration methods to simplify code, enhance readability, and
enable efficient operations like forEach, mapping, filtering and reducing arrays.

Let’s talk about forEach and


map methods
&
Iteration Methods: forEach
The forEach() method executes a provided function once for each array element
but does not create a new array.

You need not to write test


condition, neither to
initialize nor to
increment/decrement
anything
forEach syntax
Let’s have a look at its syntax:-

Can you observe that there is


a function passed to forEach
method? What kind of
function it is??
forEach example
Let’s learn to write forEach method, here we will declare and assign an array
and iterate over it using forEach method. Let’s begin:-

Can you appreciate how easy


it is compared to traditional
javascript loops?
forEach comparison with for loop
Let’s compare it with for loop of javascript, which one is easier to write??

forEach for loop


When to use what: for and forEach
Let’s compare it with for loop of javascript, which one is easier to write??

for loop forEach


When you want greater flexibility, as forEach is utilized for its simplicity and
you can decide start index, test readability, providing a straightforward
condition etc. way to iterate over array

You can conditionally break or skip code You cannot use break and continue
based on condition using break and statement and hence can’t optimize the
continue. Hence optimize the performance.
performance
Practice Question
Store 10 student names in an array and use a
forEach loop to print their names one by one.

14
Iteration Methods: What is map()
map is used to iterate over an array and creates a new array with the results,
while forEach simply iterates without returning anything.

Here we are iterating over


an array and returning a
new array with values
doubled.
map() Example 1
Let’s write code for implementing it:-
map() example 2
You are provided with a workers array and you need to iterate over that array
and return an array listing their workplaces.

peoples
array
The map function
iterates over the
peoples array and
returns an array of
their workplaces.

Array returned
by map
function
map() example 2
Let’s write code example of illustration in previous slide:-

Here we have iterated


over people array and
returned an array which
lists their workplaces
and stored in a variable
workplaces.
Practice Question
Use map to convert an array of strings to
their uppercase versions.

19
Difference: forEach and map method
Let’s observe the difference between the two:-
Higher Order functions
Higher order functions: map()
In previous illustrations we have used .forEach() and .map() method, these
functions are taking a callback function as input. These type of functions are
called higher order functions.

Here we passed a callback


function to map which is higher
order function
Higher order functions: forEach()
Similarly forEach() is also a higher order function as it receives a callback
function as an argument.

Similarly we would
have a look into more
higher order functions
in upcoming slides.

Callback function passed


to higher order function
forEach()
Search/Filter Methods: filter()
The filter method returns a new array with values from the original array that satisfy
the condition in the callback function.

Syntax: Array being iterated over

Current iterated value

If return value is true for particular


array item, array item is retained in
the array returned by filter method
Search/Filter Methods: filter()
Let’s say you have an array containing food items and it need to be iterated and
return just items having price over 15. Here is diagrammatic representation of the
solution:-

Here only those


items got filtered
out whose price
was more than
15.
filter() example
Let’s write code for example in the previous slide:-

Here bread and


cake is filtered
out.
Practice Question
Write a function using a filter to return all
elements in an array greater than a given
value.

27
Reduction Methods: What is reduce()
The reduce method transforms an array into a single value by applying a function to
each element, using an accumulator to store the result. After processing all
elements, it returns the final value.

Just like mixing


ingredients to make a
dish, the reduce method
combines values to
produce a single result.
reduce(): syntax
The reduce method iterates through an array and applies a callback function to
accumulate all elements into a single value, such as a sum, product, array, or object.
Syntax: Cumulative value that accumulates the results

Current iterated value of the


array

Initial value of accumulator


reduce() example 1
Here we were provided with an array, we can use reduce() method to calculate the
sum and return the value 14.

Sum of reduce
1 2 14
3 4
reduce() example 1
Let’s implement that example:-

reducer function accepts these arguments:-


1. Accumulator(acc): cumulative value that accumulates the results
2. Current Value(num): current value being processed
reduce() example 1
The reduce method iterates over the array, adding each value to an accumulator,
starting from 0, and returns the final sum after processing all elements. In this case,
the sum of [1, 2, 3, 4] is 10.

The accumulator starts at zero,


adding values at each step, and
the final sum is calculated at the
end.
reduce() example 2
Here given an array find out maximum value by scanning the array using reduce
method.

You might be tempted to


use forEach or map method.
Wait…wait… there is even
better way i.e. reduce()
reduce() example 2
Let’s write the javascript code using reduce().

Observe how crisp


and clear the code
is with reduce().
reduce() example 3
Provided an array of integers find out how many times integer value 2 got repeated
using reduce method.

Do this one by
yourself..
reduce() example 3
Let’s have a look at the solution:-

Were you able to do


it by yourself??
Practice Question
Find the first string in the array having more
than 5 characters.

37
In Class Questions

38
Thanks
for
watching!

39
The Complete
Javascript Course Lecture 7:
Introduction to
Objects
-Vishal Sharma

@newtonschool
Table of Contents
● Creating Objects
○ What are objects? Real-world analogies
○ Why use Object vs Other Data Types
○ Objects as key value pairs
● Accessing Properties
○ Dot Notation Deep Dive
○ Bracket Notation in Depth
● Modifying Objects ● Iterate over an object using for…in loop
○ Adding Properties ● Iterate over an object using for…of loop
○ Updating Properties
○ Deleting Properties
Creating Objects
Objects in real world
In the real world, objects are entities or things that have distinct characteristics and
behaviors. Objects can be described by their properties (attributes) and can perform
actions (methods).

Each of these objects has some


physical properties as well as
some functionality. Can you name
a few for each of them?
Objects in real world: Example
Let’s have a look at this car. It has certain properties and some functions/methods it
can perform.

Properties:-
1. color: red
2. make: Toyota
3. year: 2023
4. etc.

Methods/Functions:-
1. start
2. drive
3. etc.
Objects in Programming
They are collections of related data and functionality grouped together, often
mirroring real-world entities. Let’s write an object from the car from the previous slide.

In JavaScript, methods are also


considered properties of an
object.
Person as an Object
Similarly, we can create an object to represent a person. Imagine Ajay, a busy
professional juggling multiple tasks in a day. Alex has distinct traits like a name, black
hair, fair skin, etc along with several actions and functions it can perform.

Can you transform


this description into
an object? Function
Exercise
might only contain
console.log() for now?
Attend Meeting
Ajay
The Persona of Ajay: A Living Object
Here your implementation might differ; I have only taken a few actions as object
methods.

Now you should feel confident


writing an object by yourself.
Object Creation
Workshop

9
Workshop: Question
Create an object to represent a smartphone with the following properties: brand,
model, price, and features (as an array). And write some methods like messaging,
calling, etc.

Be confident, and you will be able to write in one go.

10
Objects vs Other Data Types
Objects vs Primitives: A Unified Concept
Objects are derived from primitive types but differ in storing and managing data,
grouping related data and behaviors for more flexibility.

Notice how various data


types are included inside
the object named 'ajay'.

12
How objects are different from primitives
They differ in the following ways:-

Aspect Primitives Objects

Structure Simple, single values like numbers or text. Complex things that store many We will
related values or actions. discuss
access
Storage Small and fast. Bigger and slower. methods in
later slides
Access Accessed by identifier storing value. Accessed via properties or methods
(e.g., object.property).

Behavior No inherent behavior; only stores data. Can include methods for processing
data.

Example var car = “Toyota” Visit slide 6 to see the example.


Objects as Key-Value Pairs
Objects as key-value pairs
Objects are essentially collections of related information represented as key-value
pairs. Values stored are accessible via that key.

name Ajay

age 30

occupation Engineer
Objects as key-value pairs
Methods also need to be accessed via its key as it is also considered as property.
Accessing Properties
Different ways to access properties
There are two main ways to access the properties of an object

Accessing Property

Dot Notation PRIMITIVESBracket Notation


Accessing Property: Dot Notation
In JavaScript, dot notation is the simplest and most common way to access the
properties of an object. You use a dot (.) followed by the property name.

● object is the object you're working


object.property with.
● property is the name of the
property you want to access.
Dot Notation: example
Let's revisit the car object with the properties color, make, and year, and then
access those properties using dot notation.

Accessing
properties using dot
notation
Dot Notation: example
Accessing the methods are no different.
Accessing Property: Bracket Notation
Bracket notation is used to access both properties and methods of an object,
especially when the property names are dynamic, contain spaces, or are stored
in variables.

Use single or double inverted


object[property] commas in case property is a
string.
Bracket Notation: example
Let's reuse the car example, object creation part remains the same but we will use
brackets instead of dot to access the object property.

This notation is very


useful in case
property name is
dynamic i.e.
changes frequently
maybe based on
some condition.
Bracket Notation: example
Accessing the methods are no different.

Here we are using


propertyName to
dynamically access
different properties of
the car object.
Modifying Objects
Why Modify Objects?
In JavaScript, objects often need to change to reflect new information.
We'll explore three ways to modify objects:

Modifying Objects

Add Property Update PropertyPRIMITIVES Delete Property


How to add properties
You can add new properties to an object anytime, expanding it dynamically. For
example, if you forget to define the car color, you can add it later like this:

We added a new
property using the
dot operator and
assigned it the
value "Red".
Adding a method property
Here we have added a method property using dot operator.

Try adding one more method


property by yourself.
How to Update Properties
You can modify the value of an existing property just the way you create a new
property.

Earlier color was ‘Red’, we have


later changed the value to ‘Blue’
by using assignment operator.
How to Update Properties
In the similar fashion we can update method properties too.

Sounds simple right??


How to Delete Properties
You can remove properties from objects using the delete keyword.

Caution

● Deleting a property makes it


completely unavailable in the
object.

● The deleted property cannot be


recovered, but the object itself
remains intact.

We got undefined because the property was


deleted.
How to Delete Properties
Methods can be deleted from an object just like properties using the delete
operator.

That’s it!
Iterating over an Object
Why Iterate Over Objects?
Objects store key-value pairs, but unlike arrays, they lack built-in iteration methods.
We need to loop through an object's properties to access each key and value.

We may need to iterate over


this object to display its
name Ajay
values, but there are also
many practical scenarios
age 30 where iteration is essential.

occupation Engineer
How to Iterate: for…in loop
We can iterate over an object using for…in loop

But how to
iterate
objects??
for…in loop is here for
rescue
Iterate Object: for…in loop
The for...in loop is used to iterate over the keys of an object, allowing you to access
both the key and its corresponding value.
Currently iterated Object being
key iterated

Body of for…in
for…in: Example
Let's iterate over the person object (with name, age, and occupation) and display its
keys and values.

Output:

name : Ajay
age: 30
occupation: Engineer
In Class Questions

38
Thanks
for
watching!

39
The Complete
Javascript Course Lecture 8:
Object Utility
Methods
-Vishal Sharma

@newtonschool
Table of Contents
● Introduction to Object utilities
● Data Retrieval Utilities
○ Object.keys()
○ Object.values()
● Copying Objects: Deep Copy vs Shallow Copy
● Practical Applications
○ Using map method to iterate object values
○ Using filter to filter out object entries
Introduction to Object Utilities
What are Object Utilities?
Object utilities in programming, especially in JavaScript, are built-in or custom
methods, functions, or techniques used to manipulate, transform, or analyze
objects.

They allow to access


and manipulate objects
in much simpler and
efficient manner.
Uses of Object Utilities
Object utilities help list properties, collect values, pair data, and rebuild structured
information.

Object.keys() Object.values() Object.values() Object.fromEntries()


List properties Collect Values Pair Data Rebuilds information

Observation #1

Observation #2
Data Retrieval Utility Methods
We have these three methods for retrieving data:-

Methods

Object.keys() Object.values() Object.entries()


Data Retrieval: Object.keys()
Object.keys() is a JavaScript method used to retrieve all the keys (property names) of
an object as an array.

Each object has one or


more key and these keys
correspond to a value.
Data Retrieval: Object.keys()
Before we jump into Object.keys() we need to understand the structure of an object.
Here there are two properties each having a key and value.

We can retrieve
property values of an
property using keys
in that object.
Data Retrieval: Object.keys()
We can retrieve the values using keys, but how to retrieve keys?? Object.keys()
method comes for rescue. Here is an example:-

Object.keys() method takes an


object as an argument and
returns all the keys in form of an
array.
Object.keys(): Use Cases
We can use Object.keys() to get an array of keys and then can iterate over that array
to access the values of that object. Here is an example:-

Accessing the value in the


object person using its keys.
Object.keys(): Use Cases
Or else we can also utilize to get the number of properties stored in the object.

Since Object.keys() return


an array containing all the
keys, we can use array
property length to get the
number of properties stored.
Data Retrieval: Object.values()
Just like Object.keys() return all the keys of the object, Object.values() retrieves all the
values of an object’s enumerable properties as an array.

We can retrieve values of properties


in an object using its keys. What if we
can access these values directly.

Here comes Object.values() handy.


Data Retrieval: Object.values()
Let’s understand it with an example:-

Here we retrieved all


the values of properties
stored in the Object.
Data Retrieval: Use Cases
We can iterate all values using forEach loop.

Here we retrieved all


the values of properties
stored in the Object.
Data Retrieval: Object.entries()
What if we need both key and values?? We can retrieve both key and values using
Object.entries.

Object.entries()
converts an object
into an array of
key-value pairs for
easy looping and
modification.
Data Retrieval: Object.entries()
Let’s understand it with an example:-

Object enumerable properties

Converted into array


Object.entries(): Use Cases
We use Object.entries() where we need both key and value pairs at the same time.

Oh! Great we can get both


key, value pairs at the same
time.
Data Retrieval: Use Cases
We can iterate all values using forEach loop.

Here we retrieved all


the values of properties
stored in the Object.
Data Creation: Object.fromEntries()
We learned that we can convert an Object to an Array using Object.fromEntries(),
what if we need other way around?

[[‘firstName’, ‘Harry’], [‘lastName’,


‘Potter’], [‘house’, ‘Gryffindor’]]
We use
Object.fromEntries() to
convert an Array to an
Object.

{firstName: “Harry”, lastName:


“Potter”, house: “Gryffindor”}
Object.fromEntries(): Example
Let’s Understand it with an example:-

Now you should be able to


convert array to object and
object to array with ease.
Shallow Copy vs Deep Copy
Not all Copies are equal
Copying an object in JavaScript isn't always simple—some copies stay connected to
the original, while others create a completely separate version.

Shallow Copy

Contents in We can create


copy in two
memory
ways

Deep Copy

Memory address: 28208


Reference Variables points to memory
In JavaScript, objects are stored in memory, and each object is assigned a memory
location. The memory address of that location is stored in a reference variable.

holds Contents in
Reference variable 1 28208
memory

Location where
contents are stored

Memory address: 28208


Storing address references
Thus reference variable points to the memory location, it doesn’t store the content
itself.

Contents in
Memory address:
Reference variable 1
28208 memory
Copying reference values
Copying reference values doesn’t mean copying the content itself but memory
reference to that content. Such a copy is called Shallow Copy.

Reference variable 1

Contents in
Copied to 28208
memory

Location where
Reference variable 2 contents are stored

Memory address: 28208


What if we updated the content?
Even if we update our content, still both the reference variables would point to same
memory location and in turn the updated content.

Reference variable 1

Updated
Copied to 28208 contents in
memory
Location where
Reference variable 2 contents are stored

Memory address: 28208


Shallow Copy: Copying references
A shallow copy means copying the memory reference, not the actual content.

Memory: 2432

person

anotherPerson

Both variables point


to the same memory.
Same Modifying one affects
content the other.
Copying the Content itself
What if we made a copy of content in the memory and then stored that new
memory location in another reference variable. It is called Deep Copy.

Memory address: 18202 Memory address: 28208

Reference variable 1

Contents in copied Contents in


memory memory
Reference variable 2
Deep Copy: Copying Content
One way of making a deep copy is by using JSON methods i.e. JSON.stringify() and
JSON.parse()

Changing our deep copy, wouldn’t


affect the original copy

Original copy remains Unchanged


Practical Applications
Unlocking the Power of Array Methods
Object utilities like Object.keys(), Object.values(), etc transform objects into array-like
structures, making possible to use array methods such as .map(), .filter(), and .reduce().

map()

filter()

reduce()
Object.keys() with map()
Object.keys() gets the keys of an object, and when used with .map(), it lets you easily
transform those keys into a new array.

Since most of the Object


utilities return an array,
we can iterate those
returned values using
array methods easily.
Object.values() with map()
Let’s iterate values using map:-
Object.keys() with map()
Object.keys() gets the keys of an object, and when used with .map(), it lets you easily
transform those keys into a new array.

Since most of the Object


utilities return an array,
we can iterate those
returned values using
array methods easily.
Filtering Object Entries
We can use Object.entries() along with .filter() to select specific key-value pairs from an
object based on their keys.
Iterating over filtered entries using for…in
We can further iterate over filtered entries using for…in loop:-

We can convert object into


desired array form using
Object Utilities and then we
can iterate them just like
we iterate arrays.
In Class Questions

37
References
1. MDN Web Docs - JavaScript: Comprehensive and beginner-friendly documentation for
JavaScript.
https://developer.mozilla.org/en-US/docs/Web/JavaScript
2. Eloquent JavaScript: A free online book covering JavaScript fundamentals and advanced topics.
https://eloquentjavascript.net/
3. JavaScript.info: A modern guide with interactive tutorials and examples for JavaScript learners.
https://javascript.info/
4. freeCodeCamp JavaScript Tutorials: Free interactive lessons and coding challenges to learn
JavaScript.
https://www.freecodecamp.org/learn/

38
Thanks
for
watching!

39
The Complete Lecture 9:
Javascript Course
Asynchronous
Programming
-Bhavesh Bansal

@newtonschool
1
Table of Contents
● Synchronous Vs Asynchronous Programming
● Asynchronous Programming Fundamentals
● Callbacks: a Deep Dive
● setTimeout and setInterval
● setTimeout working
● Real-world applications
● Error Handling

2
Synchronous vs Asynchronous

3
Synchronous Programming
Synchronous programming means doing things one at a time, in the exact order
they're written.

Start Task 1 Task 2 …. Task 3 End

4
Synchronous Programming
So far, we’ve learned about functions, variable declarations, loops, etc. All these
execute one step at a time, in the order written.

Can you see the output?


Each line executes only
after the previous line
finishes.

5
But do we always do things in order??
Sometimes we do things one after another, but other times we start something,
stop, and switch to something else, i.e., we complete tasks asynchronously.

You might start cooking, but then


remember to check a message
from work. You stop cooking and
check the message first. Did you
follow the order?

6
Need for asynchronous programming
Just like in daily life, where tasks aren't always in order, programming uses
asynchronous tasks to handle unpredictable delays without stopping everything.

Server is
taking too
Code line 1
long
Code line 2

Fetch data from server

Rest of the Code Should I wait for the server


or continue the code?

7
Better to Wait and Keep Things Running
Sometimes it's better to wait for the server response, but instead of pausing
everything, we can continue other tasks while waiting.

The idea is to execute


shorter tasks first and catch
up on longer tasks once
they finish, reducing overall
execution time.

8
What is Async Programming?
Asynchronous programming lets tasks run independently, allowing your program to
continue other tasks while waiting for long operations to finish.

Here, the program


sends a request to the
server and, while
waiting for the
response, continues
accepting and
processing user
inputs.

9
Ways to implement async programming
There are three main ways to implement asynchronous programming in JavaScript:

Async Programing

Callbacks Promises Async/Await

10
11
Callbacks: a Deep Dive

12
Callbacks: Task to Execute Later
In simple terms, a callback is just a function that you give to another function. The
receiving function will then decide when and how to execute.

Here it is up to task1() function


when and where it executes
callback function. Here it is
executing it immediately, but that is
not always the case.

13
Executing callbacks after a while
Let’s add a delay of 2000 milliseconds before the callback executes using setTimeout().

Don’t panic, we will


learn how
setTimeout() works in
the next slides.

14
Callbacks in action: setTimeout
setTimeout is a JavaScript function that executes a callback function after a specified
delay (in milliseconds).

Syntax:

(greet,

Callback function

15
setTimeout: example 1
We can print a specific message after a certain period of time using setTimeout.

Here we get output after 2000


milliseconds, i.e. 2 secs

Output:

Hello

16
setTimeout: example 1
The same example can be rewritten like this using named functions and arrow
functions.

Using named Function Using arrow Function

17
setTimeout: example 2
Here we have implemented a countdown using setTimeout.

Output:

5
4
3
2
1
Time's up!

18
Callbacks in action: setInterval
setInterval is a JavaScript function that repeatedly executes a specified callback
function at fixed time intervals (in milliseconds).

Syntax:

(greet,

19
setInterval: example 1
Here we are printing and updating the message count every 1000 milliseconds. The
setInterval() function returns a unique identifier, known as an interval ID, which is
stored to later clear the interval

Output:

Message 1
Message 2
Message 3
..
..

20
setInterval: example 2
Here we are displaying the most updated time using setInterval. The latest time gets
updated every 1000 milliseconds, i.e. every second

Output:
In JavaScript, the Date
object represents a
12:34:56 PM
specific moment in time.
12:34:57 PM Using the Date()
constructor without
12:34:58 PM arguments creates a new
12:34:59 PM Date object set to the
current date and time.
...

21
Zombie Tasks: Task Queue Congestion
When you have too many async functions running (or scheduled but never cleared),
they can be described as 'zombie callbacks' or 'zombie tasks.' These lingering tasks
consume memory and CPU resources unnecessarily.
So many async functions!!
I can’t handle

……………..
……………..
asyncFn() asyncFn()
asyncFn() asyncFn()
asyncFn() asyncFn() asyncFn()
asyncFn() asyncFn() asyncFn()
Executes what event
loop brings to it

22
Clearing up Zombie Tasks: setTimeout
So it is always a good practice to free up such asynchronous operations that are taking
up system resources

Thank God! Now I feel


relaxed!!

It is always a good idea to release


setTimeout() when it is no longer used
to save up the resources.
23
Clearing up Congestion: setInterval
You should always conditionally clear the interval after use to avoid needless
consumption of resources. Otherwise, it would get repeated infinitely Here is how you
can do it:

Output:

Interval cleared

This argument sets clear time to


10000 milliseconds, i.e. 10 secs
24
Some Real World Examples

25
Quick Reminder System
Imagine you're working on a task and suddenly remember you need to call a friend in
5 minutes. A quick and simple solution can help you set a one-time reminder to pop up
after a specific delay.

It’s time to call my


friend!!!

26
Build a timer using setTimeout
A quick solution lets you set a one-time reminder to alert you after a delay.

Output:

Call your friend in 300 seconds

27
Simple Productivity Timer
You’re working on a project and want to stay focused by tracking your time. To stay
productive, set a timer to remind you every 30 minutes to take a break.

28
Build a reminder using setInterval
An easy solution is to build a recurring reminder using setInterval

Output:

Time for a break! 30 mins

Time for a break! 60 mins

Time for a beak! 90 mins

29
setTimeout
Workshop

30
Workshop: Question 1
You are building a web app that reminds users to save their work every 10 minutes.
Write a function using setTimeout that logs "Please save your work!" after a 10-minute
delay.

What should the function look like?

Reminder
Can you write a code to
implement this reminder??
Save your work; otherwise, progress would
be lost.

31
Workshop: Question 2
In your app, you want to show a message to the user saying "Action timed out!" if they
don’t click a button within 5 seconds. Use setTimeout to implement this timeout
mechanism.

How will you implement this feature using setTimeout?

Alert!

I’m sure you’ll be able to handle


Action timed out!
this one!

32
Error Handling

33
Need for error handling
Imagine building a web app that fetches user data from an API. Network issues, server
downtime, or request failures can lead to errors, and if not handled, the app might
crash or behave unexpectedly.

Why server is not


sending data

Request for data


Meanwhile
server crashed

34
Common Causes of Errors
There are several reasons due to which errors can occur:

Reasons for Errors

Server Incorrect data


Network Issue And many more.
Unavailability format

35
Handling Errors using try/catch block
JavaScript provides the try...catch statement to handle errors gracefully.

Syntax:

36
Dummy Example: try/catch
try/catch for fetching data, but for simplicity we have replaced fetch with Math.random()

Output:

// if response === false

Error: Failed to fetch data!

We used async keyword to make


function asynchronous.

37
Real Example: try/catch
Let’s use proper fetch function to fetch the data from the server

Don’t stress about fetch()


api, we will learn it later

Output:

// if response === false

Error: Failed to fetch data!

38
In Class Questions

39
References
1. MDN Web Docs: JavaScript: Comprehensive and beginner-friendly documentation for JavaScript.
https://developer.mozilla.org/en-US/docs/Web/JavaScript
2. Eloquent JavaScript: A free online book covering JavaScript fundamentals and advanced topics.
https://eloquentjavascript.net/
3. JavaScript.info: A modern guide with interactive tutorials and examples for JavaScript learners.
https://javascript.info/
4. freeCodeCamp JavaScript Tutorials: Free interactive lessons and coding challenges to learn
JavaScript.
https://www.freecodecamp.org/learn/

40
Thanks
for
watching!

41
The Complete Lecture 10:
Javascript Course
Introduction to
Promises
-Bhavesh Bansal

@newtonschool
1
Table of Contents
● Callbacks vs Promise: Need for promise
● Understanding Promises
○ Promises in Javascript
○ Basic Promise Usage
● Creating Promises
○ Promise Constructor
○ Promise Methods: then(), catch() and finally()
● Handling Promise States
resolve reject pending
● Pending ● Pending

○ ○ ○
● Error Handling
2
Why do we need Promises?

3
Pre-discussed: Async Programming
Asynchronous programming lets tasks run independently, allowing your program to
continue other tasks while waiting for long operations to finish.

Here, the program


sends a request to the
server and, while
waiting for the
response, continues
accepting and
processing user
inputs.

4
Pre-discussed: Ways to implement
There are three main ways to implement asynchronous programming in JavaScript:

Async Programing

Callbacks Promises Async/Await

5
Pre-discussed: Callbacks
In simple terms, a callback is just a function that you give to another function. The
receiving function will then decide when and how to execute.

Here it is upto task1() function


when and where it executes
callback function. Here it is
executing it immediately but that
is not always the case.

6
Pre-discussed: Callbacks
Let’s add a delay of 2000 milliseconds before callback executes using setTimeout().

Here we are adding a delay


inside task1 function using
setTimeout().

7
Callbacks: Don’t make function async
Callbacks don’t make functions asynchronous!

Output:
Hello, Alice
Goodbye!

Here, sayGoodbye() executes


immediately after console.log().
There's nothing asynchronous
happening.

8
Callbacks: Handle async operations
Let’s have a look at end to end comparison of performing async operations without
and with callbacks.

Can you tell why??

Why?

9
Callbacks: Handle async operations
Here fetch() does return a value, but since we are not using callbacks, we can’t add a
task which only needs to happens after fetch operations completes.

We expect to get a
value immediately after
calling getUserData(),
but since fetch() is
asynchronous, the data
isn’t available yet, so
we get undefined.

10
Callbacks: Handle async operations
Instead we need to pass a function to which gets invoked only after fetch() completes
its execution. And that function is called Callback Function.

Callback function got received

Callback function gets invoked


only when fetch operation
completes

Passing the callback function


to getUserData() function

11
Challenge with Callbacks
Callbacks facilitate asynchronous operations, but when multiple operations need to be
performed sequentially, they can lead to callback hell.

Callback hell makes


code hard to debug
and update, leading to
poor scalability.

12
Promises: a more structured way
Promises are built on callbacks, but they offer a more structured and manageable
way to handle asynchronous operations compared to using callbacks directly.

.then()
A Promise essentially wraps Callbacks
an asynchronous operation chained with
and provides two callback promise
.catch()

13
Understanding the Promises

14
Have you ever made a promise?
If you did, then you must know how valuable promises are. A promise in real life is
a commitment or guarantee made by someone.

Sadly, few promises


remain unfulfilled.

15
Stages of promise
If you did, then you must know how valuable promises are. A promise in real life is
a commitment or guarantee made by someone.

16
Promises in Javascript
A promise is a commitment in programming—a guarantee that something will
happen in the future but not an immediate action. It’s a placeholder for future work.

Promise Fulfilled
Pending
State
After specific
period of time

Promise
Rejected

17
Different promise states
Promises in Javascript exist in three states: pending, fulfilled, and rejected.

Initially, a promise remains in a


pending state, and after some
time it either gets
resolved/fulfilled or rejected.

18
Creating Promises

19
Promise: constructing a promise
To create a promise in JavaScript, you use the Promise constructor. The promise
constructor receives two functions as arguments: resolve() and reject()

The resolve function is called when


the promise is successfully
fulfilled.

The reject function is called when


the promise is rejected.

20
Promise: Using Promise Constructor
To create a promise in JavaScript, you use the Promise constructor. The promise
constructor receives two functions as arguments: resolve() and reject()

Received resolve and


reject functions as
arguments

21
Promise: resolve()
The resolve method in JavaScript is a static method of the Promise object. It is used
to create a promise that is resolved with a given value.

resolve() function’s
work is to finish the
task and provide a
return value.
Resolved the task and provided
the work data as return value

Fail/rejected reject() function’s


Promised to complete the task and return
in meeting fail/error
work is to return an
message appropriate error
message
22
Promise: resolve()
Let’s have a look at a dummy example:

On successful
resolution of
promise, resolve()
returns a value.
For simplicity, we
are returning a
success message.

23
Promise: reject()
It might be possible that a promise can’t be delivered and you need to provide an
explanation and, in JavaScript, an error message.

resolve() function
work is to finish the
task and provide a
return value.
Resolved the task and provide
the work data as return value

reject() function work


Fail/rejected is to return an
Promised to complete the task and return
in meeting appropriate error
fail/error
message
message

24
Promise: reject()
Let’s have a look at a dummy example:

On failure to
resolve a promise
reject() returns an
error message.
For simplicity we
are returning a
failure message..

25
Promise: pending()
Before either promise gets resolved or rejected, there is some wait period. This
wait period is called pending state of promise

Pending State

Resolved the task and provided


Wait the work data as return value
Period

Fail/rejected
Promised to complete the task and return
in meeting fail/error
message

26
Promise Creation: Example 1
Let’s understand promises with a simple example:

Using resolve() to
fulfill the promise

Using reject() to
reject the promise

27
Promise Creation: Example 2
Let’s take a more practical example:

Success Or Failure

resolve reject

28
Handling the Promise

29
Promises: Handling Promise Outcomes
As we have learned, a promise is initially in a pending state, and then after a while it
either gets resolved or rejected.

ture
cap e
ed valu
What to do with olv
Res
resolved and
rejected outcomes
Han
dle
Erro
r

30
Promises: Bridging Hope and Reality
We hope a promise resolves/fulfilled and gives us a value to work with in the “then”
block. However, if it gets rejected, we handle it in the “catch” block.

We can add
We capture finally at the end
resolved value (optional)
using .then()
block

.finally()

Or else we
handle error
Finally runs, regardless of
inside .catch()
the promise's result.
block

31
Promise: Using the .then() block
The .then() block handles data after resolution in a promise chain by capturing it and
allowing further processing.

Promise returns the value

We can use the returned


value from Promise inside
.then() block

32
.then(): Example
The .then() block is used to handle the successful resolution of a promise, capturing
the returned value and allowing further processing or actions.

Here we are using .then() block to


capture the resolved value

33
Promise: Using .catch() block
The .catch() block handles errors or rejections in a promise chain, ensuring that any
issues during the operation are caught and managed gracefully.

.catch() is indeed added


after the last .then() block in
most cases to handle any
errors that occur while
consuming the promise.

34
.catch(): Example
It might be possible that error occurred while consuming the promise which can be
caught using the .catch() block.

Here we are capturing


error while consuming
the promise.

35
Promise: Using .finally() block
It is possible to chain a block that runs regardless of whether the promise is resolved
or rejected using .finally() block.

36
.finally(): Example
It is possible to chain a block that runs regardless of whether the promise is resolved
or rejected using .finally() block.

finally() block

37
Why do we need Promises??
In the previous lecture we learned that callbacks can be used to implement async
programming; then why do we need to make promises?

Seems
Cluttered
Callback

I can perform
async
operations

38
Why do we need Promises??
Callbacks can often lead to cluttered and unreliable code due to nested functions. It is
better to chain tasks, where one task starts after the previous one ends, and this is
achieved using promises.

39
Callbacks vs Promises vs Async/await
We use callbacks for simple asynchronous tasks, promises for chaining more complex
tasks, and async/await for writing asynchronous code that appears sequential.
Promise Basic Usages

41
Basic Promise Usage
Promises in JavaScript simplify handling asynchronous operations. Here are
common use cases:

Usages

Setting up
Fetching Data Reading Files Many More..
Timers

● setTimeout()
We will learn it later in detail,
● setInterval()
here we will have brief overview.

42
Usage: Fetching Data
We use fetch api to get data from the server.

Fetching data from server is an


async operation so we used
promise for it.

Here we conditionally
rejected/resolved the
promise

43
setTimeout and setInterval

with Promises

44
Pre-discussed: setTimeout
setTimeout is a JavaScript function that executes a callback function after a specified
delay (in milliseconds).

Syntax:

(greet,

Callback function

45
Pre-discussed: setTimeout Example
We can print specific message after a certain period of time using setTimeout.

Here we get output after 2000


milliseconds i.e. 2 secs

Output:

Hello

46
setTimeout wrapped in a Promise
There might be instances where you need to set up timers in JavaScript. In such cases,
you can use setTimeout in combination with promises

Creating and returning a


promise

Calling the function


returning the promise and
consuming the returned
promise

47
Pre-discussed: setInterval
setInterval is a JavaScript function that repeatedly executes a specified callback
function at fixed time intervals (in milliseconds).

Syntax:

(greet,

48
Pre-discussed: setInterval example
Here we are printing and updating message count every 1000 milliseconds. The
setInterval() function returns a unique identifier, known as an interval ID, which is
stored to later clear the interval

Output:

Message 1
Message 2
Message 3
..
..

49
Usage: Setting up timers (SetInterval)
In similar fashion you can use setInterval if you want a task to be repeated after
certain interval of time.

Creating and returning a


promise

Calling the function


returning the promise.

50
Understanding Asynchronous
flow in Promises

51
What is Asynchronous Flow?
Asynchronous flow allows programs to perform tasks concurrently without blocking
other tasks. It enables operations such as fetching data, reading files, or waiting for
user input without freezing the program.

Unlike sync operations


async operations do not
need to wait till the other
task complete its
execution.

52
Asynchronous Flow in Promises
In promises we chain the tasks using then() and catch() blocks. Hence program is
executed in chain like manner.

Corresponding block executes


only after the execution of block
previous block.

53
Workshop: Question
You're building a registration form where users submit their name, email, and age. The
input data needs to be validated asynchronously, such as if name is valid, checking if
the email is already registered (with a delay) and ensuring the age is valid.

How would you implement using promises?


Can you
validate data?

Name

Email

Age

54
Workshop: Solution
Let’s write a function using promises for validating name asynchronously.

Write functions to
validate email and age
by yourself.

55
Workshop: Solution
Let’s write validation functions for email and age too.

Validating Email Validating Age

56
In Class Questions

57
References
1. MDN Web Docs - JavaScript: Comprehensive and beginner-friendly documentation for
JavaScript.
https://developer.mozilla.org/en-US/docs/Web/JavaScript
2. Eloquent JavaScript: A free online book covering JavaScript fundamentals and advanced topics.
https://eloquentjavascript.net/
3. JavaScript.info: A modern guide with interactive tutorials and examples for JavaScript learners.
https://javascript.info/
4. freeCodeCamp JavaScript Tutorials: Free interactive lessons and coding challenges to learn
JavaScript.
https://www.freecodecamp.org/learn/

58
Thanks
for
watching!

59
The Complete Lecture 10:
Javascript Course
Introduction to
Promises
-Bhavesh Bansal

@newtonschool
1
Table of Contents
● Callbacks vs Promise: Need for promise
● Understanding Promises
○ Promises in Javascript
○ Basic Promise Usage
● Creating Promises
○ Promise Constructor
○ Promise Methods: then(), catch() and finally()
● Handling Promise States
resolve reject pending
● Pending ● Pending

○ ○ ○
● Error Handling
2
Why do we need Promises?

3
Pre-discussed: Async Programming
Asynchronous programming lets tasks run independently, allowing your program to
continue other tasks while waiting for long operations to finish.

Here, the program


sends a request to the
server and, while
waiting for the
response, continues
accepting and
processing user
inputs.

4
Pre-discussed: Ways to implement
There are three main ways to implement asynchronous programming in JavaScript:

Async Programing

Callbacks Promises Async/Await

5
Pre-discussed: Callbacks
In simple terms, a callback is just a function that you give to another function. The
receiving function will then decide when and how to execute.

Here it is upto task1() function


when and where it executes
callback function. Here it is
executing it immediately but that
is not always the case.

6
Pre-discussed: Callbacks
Let’s add a delay of 2000 milliseconds before callback executes using setTimeout().

Here we are adding a delay


inside task1 function using
setTimeout().

7
Callbacks: Don’t make function async
Callbacks don’t make functions asynchronous!

Output:
Hello, Alice
Goodbye!

Here, sayGoodbye() executes


immediately after console.log().
There's nothing asynchronous
happening.

8
Callbacks: Handle async operations
Let’s have a look at end to end comparison of performing async operations without
and with callbacks.

Can you tell why??

Why?

9
Callbacks: Handle async operations
Here fetch() does return a value, but since we are not using callbacks, we can’t add a
task which only needs to happens after fetch operations completes.

We expect to get a
value immediately after
calling getUserData(),
but since fetch() is
asynchronous, the data
isn’t available yet, so
we get undefined.

10
Callbacks: Handle async operations
Instead we need to pass a function to which gets invoked only after fetch() completes
its execution. And that function is called Callback Function.

Callback function got received

Callback function gets invoked


only when fetch operation
completes

Passing the callback function


to getUserData() function

11
Challenge with Callbacks
Callbacks facilitate asynchronous operations, but when multiple operations need to be
performed sequentially, they can lead to callback hell.

Callback hell makes


code hard to debug
and update, leading to
poor scalability.

12
Promises: a more structured way
Promises are built on callbacks, but they offer a more structured and manageable
way to handle asynchronous operations compared to using callbacks directly.

.then()
A Promise essentially wraps Callbacks
an asynchronous operation chained with
and provides two callback promise
.catch()

13
Understanding the Promises

14
Have you ever made a promise?
If you did, then you must know how valuable promises are. A promise in real life is
a commitment or guarantee made by someone.

Sadly, few promises


remain unfulfilled.

15
Stages of promise
If you did, then you must know how valuable promises are. A promise in real life is
a commitment or guarantee made by someone.

16
Promises in Javascript
A promise is a commitment in programming—a guarantee that something will
happen in the future but not an immediate action. It’s a placeholder for future work.

Promise Fulfilled
Pending
State
After specific
period of time

Promise
Rejected

17
Different promise states
Promises in Javascript exist in three states: pending, fulfilled, and rejected.

Initially, a promise remains in a


pending state, and after some
time it either gets
resolved/fulfilled or rejected.

18
Creating Promises

19
Promise: constructing a promise
To create a promise in JavaScript, you use the Promise constructor. The promise
constructor receives two functions as arguments: resolve() and reject()

The resolve function is called when


the promise is successfully
fulfilled.

The reject function is called when


the promise is rejected.

20
Promise: Using Promise Constructor
To create a promise in JavaScript, you use the Promise constructor. The promise
constructor receives two functions as arguments: resolve() and reject()

Received resolve and


reject functions as
arguments

21
Promise: resolve()
The resolve method in JavaScript is a static method of the Promise object. It is used
to create a promise that is resolved with a given value.

resolve() function’s
work is to finish the
task and provide a
return value.
Resolved the task and provided
the work data as return value

Fail/rejected reject() function’s


Promised to complete the task and return
in meeting fail/error
work is to return an
message appropriate error
message
22
Promise: resolve()
Let’s have a look at a dummy example:

On successful
resolution of
promise, resolve()
returns a value.
For simplicity, we
are returning a
success message.

23
Promise: reject()
It might be possible that a promise can’t be delivered and you need to provide an
explanation and, in JavaScript, an error message.

resolve() function
work is to finish the
task and provide a
return value.
Resolved the task and provide
the work data as return value

reject() function work


Fail/rejected is to return an
Promised to complete the task and return
in meeting appropriate error
fail/error
message
message

24
Promise: reject()
Let’s have a look at a dummy example:

On failure to
resolve a promise
reject() returns an
error message.
For simplicity we
are returning a
failure message..

25
Promise: pending()
Before either promise gets resolved or rejected, there is some wait period. This
wait period is called pending state of promise

Pending State

Resolved the task and provided


Wait the work data as return value
Period

Fail/rejected
Promised to complete the task and return
in meeting fail/error
message

26
Promise Creation: Example 1
Let’s understand promises with a simple example:

Using resolve() to
fulfill the promise

Using reject() to
reject the promise

27
Promise Creation: Example 2
Let’s take a more practical example:

Success Or Failure

resolve reject

28
Handling the Promise

29
Promises: Handling Promise Outcomes
As we have learned, a promise is initially in a pending state, and then after a while it
either gets resolved or rejected.

ture
cap e
ed valu
What to do with olv
Res
resolved and
rejected outcomes
Han
dle
Erro
r

30
Promises: Bridging Hope and Reality
We hope a promise resolves/fulfilled and gives us a value to work with in the “then”
block. However, if it gets rejected, we handle it in the “catch” block.

We can add
We capture finally at the end
resolved value (optional)
using .then()
block

.finally()

Or else we
handle error
Finally runs, regardless of
inside .catch()
the promise's result.
block

31
Promise: Using the .then() block
The .then() block handles data after resolution in a promise chain by capturing it and
allowing further processing.

Promise returns the value

We can use the returned


value from Promise inside
.then() block

32
.then(): Example
The .then() block is used to handle the successful resolution of a promise, capturing
the returned value and allowing further processing or actions.

Here we are using .then() block to


capture the resolved value

33
Promise: Using .catch() block
The .catch() block handles errors or rejections in a promise chain, ensuring that any
issues during the operation are caught and managed gracefully.

.catch() is indeed added


after the last .then() block in
most cases to handle any
errors that occur while
consuming the promise.

34
.catch(): Example
It might be possible that error occurred while consuming the promise which can be
caught using the .catch() block.

Here we are capturing


error while consuming
the promise.

35
Promise: Using .finally() block
It is possible to chain a block that runs regardless of whether the promise is resolved
or rejected using .finally() block.

36
.finally(): Example
It is possible to chain a block that runs regardless of whether the promise is resolved
or rejected using .finally() block.

finally() block

37
Why do we need Promises??
In the previous lecture we learned that callbacks can be used to implement async
programming; then why do we need to make promises?

Seems
Cluttered
Callback

I can perform
async
operations

38
Why do we need Promises??
Callbacks can often lead to cluttered and unreliable code due to nested functions. It is
better to chain tasks, where one task starts after the previous one ends, and this is
achieved using promises.

39
Callbacks vs Promises vs Async/await
We use callbacks for simple asynchronous tasks, promises for chaining more complex
tasks, and async/await for writing asynchronous code that appears sequential.
Promise Basic Usages

41
Basic Promise Usage
Promises in JavaScript simplify handling asynchronous operations. Here are
common use cases:

Usages

Setting up
Fetching Data Reading Files Many More..
Timers

● setTimeout()
We will learn it later in detail,
● setInterval()
here we will have brief overview.

42
Usage: Fetching Data
We use fetch api to get data from the server.

Fetching data from server is an


async operation so we used
promise for it.

Here we conditionally
rejected/resolved the
promise

43
setTimeout and setInterval

with Promises

44
Pre-discussed: setTimeout
setTimeout is a JavaScript function that executes a callback function after a specified
delay (in milliseconds).

Syntax:

(greet,

Callback function

45
Pre-discussed: setTimeout Example
We can print specific message after a certain period of time using setTimeout.

Here we get output after 2000


milliseconds i.e. 2 secs

Output:

Hello

46
setTimeout wrapped in a Promise
There might be instances where you need to set up timers in JavaScript. In such cases,
you can use setTimeout in combination with promises

Creating and returning a


promise

Calling the function


returning the promise and
consuming the returned
promise

47
Pre-discussed: setInterval
setInterval is a JavaScript function that repeatedly executes a specified callback
function at fixed time intervals (in milliseconds).

Syntax:

(greet,

48
Pre-discussed: setInterval example
Here we are printing and updating message count every 1000 milliseconds. The
setInterval() function returns a unique identifier, known as an interval ID, which is
stored to later clear the interval

Output:

Message 1
Message 2
Message 3
..
..

49
Usage: Setting up timers (SetInterval)
In similar fashion you can use setInterval if you want a task to be repeated after
certain interval of time.

Creating and returning a


promise

Calling the function


returning the promise.

50
Understanding Asynchronous
flow in Promises

51
What is Asynchronous Flow?
Asynchronous flow allows programs to perform tasks concurrently without blocking
other tasks. It enables operations such as fetching data, reading files, or waiting for
user input without freezing the program.

Unlike sync operations


async operations do not
need to wait till the other
task complete its
execution.

52
Asynchronous Flow in Promises
In promises we chain the tasks using then() and catch() blocks. Hence program is
executed in chain like manner.

Corresponding block executes


only after the execution of block
previous block.

53
Workshop: Question
You're building a registration form where users submit their name, email, and age. The
input data needs to be validated asynchronously, such as if name is valid, checking if
the email is already registered (with a delay) and ensuring the age is valid.

How would you implement using promises?


Can you
validate data?

Name

Email

Age

54
Workshop: Solution
Let’s write a function using promises for validating name asynchronously.

Write functions to
validate email and age
by yourself.

55
Workshop: Solution
Let’s write validation functions for email and age too.

Validating Email Validating Age

56
In Class Questions

57
References
1. MDN Web Docs - JavaScript: Comprehensive and beginner-friendly documentation for
JavaScript.
https://developer.mozilla.org/en-US/docs/Web/JavaScript
2. Eloquent JavaScript: A free online book covering JavaScript fundamentals and advanced topics.
https://eloquentjavascript.net/
3. JavaScript.info: A modern guide with interactive tutorials and examples for JavaScript learners.
https://javascript.info/
4. freeCodeCamp JavaScript Tutorials: Free interactive lessons and coding challenges to learn
JavaScript.
https://www.freecodecamp.org/learn/

58
Thanks
for
watching!

59
The Complete Lecture 11:
Javascript Course
Understanding
APIs
-Narendra Kumar

@newtonschool
1
Table of Contents
● Quick Recap
● Understanding APIs
● Rest API: Understanding with fetch()
● Error Handling
○ Basic Error Catching
○ Multiple Error Handlers
○ Recovery Patterns
● Promise: Static Methods
● Status Codes

2
Quick Recap

3
Pre-discussed: Making a Promise
If you did then you must know how valuable promises are. A promise in real life is
a commitment or guarantee made by someone.

Sadly, few promises


remain unfulfilled.

4
Pre-discussed: Stages of promise
If you did then you must know how valuable promises are. A promise in real life is
a commitment or guarantee made by someone.

5
Pre-discussed: Promises in Javascript
A promise is a commitment in programming—a guarantee that something will
happen in the future, but not an immediate action. It’s a placeholder for future work.

Promise Fulfilled
Pending
State
After specific
period of time

Promise
Rejected

6
Pre-discussed: Different promise states
Promises in javascript exists in three states namingly, pending, fulfilled, and rejected.

Initially promise remains in


pending state, and after
sometime it either gets
resolved/fulfilled or rejected.

7
Pre-discussed: Handling Promise
As we have learned that promise is initially at pending state and then after a while it
either get resolved or rejected.

ture
cap e
ed valu
What to do with olv
Res
resolve and
rejected outcomes
Han
dle
Erro
r

8
Pre-discussed: Handling Promise
We hope a promise resolves/fulfilled and gives us a value to work with in the then
block. However, if it gets rejected, we handle it in the catch block.

We can add
We capture finally at the
resolved value end(optional)
using .then()
block

.finally()

Or else we
handle error
Finally runs, regardless of
inside .catch()
the promise's result.
block

9
Promises in APIs
Applications often fetch external data using APIs. Since APIs return data
asynchronously, they often return Promises.

We can handle
it using then /
catch
Many a time
We use return
For many server
APIs
related tasks
promise

10
But What they are exactly?
Before we jump into how to handle promises returned by APIs lets understand what
they are.

They seems to be some


kind of interface, a kind
of gateway to other
places.

11
Understanding APIs

12
What is an API?
API stands for Application Programming Interface. An API is like a messenger that
connects two different apps or programs talk to each other.

Understood??

Let’s
understand it
with an analogy

13
Let’s understand it with an analogy
In this analogy, the waiter is like an API—taking the guest's order (request) to the chef
(server) and bringing back the dish (response),

The waiter is the entry


point for
communication with
the chef, just like an
API connects different
software systems.

14
API: Bridge Between User and Server
Just like waiter in previous analogy, API stands in between end user and server,
facilitating communication.

15
But Why Not Communicate Directly?
Software often uses different languages and environments, making direct
communication difficult. APIs bridge that gap, allowing apps to understand each other.

Services like MongoDB and


software like ChatGPT provide APIs
API that allow different languages to
communicate efficiently.

Python

16
Popular Examples of APIs in Action
Let’s have a look at few popular apis:-
Firebase API

Remember how
often we used the
Fetch API in
previous lectures

17
API Endpoints: How to Access APIs?
An API endpoint is a specific URL using which an API can be accessed by a client
application.
API Endpoint

18
Types of APIs
There are different types of APIs. Here are few of them:-

API Types

Rest APIs GraphQL Many more...

19
Rest API
Understanding with fetch()

20
Rest API
A REST API allows apps to communicate over the internet using simple commands like
GET, POST, PUT, and DELETE. Each request is independent and doesn't remember the
previous one.

Rest API

We provide them simple http


request like GET, POST etc, and we
get data in response.

21
Rest API: fetch api example
The fetch() API returns a promise that resolves to a response. .then() handles and
parses the data, while .catch() handles errors.

.then() .then()
Fetch api returns a Response data is Transformed data is
response object transformed into json consumed

Any error occurred is


captured in .catch()

.catch()
22
fetch API: then/catch
The fetch() API returns a promise that resolves to a response. .then() handles and
parses the data, while .catch() handles errors.
If resolves returns
response data else throws
an error

Response data is
transformed to json object

Transformed data is
consumed

If any error then gets


caught in .catch()
23
Settling fetch API: then/catch
Any promise gets settled if it either gets resolved or gets rejected.

Either returns a
response data or
throws an error

Based on results i.e.


response or error, it
gets passed either to
.then() or .catch()

24
fetch API: then/catch chaining
Here fetch api returns a promise, when promise gets resolved it returns a response
object which is received by the first then block and values gets passed down in the
chain.

.then() chaining,
values returned
from previous
gets captured in
next .then()

25
fetch: then/catch Data transformation
The received data from the fetch is in form of string which needs to be transformed
into a json object for further processing.

Response data is
transformed into json
object

26
fetch: then/catch Data transformation
The received data from the fetch is in form of string which needs to be transformed
into a json object for further processing.

Transformed response
data returned by .then()
gets received by next
.then() in the chain

27
fetch: then/catch Catching the Error
Error occurred whether due to server or error thrown from anywhere inside our code
gets caught in the .catch().

Error thrown from


inside our code

Error get captured in


.catch()
28
then/catch
Workshop

29
Workshop: Question 1
You are building a simple weather application that fetches data from a weather API. If
the fetch operation fails, you want to display an error message to the user. How would
you structure the promise to handle this error?

How you would handle error using catch()?

30
Workshop: Question 2
You need to fetch user data from an API and then fetch their favorite products from
another API.

How would you chain these two promises and handle any error that may occur
in either of the steps?

31
fetch API: HTTP methods
Fetch APIs use standard HTTP methods to perform actions on resources. Each method
has a specific purpose and meaning.

32
fetch() - GET method
Let’s understand REST API with an example of fetch api. If we don’t specify anything in
fetch then it does GET request by default. GET request retrieves a resource from the
server.

URL for the GET request It would retrieve data


from the API endpoint.

The response is typically


in JSON format, and we
can process it using
.json().

33
fetch() - POST method
If we want to send some data instead of requesting we can do a post request with
appropriate data specifying what data is being sent in the body.

To send data we do POST request

Specifying data format is JSON

In the body, we convert the JSON


data to a string so it can be sent over
the network.

34
fetch() - PATCH method
PATCH request updates a resource or data stored in the server.
We need to pass an
identifier to identify
which item to path
in database

And need to supply


the value to update.

35
fetch() - PUT method
Similarly we can perform PUT request:-

Instead of updating the


resource, PUT request
replaces the entire resource.

This new data would replace


the data entry with identifier 1

36
fetch() - DELETE method
In the same manner as that of PATCH we can perform deletion.

Unlike PATCH we
don’t need to
pass body in
DELETE request.

37
GraphQL API: Querying the database
GraphQL is a query language for APIs that lets clients request exactly the data they
need, reducing over-fetching or under-fetching of data.

38
GraphQL API
Let’s have a look at an example:-

The server stores the entire dataset,


but you only need “name” and “email”.

Unlike other APIs that overfetch by


retrieving entire data units, GraphQL
lets you fetch exactly what you need,
avoiding unnecessary data.

39
GraphQL API: Sending Request Query
Instead of fetching everything, you can query only what you need:

Query you perform Result you get

40
GraphQL API: Sending Request Query
Instead of fetching everything, you can query only what you need:

Query you perform Result you get

41
Error Handling

42
Error Handling: Catch block
The .catch() block is used to handle any errors that occur during the execution of a
promise or any promise chain. It catches both rejections and exceptions that occur in the
promise lifecycle.

Value
resolved returned
Promise .then() .then() .catch()
…..

Error Error Error

43
Handling Errors
There are following types of errors which can be thrown during the execution of a
promise/promise handling.
Errors

Promise Delays or Synchronous


Rejection Timeouts Others
Errors

Errors from explicit Errors caused by Errors in .then() or


promise rejections or network timeouts or .catch() due to
failed network delays in
invalid operations or
requests asynchronous
operations. data.

44
Promise Rejection
Promise rejection errors occur when a promise is explicitly rejected or if an operation
inside the promise fails.

A promise can be manually rejected


using reject(), or due to
network/HTTP failures like 404 or 500
errors, especially in API requests.

45
Promise Rejection: Manual rejection
Promise rejection errors occur when a promise is explicitly rejected or if an operation
inside the promise fails.

Here we simply caught error


and displayed using
console.error()

46
Promise Rejection: Network Http failures
For network or HTTP failures, check the response status and handle errors using
.catch() or inside the fetch() response block.

It might happened that you


got a response but it is a
failed response, in that case
you need to throw an error
from inside .then()

47
Delays or Timeouts
To handle timeouts, create a timeout promise and reject if the operation exceeds the
allowed time.

Most asynchronous
APIs, especially network
requests like HTTP fetch
calls, do have a built-in
timeout to prevent the
request from hanging
indefinitely

48
Synchronous Errors
Synchronous errors like invalid input/data, type errors etc, could occur for which we
need to throw an error manually while creating the promise.

Invalid data

49
Handling Errors at different stages
We can add error handlers at different points to manage errors at each stage.

Generally we place multiple


.catch() to handle specific
type of error at different
places

Throws an error only if comment fetching fails.

Handles errors anywhere in the code.


50
Recovering from errors
Recovering from Errors refers to the process of handling errors in a way that allows
the program to continue running or perform a fallback action instead of crashing.

Let’s say that fetch operation


failed to retrieve data from
the server, in that case we
can provide some fallback
data.

51
Recovering from errors
Or we can retry by sending one more fetch request to the server:-

Here, we are recursively


calling fetchWithRetry(),
in case network error occurs
along with limiting the
number of retries.

52
Recovering from errors
Or else we can graceful show minimal or different content

Or we can simply state


“Difficulty in fetching data, try
again later”.

53
Promise: Static Methods

54
Promise: What are Static methods?
Static methods of the Promise class are called on the Promise constructor to manage
multiple promises or handle resolution globally.

Static Methods

Promise.all() Promise.race() Many more...

55
Static Method: Promise.all()
Promise.all() is a static method that takes an array of promises and returns a single
promise. It resolves when all promises resolve or rejects as soon as any promise
rejects.

If all Promises
Resolved got resolved

If one or more
Rejected remained
unresolved

56
Promise.all(): Example
Promise.all() is a static method that takes an array of promises and returns a single
promise. It resolves when all promises resolve or rejects as soon as any promise
rejects.

Here we have three promises which


returns 10, 20 and 30 respectively as
resolved value

Since all of them are getting resolved,


Promise.all() will return an array of
values

57
Promise.all(): Example
Let’s say one of the promise is not getting resolved.

This promise is being rejected

So instead an error would be


thrown

And error gets captured by


catch block

58
Static Method: Promise.race()
Promise.race() is a static method that takes an array of promises and returns a single
promise, which resolves or rejects as soon as one of the promises settles.

Since the first promise in


Promise.race is settled with
state resolve, Promise.race
will be resolved.

59
Static Method: Promise.race()
Let’s say first settled promise gets rejected, Promise.race() would also be settled as
rejected.

Since the first promise in


Promise.race is settled with
state reject, Promise.race will
be rejected.

Promise.race() rejected here

60
Promise.all(): Example
We are fetching data from a URL and setting a timeout. If the timeout occurs before
the data is fetched, Promise.race() will reject; otherwise, it will resolve with the data.

If data is fetched before


3000 milliseconds then
promise would be
resolved else it would
be rejected.

61
Promise.all()
Workshop

62
Workshop: Question
You had a form where users submit their name, email, and age. You have validated it,
now you need to consume the promises and process the data only if all validations
pass. If any validation fails, an error message should be displayed to the user.

How can you consume the promise?


Consume it
using
then/catch
Name

Consume the Email


Promise
Age

63
Workshop: Solution
Let’s consume the promise:-

Here we used Promise.all() to consume all


the promises at once.

64
Status Codes
Signalling between Client and Server

65
Status Codes: Signaling Success and Failure
When a request is processed, the server signals the outcome (success or failure) using
status codes, providing clear communication about the operation's result.

{
Data,
Status code,
Message
}
Status Code: Retrieving Status Code
When you make a fetch request, it returns a response with a status code. You can
access the status code using response.status to check the outcome of the request.

Here we are capturing status code

We can use some other variable


let say data, then we get status
code using:-

data.status
Status Code: Success
Success status codes (200-299) indicate that the request was successfully processed by
the server.

Success

203:
200: OK 201: Created 202: Accepted Non-Authoritative 204: No content
Information
Status Codes: Client Error
Client error status codes (400-499) indicate that the request was invalid or cannot be
processed due to issues on the client side.

Client Error

400: Bad 401:


Request 403: Forbidden 404: Not Found 409: Conflict
Unauthorized
Status Codes: Server Error
Client error status codes (400-499) indicate that the request was invalid or cannot be
processed due to issues on the client side.

Server Error

500: Internal 501: Not 502: Bad 503: Service 504: Gateway
Server Error Implemented Gateway Unavailable Timeout
In Class Questions

71
References
1. MDN Web Docs - JavaScript: Comprehensive and beginner-friendly documentation for
JavaScript.
https://developer.mozilla.org/en-US/docs/Web/JavaScript
2. Eloquent JavaScript: A free online book covering JavaScript fundamentals and advanced topics.
https://eloquentjavascript.net/
3. JavaScript.info: A modern guide with interactive tutorials and examples for JavaScript learners.
https://javascript.info/
4. freeCodeCamp JavaScript Tutorials: Free interactive lessons and coding challenges to learn
JavaScript.
https://www.freecodecamp.org/learn/

72
Thanks
for
watching!

73
The Complete Lecture 11:
Javascript Course
Understanding
APIs
-Narendra Kumar

@newtonschool
1
Table of Contents
● Quick Recap
● Understanding APIs
● HTTPS REST API: Understanding with fetch()
● Error Handling
○ Basic Error Catching
○ Multiple Error Handlers
○ Recovery Patterns
● Promise: Static Methods
● Status Codes

2
Quick Recap

3
Pre-discussed: Making a Promise
If you did, then you must know how valuable promises are. A promise in real life is
a commitment or guarantee made by someone.

Sadly, few promises


remain unfulfilled.

4
Pre-discussed: Stages of promise
If you did then you must know how valuable promises are. A promise in real life is
a commitment or guarantee made by someone.

5
Pre-discussed: Promises in Javascript
A promise is a commitment in programming—a guarantee that something will
happen in the future, but not an immediate action. It’s a placeholder for future work.

Promise Fulfilled
Pending
State
After specific
period of time

Promise
Rejected

6
Pre-discussed: Different promise states
Promises in JavaScript exist in three states: pending, fulfilled, and rejected.

Initially, a promise remains in a


pending state, and after some
time it either gets
resolved/fulfilled or rejected.

7
Pre-discussed: Handling Promise
As we have learned, a promise is initially in a pending state, and then after a while it
either gets resolved or rejected.

ture
cap e
ed valu
What to do with olv
Res
resolve and
rejected outcomes
Han
dle
Erro
r

8
Pre-discussed: Handling Promise
We hope a promise resolves/fulfilled and gives us a value to work with in the then
block. However, if it gets rejected, we handle it in the catch block.

We can add
We capture finally at the end
resolved value (optional)
using .then()
block

.finally()

Or else we
handle errors
Finally runs, regardless of
inside .catch()
the promise's result.
block

9
Promises in APIs
Applications often fetch external data using APIs. Since APIs return data
asynchronously, they often return Promises.

We can handle
it using then /
catch
Many a time
For many We use return
server-related APIs
tasks
promise

10
But what are they exactly?
Before we jump into how to handle promises returned by APIs, let's understand what
they are.

They seem to be some


kind of interface, a kind
of gateway to other
places.

11
Understanding APIs

12
What is an API?
API stands for Application Programming Interface. An API is like a messenger that
connects two different apps or programs to talk to each other.

Understood??

Let’s
understand it
with an analogy

13
Let’s understand it with an analogy
In this analogy, the waiter is like an API—taking the guest's order (request) to the chef
(server) and bringing back the dish (response),

The waiter is the entry


point for
communication with
the chef, just like an
API connects different
software systems.

14
API: Bridge Between User and Server
Just like waiter in the previous analogy, API stands in between end user and server,
facilitating communication.

15
But why not communicate directly?
Software often uses different languages and environments, making direct
communication difficult. APIs bridge that gap, allowing apps to understand each other.

Services like MongoDB and


software like ChatGPT provide APIs
API that allow different languages to
communicate efficiently.

Python

16
Popular Examples of APIs in Action
Let’s have a look at few popular APIs:
Firebase API

17
API Endpoints: How to Access APIs?
An API endpoint is a specific URL using which an API can be accessed by a client
application.
API Endpoint

18
Types of APIs
There are different types of APIs. Here are few of them:

API Types

HTTP APIs Many more...

IPC API Browser API

19
HTTP REST API
Understanding with fetch()

20
Rest API
A REST API allows apps to communicate over the internet using simple commands like
GET, POST, PUT, and DELETE. Each request is independent and doesn't remember the
previous one.

We provide them with simple HTTP


requests like GET, POST, etc., and we
get data in response.

21
Rest API: fetch api example
The fetch() API returns a promise that resolves to a response. .then() handles and
parses the data, while .catch() handles errors.

.then() .then()
Fetch API returns a Response data is Transformed data is
response object transformed into json consumed

Any error that


occurred is captured
in .catch()

.catch()
22
fetch API: then/catch
The fetch() API returns a promise that resolves to a response. .then() handles and
parses the data, while .catch() handles errors.
If resolves returns
response data else throws
an error

Response data is
transformed to json object

Transformed data is
consumed

If any error then gets


caught in .catch()
23
Settling fetch API: then/catch
Any promise gets settled if it either gets resolved or gets rejected.

Either returns
response data or
throws an error

Based on results, i.e.


response or error, it
gets passed either to
.then() or .catch()

24
fetch API: then/catch chaining
Here fetch returns a promise; when the promise gets resolved, it returns a response
object, which is received by the first block, and values get passed down in the chain.

.then() chaining,
values returned
from previous
get captured in
next .then()

25
fetch: then/catch Data transformation
The received data from the fetch is in the form of a string, which needs to be
transformed into a JSON object for further processing.

Response data is
transformed into json
object

26
fetch: then/catch Data transformation
The received data from the fetch is in the form of a string, which needs to be
transformed into a JSON object for further processing.

Transformed response
data returned by .then()
gets received by next
.then() in the chain

27
fetch: then/catch Catching the Error
Error occurred whether due to server or error thrown from anywhere inside our code
gets caught in the .catch().

Error thrown from


inside our code

Error get captured in


.catch()
28
then/catch
Workshop

29
Workshop: Question 1
You are building a simple weather application that fetches data from a weather API. If
the fetch operation fails, you want to display an error message to the user. How would
you structure the promise to handle this error?

How would you handle errors using catch()?

30
Workshop: Question 2
You need to fetch user data from an API and then fetch their favorite products from
another API.

How would you chain these two promises and handle any error that may occur
in either of the steps?

31
fetch API: HTTP methods
Fetch APIs use standard HTTP methods to perform actions on resources. Each method
has a specific purpose and meaning.

32
fetch() - GET method
Let’s understand REST API with an example of fetch API. If we don’t specify anything in
fetch, then it does GET request by default. A GET request retrieves a resource from the
server.

URL for the GET request


It retrieves data from the
API endpoint, expecting the
response to be a stream of
bytes convertible to JSON
format which process using
the .json() method.

33
fetch() - POST method
If we want to send some data instead of requesting, we can do a post request with
appropriate data specifying what data is being sent in the body.

To send data, we do POST request

Specifying data format is JSON

In the body, we convert the JSON


data to a string so it can be sent over
the network.

34
fetch() - PATCH method
PATCH request updates a resource or data stored in the server.
We need to pass an
identifier to identify
which item to path
in database

And need to supply


the value to update.

35
fetch() - PUT method
Similarly we can perform PUT request:-

Instead of updating the


resource, PUT request
replaces the entire resource.

This new data would replace


the data entry with identifier 1

36
fetch() - DELETE method
In the same manner as that of PATCH we can perform deletion.

Unlike PATCH we
don’t need to
pass body in
DELETE request.

37
Error Handling

38
Error Handling: Catch block
The .catch() block is used to handle any errors that occur during the execution of a
promise or any promise chain. It catches both rejections and exceptions that occur in the
promise lifecycle.

Value
resolved returned
Promise .then() .then() .catch()
…..

Error Error Error

39
Handling Errors
There are following types of errors which can be thrown during the execution of a
promise/promise handling.
Errors

Promise Delays or Synchronous


Rejection Timeouts Others
Errors

Errors from explicit Errors caused by Errors in .then() or


promise rejections or network timeouts or .catch() due to
failed network delays in
invalid operations or
requests asynchronous
operations. data.

40
Promise Rejection
Promise rejection errors occur when a promise is explicitly rejected or if an operation
inside the promise fails.

A promise can be manually rejected


using reject(), or due to
network/HTTP failures like 404 or 500
errors, especially in API requests.

41
Promise Rejection: Manual rejection
Promise rejection errors occur when a promise is explicitly rejected or if an operation
inside the promise fails.

Here we simply caught error


and displayed using
console.error()

42
Promise Rejection: Network Http failures
For network or HTTP failures, check the response status and handle errors using
.catch() or inside the fetch() response block.

It might happened that you


got a response but it is a
failed response, in that case
you need to throw an error
from inside .then()

43
Delays or Timeouts
To handle timeouts, create a timeout promise and reject if the operation exceeds the
allowed time.

Most asynchronous
APIs, especially network
requests like HTTP fetch
calls, do have a built-in
timeout to prevent the
request from hanging
indefinitely

44
Synchronous Errors
Synchronous errors like invalid input/data, type errors etc, could occur for which we
need to throw an error manually while creating the promise.

Invalid data

45
Handling Errors at different stages
We can add error handlers at different points to manage errors at each stage.

Generally we place multiple


.catch() to handle specific
type of error at different
places

Throws an error only if comment fetching fails.

Handles errors anywhere in the code.


46
Recovering from errors
Recovering from Errors refers to the process of handling errors in a way that allows
the program to continue running or perform a fallback action instead of crashing.

Let’s say that fetch operation


failed to retrieve data from
the server, in that case we
can provide some fallback
data.

47
Recovering from errors
Or we can retry by sending one more fetch request to the server:-

Here, we are recursively


calling fetchWithRetry(),
in case network error occurs
along with limiting the
number of retries.

48
Recovering from errors
Or else we can graceful show minimal or different content

Or we can simply state


“Difficulty in fetching data, try
again later”.

49
Promise: Static Methods

50
Promise: What are Static methods?
Static methods of the Promise class are called on the Promise constructor to manage
multiple promises or handle resolution globally.

Static Methods

Promise.all() Promise.race() Many more...

51
Static Method: Promise.all()
Promise.all() is a static method that takes an array of promises and returns a single
promise. It resolves when all promises resolve or rejects as soon as any promise
rejects.

If all Promises
Resolved got resolved

If one or more
Rejected remained
unresolved

52
Promise.all(): Example
Promise.all() is a static method that takes an array of promises and returns a single
promise. It resolves when all promises resolve or rejects as soon as any promise
rejects.

Here we have three promises which


returns 10, 20 and 30 respectively as
resolved value

Since all of them are getting resolved,


Promise.all() will return an array of
values

53
Promise.all(): Example
Let’s say one of the promise is not getting resolved.

This promise is being rejected

So instead an error would be


thrown

And error gets captured by


catch block

54
Static Method: Promise.race()
Promise.race() is a static method that takes an array of promises and returns a single
promise, which resolves or rejects as soon as one of the promises settles.

Since the first promise in


Promise.race is settled with
state resolve, Promise.race
will be resolved.

55
Static Method: Promise.race()
Let’s say first settled promise gets rejected, Promise.race() would also be settled as
rejected.

Since the first promise in


Promise.race is settled with
state reject, Promise.race will
be rejected.

Promise.race() rejected here

56
Promise.all(): Example
We are fetching data from a URL and setting a timeout. If the timeout occurs before
the data is fetched, Promise.race() will reject; otherwise, it will resolve with the data.

If data is fetched before


3000 milliseconds then
promise would be
resolved else it would
be rejected.

57
Promise.all()
Workshop

58
Workshop: Question
You had a form where users submit their name, email, and age. You have validated it,
now you need to consume the promises and process the data only if all validations
pass. If any validation fails, an error message should be displayed to the user.

How can you consume the promise?


Consume it
using
then/catch
Name

Consume the Email


Promise
Age

59
Workshop: Solution
Let’s consume the promise:-

Here we used Promise.all() to consume all


the promises at once.

60
Status Codes
Signalling between Client and Server

61
Status Codes: Signaling Success and Failure
When a request is processed, the server signals the outcome (success or failure) using
status codes, providing clear communication about the operation's result.

{
Data,
Status code,
Message
}
Status Code: Retrieving Status Code
When you make a fetch request, it returns a response with a status code. You can
access the status code using response.status to check the outcome of the request.

Here we are capturing status code

We can use some other variable


let say data, then we get status
code using:-

data.status
Status Code: Success
Success status codes (200-299) indicate that the request was successfully processed by
the server.

Success

203:
200: OK 201: Created 202: Accepted Non-Authoritative 204: No content
Information
Status Codes: Client Error
Client error status codes (400-499) indicate that the request was invalid or cannot be
processed due to issues on the client side.

Client Error

400: Bad 401:


Request 403: Forbidden 404: Not Found 409: Conflict
Unauthorized
Status Codes: Server Error
Client error status codes (400-499) indicate that the request was invalid or cannot be
processed due to issues on the client side.

Server Error

500: Internal 501: Not 502: Bad 503: Service 504: Gateway
Server Error Implemented Gateway Unavailable Timeout
In Class Questions

67
References
1. MDN Web Docs - JavaScript: Comprehensive and beginner-friendly documentation for
JavaScript.
https://developer.mozilla.org/en-US/docs/Web/JavaScript
2. Eloquent JavaScript: A free online book covering JavaScript fundamentals and advanced topics.
https://eloquentjavascript.net/
3. JavaScript.info: A modern guide with interactive tutorials and examples for JavaScript learners.
https://javascript.info/
4. freeCodeCamp JavaScript Tutorials: Free interactive lessons and coding challenges to learn
JavaScript.
https://www.freecodecamp.org/learn/

68
Thanks
for
watching!

69
70
GraphQL API: Querying the database
GraphQL is a query language for APIs that lets clients request exactly the data they
need, reducing over-fetching or under-fetching of data.

71
GraphQL API
Let’s have a look at an example:-

The server stores the entire dataset,


but you only need “name” and “email”.

Unlike other APIs that overfetch by


retrieving entire data units, GraphQL
lets you fetch exactly what you need,
avoiding unnecessary data.

72
GraphQL API: Sending Request Query
Instead of fetching everything, you can query only what you need:

Query you perform Result you get

73
GraphQL API: Sending Request Query
Instead of fetching everything, you can query only what you need:

Query you perform Result you get

74
Lecture 13:
Introduction to
React
-Vishal Sharma

The Ultimate
React Course
1
Prerequisites:
● Basic Web Development Knowledge
I have been already
○ HTML taught these before
○ CSS
○ Javascript
● Text Editor
○ VS Code

2
Table of Contents
● What is React? (Overview and History)
● Setting up a react development environment
● Understanding the React Project Structure
● Creating Functional Components
● JSX Syntax: Writing HTML in javascript
● Rendering components in React application

3
What is React?
A brief Overview

4
Have you ever visited a restaurant?
In a local restaurant, the chef makes each dish from scratch, providing flexibility but it
can be slow and labour intensive. In a franchise, standardized recipes and pre-made
ingredients make the process faster and more consistent.

Local Restaurant Franchise Restaurant


5
JavaScript: Local Restaurant of Web Dev
Just like a local restaurant, JavaScript is flexible but can be slow but difficult to
maintain and labor-intensive as the app grows.

Can’t make from Fed up


scratch rewriting the
code..

6
React: The Franchise Model
React just like a franchise restaurant, it offers standardized processes, reusable
components, and faster, more consistent app development.

Cooked this
Wrote two day
perfect dish in few
code in 2 hrs..
moments..

7
Struggles of JavaScript Development
As web applications became more dynamic, codebase grew larger javascript struggled
with low performance, inefficient updates, and complex code was hard to manage and
maintain.

It’s Struggle to maintain JavaScript websites Code getting too Complex


8
React: The Savior of Web Development
In 2011, Jordan Walke at Facebook, tired of the ongoing frustrations, set out to find a
better way. He envisioned a tool that could make the development process smoother
and more efficient.

Jordan Walker React making life easy for developers


9
What is React?
React is a JavaScript library for building user interfaces, maintained by Facebook.

Library for building web interfaces Build beautiful interfaces with react

10
Why use React?
React is most widely library for building single page websites. For the following
reasons:-

11
Key Features of React
The following are the key features of react:-

Don’t worry if you don’t


understand few of the
terms, we will explain
each of them throughout
our course.

12
Popular websites built on React
The following are few popular websites which uses React:-

Have you identified


your dream company
among these??

13
Setting up a React Project

14
How to Run React Code
React applications can be run in various ways, depending on the development setup
and requirements.

React Environment We will learn how to


setup locally in
future lectures.

Newton Box

Run React Online Run React Locally


15
Run React Online: Newton Box Playground
We can run React code effortlessly without worrying about setup by using remote tools.
Let’s explore how to run React code using Newton Box.
Click on this Link
https://my.newtonschool.co/playground/newton-box/3mmvu006csv0 to open Newton
Box

In Newton Box you can


directly write React Code
and view its preview in
side browser.

16
Run React Online: Newton Box
Let’s analyse UI of Newton Box:-

In built browser to
see the changes

Here you can open Project Here you will write your
files/folders and install dependencies React code 17
Understanding Project Structure

18
Project Structure
In file explorer you can see multiple folders and files being created, let’s understand
each one by one:- Contains all third-party dependencies
installed via npm or yarn.

Contains static files directly served by the


browser.

Contains all the application code

Lists dependencies, scripts, and project


metadata

19
Project Structure
Here we have two more files:-

Here you can specify which files needs


to be ignored by git.

Its primary purpose is to ensure


consistent installations across
different environments. You would be
rarely updating this file manually.

20
Project Structure: src folder
Let’s open the src folder and see its contents:-

Here, you'll find multiple


files. App development
begins with App.js, the main
component of the
application. The App.css file
is used to style and enhance
the visual appearance of the
content in App.js.

21
Project Structure: package.json
📦 package.json in a React project is a file that manages project settings, dependencies,
and scripts to run, build, and test the app.

We can execute these


Dependencies installed
scripts with npm:-
automatically with React
npm start
npm build
Script commands with an …..
alias for npm

22
Functional Components

23
React Functional Components
React functional components are JavaScript functions that return JSX to define and
render UI elements in a React application.

Just like the math functions, React


functional components execute logic
and return UI elements

24
Creating Functional Components
The default code inside App.js is actually a functional component:-

We need to clean
up a bit to include
our custom code.

Functional component

25
Cleaning up Template Code
We would like to create our own functional components so remove template code
and start including our own code instead of react template provided by
create-react-app:-
Redacted

Let’s redact our


template code

And add
Hello, World!

26
Cleaning Up template Code
Let’s also delete unnecessary files from the src folder:-
Also remove index.css from
index.js file as we have
deleted this file

Removed

index.js file

27
Cleaning Up Template Code
Inside index.js reportWebVitals.js file was throwing error, so we removed it from import
statement as well as at the bottom of the file where it was being invoked:-

Removed
reportWebVitals

28
Component based structure in React
React follows a component based structure, where you built the components once
and use them in your code. React Web page we created from React
components

We can reuse
components
React
multiple times. As
Components
we did here..

29
Let’s create some new components
Just like App.js which is the root component, we can build other components. For now
we will build functional components.

We will build these components:-

Header Footer

30
Creating Component: Header.jsx
For now we will create components in the same file i.e. App.js:-

Here we have created a


simple header component
with a simple message.

Header Component

31
Including Header in App.js
We can simply use Header component previously written in App.js file and use it like
this:-

We can include our


components using custom JSX
tags, similar to HTML elements.

32
Let's see how it appears in the browser
Let’s have a look at side browser:-

33
Creating Footer Component
Similarly we can create Footer component and use it in inside App like this:-

Awesome, I now can


create new
components…

34
Let’s have a look of it in the browser
Let’s open the browser and see how it looks:-

Similarly we can create as


many components needed
and use them throughout
the project

35
Styling our React Components
We only have introduced how to write plain JSX, but it looks a bit off. To make it more
appealing we can style it using CSS.

Wow! It looks way


So boring!!
better with CSS

36
How to Style our Component - Inline?
To write inline styles we use style attribute and write our style inside two curly braces:-

Style tag is used to include our styles


and unlike html, we include styles
inside double curly braces {{ }}

Why two curly braces {{...}}

37
Styling Component: { } vs {{ }}
Use single curly braces when you are using javascript variable to feed styles and
double when you are writing styles directly.

We first create a style


object {} to store our
styles. Then, in JSX, we
wrap it inside {} again
Just like any
to apply it, just like
JSX variable,
using any JavaScript
we enclose
variable.
headerStyle in
curly braces {}

38
How to Style our Component - External?
Using inline styles everywhere can clutter the code, so we often use an external CSS file.
We define styles with class names, import the file, and apply the classes in components
using className.

Importing
Header.css file in
Using .header class our file.

Note: Instead of
using class we use
className for
Header.jsx classes
Header.css
39
Have you observed Camel Casing?
In our component which is JSX, style properties use camelCase instead of kebab-case.

camelCase kebab-case

backgroundColor background-color
uses
textAlign text-align

fontSize font-size

Don’t worry, We will learn JSX in borderRadius border-radius


next lecture.
40
Kebab-Style works outside Components
However you can use kebab-style outside the component files, like .css files.

Kebab-Style
text-align

font-size

font-weight

border-radius

41
Why it is called camelCase?
It's called camelCase because the capital letters in the middle create "humps" like a
camel! 🐪

Look closely… see any


humps? 👀

Were you able to guess?

42
In Class Questions

43
References
1. React Docs: https://react.dev
2. MDN React Guide: Comprehensive and beginner-friendly documentation for React
https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_fram
eworks/React_getting_started
3. Websites and Tutorials:
a. 📌 w3schools: https://www.w3schools.com/REACT/DEFAULT.ASP
b. 📌codecademy: https://www.codecademy.com/learn/react-101
4. Other Useful Resources
a. 📌 React GitHub Repository: https://github.com/facebook/react
b. 📌 React Patterns & Best Practices: https://reactpatterns.com/

44
Thanks
for
watching!

45
The Ultimate Lecture 14:
React Course
JSX, Interpolation,
and Rendering
- Narendra Kumar

@newtonschool
1
Prerequisites
● Setting up React dev environment
● Understanding of project structure in react
● React Functional Components
● Basic Understanding of JSX
● Launching React Application in browser using terminal

2
Table of Contents
● Quick Recap
● Introduction to JSX
JSX
● JSX in React
● Writing JSX in React
● Variables in JSX
● Conditional Rendering in JSX
● Loop Rendering in JSX
● Common Errors in JSX
● Summary and Takeaways

3
Quick Recap
A brief Overview

4
Pre-discussed: Project Structure
In File Explorer, you can see multiple folders and files being created. Let’s understand
each one, one by one: Contains all third-party dependencies
installed via npm or yarn.

Contains static files directly served by the


browser.

Contains all the application code

Lists dependencies, scripts, and project


metadata.

5
Pre-discussed: Components
React follows a component-based structure, where you build the components once
and use them in your code. React Web page we created from React
components

We can reuse
components
React
multiple times. As
Components
we did here.

6
Pre-discussed: Creating Header
Let’s create a component named Header.jsx:-

Although not explicitly used in the function, React


is still required to import.

We need to export component to utilize it in some


other place

7
Pre-discussed: Including Header in App.js
We can simply import it in App.js file and use it here:

While importing, we have used relative


path with respect to location of App.js

We can include our components using


custom JSX tags, similar to HTML
elements.

8
Introduction to JSX

9
What is JSX?
JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a
JavaScript file.
JSX is basically javascript
embedded inside HTML
code.

10
Let’s Understand it with an example
Here in this code, the entire snippet inside the return statement is JSX.

Javascript
Variable Anything that evaluates
to a primitive value, an
array, or a function
call returning a valid
HTML with JSX-friendly value can
JavaScript be placed inside JSX.
embedded

11
How do I write JSX code?
We have simple rules for writing JSX: Child elements inside the root element.

Rules for writing JSX

JSX must have a single root element.

Use curly braces {} to embed


Javascript.
12
Using fragment <>..</> instead of <div>
Many a time we use fragment <>...</> instead of <div>..</div> tag of HTML.

We use fragments instead of


<div>...</div> to avoid default HTML
styling.

13
Variables in JSX

14
Why use variables inside JSX?
Using variables in JSX makes apps faster, keeps code organized, and updates data
easily, like live scores or user info. 🚀

Here we are using variables


to store values and using
those values inside our JSX.

15
Use cases of variables in JSX
JSX makes building UI easier and more efficient for variety of use cases.

Use Cases

Displaying Conditional
Calling Functions
Dynamic Content Rendering

And many more...


16
JSX: Displaying Dynamic Content
In the previous example, we stored values in variables and used them in JSX. When
these values change, JSX updates automatically. 🚀

However, these
When these updates are not
value change guaranteed, so
we use hooks.

Don’t worry, we
will learn about
hooks later.
JSX updates
automatically

17
JSX: Conditional Statements
Just like variables, we can also embed conditional statements inside JSX inside curly
braces.

Conditionally Rendering Winner

18
JSX: Calling Functions
Instead of using conditional statements inside JSX, we can directly call a function.

We may directly
call a function
inside JSX.

19
Conditional Rendering

20
What is conditional rendering?
Conditional rendering in JSX controls what UI elements appear based on conditions like
user login status or data availability, similar to if-else in JavaScript.

We can use the following


structures to conditionally
render in a ReactJS app.

21
Conditional Rendering: if...else
In React, if-else decides what to render, useful for returning different UI elements based
on conditions.

22
Conditional Rendering: if...else
If isLoggedIn is set to false, a different message appears as the login status changes.

23
Conditional Rendering: switch
The switch statement is a better choice when handling multiple conditions in JSX, as too
many if-else statements can make the code messy and harder to read.

Which version of
code looks cleaner
to you?

24
Conditional Rendering: switch
Let’s have a look of it at the browser:

25
Conditional Rendering: switch
Let’s try changing it to user this time:

26
Conditional Rendering: AND (&&)
The logical AND (&&) operator is a way to conditionally render elements in JSX. It works
when you only need to display something if a condition is true without needing an else
case.

isLoggedIn
Renderable only if
is true
27
Conditional Rendering: AND (&&)
Let’s change isLoggedIn to false for a moment:

isLoggedIn decides
rendering of button

Since isLoggedIn is false,


<button> has gotten hidden
28
Conditional Rendering: Ternary ( ? : )
Need a fallback when isLoggedIn is false? Use a ternary operator: show "Logout" if true,
else "Login."

If isLoggedIn is true, then


Logout button would appear

If isLoggedIn is false, then


Login button would appear
29
Loop Rendering in JSX

30
Why use loops in JSX?
Often, we need to dynamically generate lists of items. Since JSX doesn’t support for
loops directly inside {}, we use array methods like map() to loop over data.

✅ Displaying a list of products

✅ Rendering menu items


✅ Showing a leaderboard

Common Use Cases

31
Rendering a list of items
Here we have an array, and we are iterating over that array using the map() function of
the array.

32
How it works?
The map function returns an array of list items, which JSX can directly render inside
elements like <ul> or <div>. JSX supports rendering arrays, so each item is displayed
automatically.

Map JSX
returns processes

an array the array


of list
items

33
Common Errors in JSX

34
Errors in JSX
JSX is powerful, but small mistakes can cause errors. Some of the common errors we
have listed below:

Common Errors

Forgetting to wrap Forgetting to wrap


Missing keys when Not closing tags
multiple elements JavaScript
rendering lists properly
in a parent tag expressions in {}

And many more...

35
Forget to wrap elements in parent tag
JSX requires a single parent element to wrap all other elements inside it. Without this,
JSX will throw an error.

Will throw an
error

No parent element
36
Missing Keys in Lists
React uses keys to efficiently update and re-render lists. Without a key, React may not
track items correctly, leading to unwanted re-renders or UI bugs.

It throws errors in browser console if we don’t


include key in items being iterated in loop

37
Missing Keys in Lists
Including keys in an iterable list makes the React rendering process efficient.

No
errors

after
including key

Using keys for


efficient re-renders

38
Forgetting to wrap expressions in {}
Many a time people might want to include a variable, but since they forget to use curly
braces, they end up writing a string instead of a variable.

Here we got string “name”


Here we forget to include braces, so JSX treats it as a string. instead of variable name 39
Forgetting to wrap expressions in {}
Many a time people might want to include a variable, but since they forget to use curly
braces, they end up writing a string instead of a variable.

Here we correctly used braces

40
Not Closing Tags Properly
Many a time people forget closing a tag, which can result in an error.

Forget to close h1

41
In-class questions

42
References
1. MDN React Guide: Comprehensive and beginner-friendly documentation for React
https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_fram
eworks/React_getting_started
2. Websites and Tutorials:
a. 📌 w3schools: https://www.w3schools.com/REACT/DEFAULT.ASP
b. 📌codecademy: https://www.codecademy.com/learn/react-101
3. Other Useful Resources
a. 📌 React GitHub Repository: https://github.com/facebook/react
b. 📌 React Patterns & Best Practices: https://reactpatterns.com/

43
Thanks
for
watching!

44
The Ultimate Lecture 15:
React Course
State Management
& Event Handling
-Narendra Kumar

@newtonschool
1
Prerequisites
● Setting up React dev environment
● Understanding of project structure in react
● React Functional Components
● Basic Understanding of JSX
● Launching React Application in browser using terminal

2
Table of Contents
● Quick Recap
● Problems in using javascript variables
● Understanding State with useState
○ What is State?
○ useState Hook syntax and usage
● Event Handling in React
● State and Events Together
Events in React
● Workshop:To-do App
● Summary and Takeaways

3
Quick Recap
A brief Overview

4
How to write JSX code?
We have simple rules for writing JSX:- Child elements inside root element.

Rules for writing JSX

JSX must have a single root element.

Use curly braces {} to embed


Javascript.
5
JSX: Displaying Dynamic Content
We can store values in variables and used them in JSX. When these values change, JSX
updates automatically. 🚀

However these
When these updates are not
value changes guaranteed, so
we use hooks.

Don’t worry we
will learn about
hooks later.
JSX updates
automatically

6
Problems in using Variables

7
Managing Data in React
In JavaScript, we use variables to store data. Can we use them in React to update the
UI? Let’s find out!

Can we use them


in React too??

Javascript Variables to store values

8
Managing Data in React
Here we have built an app where we can increment the value of count by clicking on
Increment button.

9
Managing Data in React
Here we have built an app where we can increment the value of count by clicking on
Increment button.

Initialized count with 0

Function to increment the


value of count

Displaying the value of


Count

Button to Increment the


value of Count

10
Managing Data in React
Let’s understand how it works:- Initial State

After first click in Increment

Not reflected
in UI

But
Value gets
updated in
console 11
Managing Data in React
Oh, let’s try one more click:-
Holly, molly, why is
After second click in Increment it not updating?

UI still remains Value incremented


unchanged But
from 1 to 2

12
Why did it happen?
It happened because React doesn’t track normal variable changes. React only
re-renders when state or props change.

Even though we change


React doesn’t track the changes the value UI doesn’t
changes and if we
Update javascript variable
No re-render happens reload the page then
value returns to its
default.
UI stays the same

13
Why did it happen?
React re-renders only when state or props change, ensuring the UI always reflects the
latest state accurately. 🚀

Send
Sendupdated
updatedvalue to view
value to the view
Use state to re-render the
UI when a value changes;
Update state object avoid it for values that
Value gets reflected in UI
don’t affect rendering.

Can see updated value

14
Understanding React State

15
Introduction - What is State?
State is like a theater play 🎭—the stage (UI) must always reflect the latest scene.
Actors (state values) change their poses.
Actors in
different dance
poses(state The director (React)
values) ensures the
audience sees the
right scene by
updating the stage
when needed.

Stage (UI)
16
Introduction - What is State?
Different states in react gets stored in the memory. It stores values that change over
time and updates the UI accordingly.

Just like each play has several


Component actors having different poses,
each component in React can
maintain multiple states.
State State

State

17
Understanding useState Hook
useState is a React Hook that lets us add state to functional components.It returns an
array with two elements:

returns
useState [stateVariable, setStateFunction]

Holds Current Function to update


Value Current Value

18
Declaring state with useState hook
We use the useState hook to initialize a React state variable, allowing components
to track and update values dynamically.

Holds current Updates the state and


state value triggers a re-render

Initializes the state


with a starting value

19
useState hook usage
Let’s create a counter where we can increment or decrement the counter by clicking
buttons, for storing count variable, here we will use state variable.

At first we must import the useState hook


from the React library

We initialized the state variable with 0


State variable

20
useState hook usage
Let’s create a counter where we can increment or decrement the counter by clicking
buttons, for storing count variable, here we will use state variable.

Accordingly
value in UI
should
change
Now we need to add an event handler to
handle events:-

1. User Clicks on Increment button


2. User Clicks on Decrement button
21
useState: setter function
The setter function returned by useState is used to update the state value and
trigger a re-render.

Setter Function

Increments the value of count variable state

Decrements the value of count variable state

22
useState: setter function
Let’s write complete code for Counter app using useState and it’s setter function:-

Incrementing and
decrementing using
setCount() setter function
when user clicks the
button.
Event Handlers

23
Testing our app: Increment Button
Let’s try clicking on the ‘Increment’ button:

Before Click:- 2nd Click:- 3rd Click:-

Increment button is working as


expected

24
Testing our app: Decrement Button
Let’s try clicking on the ‘Decrement’ button:

Before Click:- 2nd Click:- 3rd Click:-

Decrement button too is working


as expected
25
Event Handling in React

26
Forms: Creating the file
Forms in React are different from regular HTML because React manages form elements
using state. Let’s create a FormExample.jsx component and include it in our App.js

Go to Explorer and
create a folder
Components and
inside it create a
component named
FormExample.jsx

Include a form in
that file.

27
Forms: Creating and including in App.js
Let’s add FormExample in our App.js as a component: Importing FormExample
using a relative path
Relative path

Including
FormExample in
App.js

28
Forms: Viewing in browser
Let’s have a look at it in the browser:-

29
Forms in React
Create a state variable name and its setter function setName. And add it to the value
attribute to our input box.
Now we need to change
the name state variable
whenever user types a
When name state value in input box
variable changes,
value in the input box
also changes too

We can add an onChange event


which throws an even whenever
we change value in box 30
Forms in React
Add onChange event and associate a function which changes the value of name state
variable:-
Invokes handleChange function Receives an event

We can extract input value from that event as


value gets stored in event.target.value

31
Forms in React
Let’s also add an event on form submission:-

We need to prevent the default behaviour of


submit using event.preventDefault()
name
When we submit the form handleSubmit
function is invoked and by default an event
is passed to it.

32
Workshop

33
Workshop: Build a ToDo App
Create a To-Do App using React that allows users to add, and display tasks.

● Use the useState hook to manage the list of tasks.


● Provide an input field where users can enter a task.
● Add a button to submit and add the task to the list.

After Entering a
task and pressing
Enter

34
Workshop: Solution
Let’s have a look at the solution:-
Store all user-entered ToDos in an array

Capturing Todo entered by the user

When user clicks the button, Todo is added to the todos array

Displaying Todos stored in todos array


35
Workshop: Solution
Let’s have a look at the solution:-

Here:-
1. …todos: fetches all the previous todos and
2. { text: input, id: Date.now() }: New todo
We are using
timestamps as id
36
In Class Questions

37
References
1. MDN React Guide: Comprehensive and beginner-friendly documentation for React
https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_fram
eworks/React_getting_started
2. Websites and Tutorials:
a. 📌 w3schools: https://www.w3schools.com/REACT/DEFAULT.ASP
b. 📌codecademy: https://www.codecademy.com/learn/react-101
3. Other Useful Resources
a. 📌 React GitHub Repository: https://github.com/facebook/react
b. 📌 React Patterns & Best Practices: https://reactpatterns.com/

38
Thanks
for
watching!

39
The Ultimate Lecture 17:
React Course
API Integration

-Narendra Kumar

@newtonschool
1
Table of Contents
● Quick Recap
● Introduction to useEffect
● Side Effects in React (data fetching)
● Fetching data with fetch
● Lifting State Up useEffect
● Managing API using useState and useEffect
● Error Handling and Loading States
Events in React
● Example: Displaying Public Data from a
Public API

2
Quick Recap
A brief Overview

3
Recap: Exporting Files
To use components and in this case Header.js, we must export them from their
respective files and import them where needed.

Tells we are We are


And the export
exporting the exporting
type is default
Exporting Header Component
component Footer
export
component

4
Recap: Import Files
Let’s dissect each part of our import statement:-

Component name we are Path of the file from where we


importing since it is default are importing the component.
import, we can use alias Here we have used relative path.

5
Recap: Passing props from parent to child
Prop passing from parent to child means sending data from a parent component to a
child component in React using props (properties).
Props gets received in javascript
variables as parameter to our
component.
Props are
passed just like
we write
attributes in
HTML elements

Using received prop value dynamically


inside our JSX.
6
Recap: Creating a React App
Terminal would look like this:-

Run create vite@latest command with project directory name next to it

7
Recap: Installing and Launching App
And then you need to install all the packages by using “npm install” and run the app
using “npm run dev”.

Run “npm install” to install all the


project dependencies packages

Run “npm run dev” to run your react


application

Type this url in the address bar of your


browser to preview your Project.
8
Where is my data?

Introduction to useEffect()
Handling Side-Effects

9
Remember async operations in JS?
We used callbacks, promises, etc. But why? What was the issue with async operations?

Async operations do not


execute immediately, so
waiting for them blocks the
execution of other tasks.

10
Use used promises to handle async ops
We used promises to handle async operations in JS. Here is an example:

And then need to pass this


orderFood() function to the
event listener attached to
an element.

11
Use used promises to handle async ops
We used promises to handle async operations in JS. Here is an example:-

Do I need to do all this


work to each element we
want to listen?

Thankfully we have
useEffect() hook in React.

12
Don’t worry we have useEffect() in React
useEffect in React handles side effects like data fetching, subscriptions, or DOM
updates after render.

Here Mounted means


DOM tree is created

We include async
code inside
useEffect block

13
useEffect() simplifies the page updates
Just like promises facilitates the async operations to happen in right order, useEffect
makes sure that async code runs only at the end allowing other parts of the page to load
immediately.
After the page rendering is complete useEffect runs,
re-rendering the page if code inside the useEffect
changes the content of the page.

14
Let’s Understand with a Simple Example
Suppose you are provided a url from where you need to fetch the data and display its
title in your web page.

If we use javascript we need to add event listener Whereas React runs useEffect at the end and if
and create, insert dom elements by ourself useEffect code changes content of the page, it
reloads the latest copy of the page.
15
Order of execution…
Let’s understand the order of execution of useEffect() with respect to rest of the code.

1. State Variable is declared and assigned


null

3. Code inside useEffect() block executes

2. Expression is evaluated and since data is null.


Loading… is returned

16
How React knows content has changes?
React tracks if its state variables are changed and when they are changed, a re-render
of web page is triggered.

State Variable

Updating the state variable after


fetch async operation is
complete, making web page
re-render with latest copy.

17
Initial Render: Data is not fetched yet
If your internet connection is fast enough then initial render might not visible to you, in
that case you need to slow down your internet connect from network tab of inspect tool.

18
After fetch operation is completed
Have you observed that entire return block was executed once and as soon as state
variable inside useEffect executed, JSX inside return statement got re-evaluated and
re-rendered.

19
Key Takeaway
The only major work of useEffect is to execute its code after the initial render. We
execute all async operations inside it, and make state changes if needed after async
operations are complete, triggering the page re-render again.

Code inside useEffect


runs
As soon as the state
Initial Render variable is changes,
Async code executes page re-rendering
and based on outcome is triggered
state variable is
changed.

20
Error Handling and Loading States
Managing failure states

21
What if fetch api fails?
In case data fetching fails, then block is never executed and data state variable is never
set. Would that mean, our app is always in Loading state? Isn’t it inappropriate…

Always shows Loading state, but we should be


showing that data fetch failed.

22
Using Error State to Manage Errors
We need to maintain an error state to handle failures. Check response.ok to detect API
failure. If false, throw an error, which is caught in catch to update the error state.

If an error occurs, it is thrown and caught in catch,


where the error state is updated with the message.

We check for an error first and display the error message if present;
otherwise, we render the data.

23
Let’s introduce a typo to check error message
Here we have intentionally introduced a typo to check if the error message is rendered
in the screen.

Typo “todo” instead of


“todos”

24
Lifting State Up
Child Talking to Parent

25
Recap: Create new components
Just like App.js which is the root component, we can build other components. For now
we will build functional components.

We will build these components:-

Header Footer

26
Creating Header.jsx
Here we have created Header component in the separate named Header.jsx:-

Here we have created a


simple header component
with a simple message.

Header Component

27
Pre-discussed:Including Header in App.js
We can simply import it in App.js file and use it here:-

While importing we have used relative


path with respect to location of App.js

We can include our components using


custom JSX tags, similar to HTML
elements.

28
Recap: Creating Footer Component
Similarly we can create Footer component and use it in inside App like this:-

Awesome, I now can


create new
components…

29
Recap: Customized Message in Header
Often, we need to display names or similar data in the webpage header. We can store
the value and pass it to the Header component.

This doesn’t seems


right, we should be
taking data from Home
Page i.e. App.jsx

30
Recap: Passing props from parent to child
Instead we can use prop. Prop passing from parent to child means sending data from a
parent component to a child component in React using props (properties).
Props gets received in javascript
variables as parameter to our
Props are component.
passed just like
we write
attributes in
HTML elements

Using received prop value dynamically


inside our JSX.
31
What if we need to pass prop child to parent
Lifting State Up moves state from a child to its parent, allowing shared management.
The child updates the parent using callback functions passed as props.

PApp.jsx
P
Here parent App.jsx passes the state
Child to
parent to its states to Footer.jsx and
Parent Header.jsx, Header.jsx modifies the
to child
state and send back to parent
App.jsx

Footer.jsx Header.jsx

32
Lifting State Up: How it happens
The child updates the parent using callback functions passed as props.

P
P

State update function


passed as a value in
onNameChange prop

33
Lifting State Up: How it happens
Props passed are received in the child component, and then child can use it.

Received as prop
P
P
Here we have
attached received
function(onNameCha
nge) to onChange
event

34
Lifting State Up: How it happens
Let’s understand the entire flow, what get passed to where:-
Prop got received

State
changer
P function
passed as
P prop Prop
function
attached to
onChange
event

App.jsx
Header.jsx

35
Lifting State Up: How it happens
Here we have attached state updater function to an even in the child component.

P handleNameChange()
got attached to
P onChange event

App.jsx

Header.jsx

36
Lifting State Up: How it happens
When user writes its name on input box, onChange event handler gets invoked and an
event gets passed to its associated function i.e. onNameChange().

37
Lifting State Up: How it happens
onNameChange() in turn corresponds to handleNameChange() function in the parent
component.

Event received in
onNameChange()

Header.jsx

Event gets passed


to parent

When user writes in input box


onNameChange() receives and event object App.jsx
38
Lifting State Up: How it happens
Hence we can update the state of parent function by passing state updater function in
a prop.

Updates the value


in react state
“name”

App.jsx

39
Workshop

40
In Class Questions

41
References
1. MDN React Guide: Comprehensive and beginner-friendly documentation for React
https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_fram
eworks/React_getting_started
2. Websites and Tutorials:
a. 📌 w3schools: https://www.w3schools.com/REACT/DEFAULT.ASP
b. 📌codecademy: https://www.codecademy.com/learn/react-101
3. Other Useful Resources
a. 📌 React GitHub Repository: https://github.com/facebook/react
b. 📌 React Patterns & Best Practices: https://reactpatterns.com/

42
Thanks
for
watching!

43
The Ultimate Lecture 18:
React Course
Hooks and React
Lifecycle
-Narendra Kumar

@newtonschool
1
Table of Contents
● Quick Recap
● Details about useEffect
● Component lifecycle
○ Mounting
○ updating
○ Destruction
● Cleanup functions in useEffect.
● Example: Timer or clock application.

2
Quick Recap
A brief Overview

3
Recap: Purpose of useEffect()
useEffect in React handles side effects like data fetching, subscriptions, or DOM
updates after render.

Here Mounted means


DOM tree is created

We include async
code inside
useEffect block

4
Recap: Order of execution…
Let’s understand the order of execution of useEffect() with respect to rest of the code.

1. State Variable is declared and assigned


null

3. Code inside useEffect() block executes

2. Expression is evaluated and since data is null.


Loading… is returned

5
Understanding useEffect in Detail
Application updates simplified

6
useEffect() dependency Array
useEffect() is a react hook which receives two arguments, the first is a callback function
and second is the dependency array.

Callback function
// Your Callback function Code It includes code to be executed

Dependency Array

Tells when should useEffect


callback be executed
7
Dependency Array: Empty
Callback function will be executed just after initial render of the web page.

Will be executed
exactly once in whole
life cycle.
// Your Callback function Code

Since dependency
array is empty

8
Dependency Array: Empty with Example
Here we want to perform a fetch operation a fetch operation just after the page renders.
To achieve this we have kept dependency array empty.

Since we are doing state update inside


the useEffect on successful completion
of fetch operation, page gets
re-rendered once again.

9
useEffect() dependency Array
useEffect() is a react hook which receives two arguments, the first is a callback function
and second is the dependency array.

But if it is non-empty, then useEffect runs whenever


If dependency array empty then useEffect is executed the state variables in that dependency arrays gets
just once after the page loads. updated.

10
Dependency Array: State Variables
If dependency array contains state variables then callback function executes for each
change in any of the state variables it contains.

Will be executed every time any


of the state variable changes

Since dependency
array have state
variables

11
Let’s understand it with an example
Here we have our old good counter app, but for debugging purpose we want to display
the value of the counter. How to do it??

12
useEffect: state variable in dependency array
Let’s write a useEffect() hook, with a callback function displaying the value of “count”
along with dependency array having count as its value.

And whenever count state updates by


one, code inside useEffect runs as
count is provided as a value in the
dependency array.

Whenever user clicks on Increment,


count state increments by one

13
useEffect: state variable in dependency array
Similarly we can add any number of state variables in the dependency array, and if any of
these state value changes, useEffect() callback function is executed.

If any of these state variable changes, callback


function in the useEffect() is executed

14
Functional Component Lifecycle
Mounting, updating and destruction

15
Lifecycle of Functional Components
In class components, lifecycle methods like componentDidMount, componentDidUpdate
etc control side effects. In functional components, useEffect replaces them.

Let’s understand each of these


phases in the upcoming slides

16
Mounting: useEffect with empty array
Let’s say you want an operation like data fetch from the remote server for the first time
website loads.
Best for operations which happens
once after the component
loads/mounts like data fetch etc.

If we keep dependency array


empty then useEffect callback
function only executes once
after initial render

17
Updating: useEffect with state variables
Many a times we need useEffect to run again and again whenever a state variable
changes, to make it happen we can add state variables in the dependency array of the
useEffect hook.

Here we were running useEffect code for


each updation in the state variable.

And whenever count state updates


by one, code inside useEffect runs
as count is provided as a value in
the dependency array.

Whenever user clicks on Increment,


count state increments by one
18
Unmount: useEffect with return
When a component is no longer needed (e.g., navigating to another page), it should
release resources through cleanup—this is called unmounting. We do it inside return.

setInterval() acquired when component mounted

setInterval() got released when component


unmounted i.e. component got destroyed.

19
Unmount: useEffect with return
We can acquire more than one resources after mounting the component and release all of
them at once inside the return block when component unmounts.

Acquiring resources after mounting

Releasing resources after unmounting

20
Key Takeaway
We always need to run clean up functions if resources are acquired during mounting
stage. If not then performance of our application is compromised.

There isn't much space; we need to


clean up the area by leaving.

21
Handling Error States
Catching Up the Errors

22
Error can happen due to various reasons
Many a time async operations can fail leading to erroneous state, we need to handle
such scenario by adding proper error handling.

23
We need to handle those errors
There are different ways to handle those errors:-

Ways to Handle Errors

.then() .catch() block try/catch block

24
then/catch to Handle the Errors
We can handle the errors using then/catch block in case of promises.

.then()
Nothing new just chain .then()
for successful execution and
.catch() block for catching up
errors.
.catch()

25
Using Error State to Manage Errors: then/catch
We need to maintain an error state to handle failures. Check response.ok to detect API
failure. If false, throw an error, which is caught in catch to update the error state.

If an error occurs, it is thrown and caught in catch,


where the error state is updated with the message.

We check for an error first and display the error message if present;
otherwise, we render the data.

26
Recap: try/catch handling errors
Imagine a nice day, driving your car and suddenly met with an accident. But don’t worry
airbags are there to catch and save you.

Car/application running A crash occurred causing Thankfully error got caught not
smoothly an injury/error causing much damage

27
Recap: try/catch Saves your day
Definitely we were not talking about car!!

Error

Web application running Error occurred try…catch caught the error


smoothly

28
Using Error State to Manage Errors: try/catch
We can achieve same using try/catch instead.

Any error raised inside try


block gets catched up in the
catch block

29
Cleanup useEffect()
Releasing resources after the use

30
Resources you need to run React App
Many a time you need to acquire resources for instance to perform a repetitive task
you need setInterval() and to finish a tasks after a certain time you need setTimeout().

setTimeout setInterval

31
But these resources stack if not released
These resources work asynchronously. If there are too many such resources executing
simultaneously, we face performance issues. We need to release them if not in use.

So many async functions!!


I can’t handle

……………..
……………..
setInterval() setInterval()
setTimeout() setTimeout()
setTimeout() setTimeout() setTimeout()
setInterval() SetInterval() setInterval()
Executes what event
loop brings to it

32
When these resources are acquired
We acquire these resources in the mounting state inside useEffect(). Let’s build a clock
using setInterval() to elaborate this:-

Adding style
to our clock

33
Let’s Render it in browser
Let’s include it in the App.jsx and render in the browser. What if we conditionally hide this
clock component, would setInterval
stop executing?

34
Let’s Hide it conditionally
Here we have added added a hide button which when clicked hides the clock i.e. removes
it from the DOM.

35
Let’s see how it looks now
Here when hide button is clicked then the <Clock /> component is removed from DOM,
but does that mean setInterval also gets removed? I don’t think so.

After hide
button is
clicked

36
What happens when hide is clicked?
Here when hide button is clicked then the <Clock /> component is removed from DOM,
but does that mean setInterval also gets removed? I don’t think so.

Message keep on printing even


after Clock is unmounted
Add this debugging statement
before clicking hide, and you will Observe this count if it
observe that this message will still keeps on increasing
be printed after every 1000ms even after component
is unmounted
37
How to avoid this: cleanup
If we attach a return block inside useEffect, it would be executed only after component is
unmounted and there we can include code to remove resources from the DOM.

This entire
process is called
CleanUp.

Block executes only


after component
unmounts.

And clearInterval()
removed the interval
from the DOM

38
Workshop

39
In Class Questions

40
References
1. MDN React Guide: Comprehensive and beginner-friendly documentation for React
https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_fram
eworks/React_getting_started
2. Websites and Tutorials:
a. 📌 w3schools: https://www.w3schools.com/REACT/DEFAULT.ASP
b. 📌codecademy: https://www.codecademy.com/learn/react-101
3. Other Useful Resources
a. 📌 React GitHub Repository: https://github.com/facebook/react
b. 📌 React Patterns & Best Practices: https://reactpatterns.com/

41
Thanks
for
watching!

42
The Ultimate Lecture 18:
React Course
Hooks and React
Lifecycle
-Narendra Kumar

@newtonschool
1
Table of Contents
● Quick Recap
● Details about useEffect
● Component lifecycle
○ Mounting
○ updating
○ Destruction
● Cleanup functions in useEffect.
● Example: Timer or clock application.

2
Quick Recap
A brief Overview

3
Recap: Purpose of useEffect()
useEffect in React handles side effects like data fetching, subscriptions, or DOM
updates after render.

Here Mounted means


DOM tree is created

We include async
code inside
useEffect block

4
Recap: Order of execution…
Let’s understand the order of execution of useEffect() with respect to rest of the code.

1. State Variable is declared and assigned


null

3. Code inside useEffect() block executes

2. Expression is evaluated and since data is null.


Loading… is returned

5
Understanding useEffect in Detail
Application updates simplified

6
useEffect() dependency Array
useEffect() is a react hook which receives two arguments, the first is a callback function
and second is the dependency array.

Callback function
// Your Callback function Code It includes code to be executed

Dependency Array

Tells when should useEffect


callback be executed
7
Dependency Array: Empty
Callback function will be executed just after initial render of the web page.

Will be executed
exactly once in whole
life cycle.
// Your Callback function Code

Since dependency
array is empty

8
Dependency Array: Empty with Example
Here we want to perform a fetch operation a fetch operation just after the page renders.
To achieve this we have kept dependency array empty.

Since we are doing state update inside


the useEffect on successful completion
of fetch operation, page gets
re-rendered once again.

9
useEffect() dependency Array
useEffect() is a react hook which receives two arguments, the first is a callback function
and second is the dependency array.

But if it is non-empty, then useEffect runs whenever


If dependency array empty then useEffect is executed the state variables in that dependency arrays gets
just once after the page loads. updated.

10
Dependency Array: State Variables
If dependency array contains state variables then callback function executes for each
change in any of the state variables it contains.

Will be executed every time any


of the state variable changes

Since dependency
array have state
variables

11
Let’s understand it with an example
Here we have our old good counter app, but for debugging purpose we want to display
the value of the counter. How to do it??

12
useEffect: state variable in dependency array
Let’s write a useEffect() hook, with a callback function displaying the value of “count”
along with dependency array having count as its value.

And whenever count state updates by


one, code inside useEffect runs as
count is provided as a value in the
dependency array.

Whenever user clicks on Increment,


count state increments by one

13
useEffect: state variable in dependency array
Similarly we can add any number of state variables in the dependency array, and if any of
these state value changes, useEffect() callback function is executed.

If any of these state variable changes, callback


function in the useEffect() is executed

14
Functional Component Lifecycle
Mounting, updating and destruction

15
Lifecycle of Functional Components
In class components, lifecycle methods like componentDidMount, componentDidUpdate
etc control side effects. In functional components, useEffect replaces them.

Let’s understand each of these


phases in the upcoming slides

16
Mounting: useEffect with empty array
Let’s say you want an operation like data fetch from the remote server for the first time
website loads.
Best for operations which happens
once after the component
loads/mounts like data fetch etc.

If we keep dependency array


empty then useEffect callback
function only executes once
after initial render

17
Updating: useEffect with state variables
Many a times we need useEffect to run again and again whenever a state variable
changes, to make it happen we can add state variables in the dependency array of the
useEffect hook.

Here we were running useEffect code for


each updation in the state variable.

And whenever count state updates


by one, code inside useEffect runs
as count is provided as a value in
the dependency array.

Whenever user clicks on Increment,


count state increments by one
18
Unmount: useEffect with return
When a component is no longer needed (e.g., navigating to another page), it should
release resources through cleanup—this is called unmounting. We do it by returning a
function that is run during unmounting.

setInterval() acquired when component mounted

setInterval() got released when component


unmounted i.e. component got destroyed.

19
Unmount: useEffect with return
We can acquire more than one resources after mounting the component and release all of
them at once inside the return block when component unmounts.

Acquiring resources after mounting

Releasing resources after unmounting

20
Key Takeaway
We always need to run clean up functions if resources are acquired during mounting
stage. If not then performance of our application is compromised.

There isn't much space; we need to


clean up the area by leaving.

21
Handling Error States
Catching Up the Errors

22
Error can happen due to various reasons
Many a time async operations can fail leading to erroneous state, we need to handle
such scenario by adding proper error handling.

23
We need to handle those errors
There are different ways to handle those errors:-

Ways to Handle Errors

.then() .catch() block try/catch block

24
then/catch to Handle the Errors
We can handle the errors using then/catch block in case of promises.

.then()
Nothing new just chain .then()
for successful execution and
.catch() block for catching up
errors.
.catch()

25
Using Error State to Manage Errors: then/catch
We need to maintain an error state to handle failures. Check response.ok to detect API
failure. If false, throw an error, which is caught in catch to update the error state.

If an error occurs, it is thrown and caught in catch,


where the error state is updated with the message.

We check for an error first and display the error message if present;
otherwise, we render the data.

26
Recap: try/catch handling errors
Imagine a nice day, driving your car and suddenly met with an accident. But don’t worry
airbags are there to catch and save you.

Car/application running A crash occurred causing Thankfully error got caught not
smoothly an injury/error causing much damage

27
Recap: try/catch Saves your day
Definitely we were not talking about a car!!

Error

Web application running Error occurred try… catch caught the error
smoothly

28
Using Error State to Manage Errors: try/catch
We can achieve same using try/catch instead.

Any error raised inside try


block gets catched up in the
catch block

29
Cleanup useEffect()
Releasing resources after the use

30
Resources you need to run React App
Many a time you need to acquire resources for instance to perform a repetitive task
you need setInterval() and to finish a tasks after a certain time you need setTimeout().

setTimeout setInterval

31
But these resources stack if not released
These resources work asynchronously. If there are too many such resources executing
simultaneously, we face performance issues. We need to release them if not in use.

So many async functions!!


I can’t handle

……………..
……………..
setInterval() setInterval()
setTimeout() setTimeout()
setTimeout() setTimeout() setTimeout()
setInterval() SetInterval() setInterval()
Executes what event
loop brings to it

32
When these resources are acquired
We acquire these resources in the mounting state inside useEffect(). Let’s build a clock
using setInterval() to elaborate this:-

Adding style
to our clock

33
Let’s Render it in browser
Let’s include it in the App.jsx and render in the browser. What if we conditionally hide this
clock component, would setInterval
stop executing?

34
Let’s Hide it conditionally
Here we have added added a hide button which when clicked hides the clock i.e. removes
it from the DOM.

35
Let’s see how it looks now
Here when hide button is clicked then the <Clock /> component is removed from DOM,
but does that mean setInterval also gets removed? I don’t think so.

After hide
button is
clicked

36
What happens when hide is clicked?
Here when hide button is clicked then the <Clock /> component is removed from DOM,
but does that mean setInterval also gets removed? I don’t think so.

Message keep on printing even


after Clock is unmounted
Add this debugging statement
before clicking hide, and you will Observe this count if it
observe that this message will still keeps on increasing
be printed after every 1000ms even after component
is unmounted
37
How to avoid this: cleanup
If we attach a return block inside useEffect, it would be executed only after component is
unmounted and there we can include code to remove resources from the DOM.

This entire
process is called
CleanUp.

Block executes only


after component
unmounts.

And clearInterval()
removed the interval
from the DOM

38
Workshop

39
In Class Questions

40
References
1. MDN React Guide: Comprehensive and beginner-friendly documentation for React
https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_fram
eworks/React_getting_started
2. Websites and Tutorials:
a. 📌 w3schools: https://www.w3schools.com/REACT/DEFAULT.ASP
b. 📌codecademy: https://www.codecademy.com/learn/react-101
3. Other Useful Resources
a. 📌 React GitHub Repository: https://github.com/facebook/react
b. 📌 React Patterns & Best Practices: https://reactpatterns.com/

41
Thanks
for
watching!

42
The Ultimate Lecture 19:
React Course
useRef

- Narendra Kumar

@newtonschool
1
Table of Contents
● Quick Recap
● Introduction to useRef.
● Managing DOM references and persisting mutable state.
● Example: Creating a custom input focus or timer with useRef.

2
Why useRef is needed in React
Application updates simplified

3
Forms: Essence of Data Collection
Forms are essential components of web applications as they allow users to interact with
the system by submitting data.

Using event handlers to update state.

Using ref variables to update state.

4
Form: Event Handlers to Update State
In React we attach event handler functions to specific events, like onChange, onClick, etc.
These event handler functions process and save the data. Here is an example:

Each time the handler function runs and changes


the state variable.

The web page re-renders

Here we have attached an event handler onChange


which executes handler function each time we press
the keyboard button

5
React way of Collecting Form Data
A prominent problem is that each time the event handler updates the state variable,
whole UI gets re-rendered.

Before we press a key For Each Key we Press UI gets re-rendered

6
Better to use useRef instead
If we use useRef instead, we can avoid this re-rendering of the web page again and again.

And changes should be made only after the user presses the enter
key to avoid re-renders every time the user enters a letter in the
input box.

We should remove this function and onChange event handler each


time we press a key

To achieve all these, we


can utilize useRef hook

7
What is useRef hook?
Way to persist data without re-renders

8
What is useRef hook?
The useRef hook in React creates a mutable reference that persists across renders
without causing re-renders.

Here we have declared a useRef variable using useRef Hook

Somehow we need to
capture the input box
value to our ref variable.

9
Attaching reference to HTML Element
Let’s attach a reference to our ref variable in the input box.

Are we manipulating DOM


elements directly??

Whenever you input something in


the input box, nameRef gets
updated. As nameRef is now
connected to our input box.

And unlike the previous way, the


web page doesn’t get re-rendered
again.

10
Storing value on state variable on submission
We will only update the state variable on submission, i.e., only one re-render. Far better
than previous method

When we submit, the state Before Clicking Submit


variable gets updated and
we get a re-render

After Clicking Submit


11
Key Takeaway
Using useRef, we can persist changes in the ref variable without re-rendering the UI.

Directly changing State variable Using ref to change the State Variable

Re-render for each change you made. You can schedule re-rendering on submit
only.

React changes the DOM. You are directly manipulating the DOM.

12
React DOM Manipulation
Managed way to change DOM

13
Understanding DOM
The DOM is a tree-like structure of an HTML or XML document that lets JavaScript access
and modify web page elements dynamically.

HTML

HEAD BODY

TITLE H1 Others
HTML is maintained in similar to this way

Page Title Hello, World!

14
What happens in DOM Manipulation
When we manipulate DOM, we change our document by changing the values in the DOM
tree.

HTML

HEAD BODY

Let’s say we TITLE H1 Others


are changing
value here Page Title Hello, World!

Gets reflected here


15
React: Managed way to manipulate DOM
In JavaScript we do DOM manipulations manually, but in React it is done in a very
managed way. We don’t do DOM manipulations directly in React, but React facilitates
manipulations.
HTML

Perform
Any
Changes
Changes
Efficiently
HEAD BODY
React Code

TITLE H1 Others

Page Title Hello, World!

16
useRef DOM Manipulation
Direct DOM Manipulation

17
useRef: Direct DOM Manipulation
Instead of allowing React to manage DOM, we can instead use useRef to directly make
changes in DOM without triggering the re-render.

HTML
Can hold direct reference
to DOM elements and
make necessary changes.
HEAD BODY

TITLE H1 input

Page Title Hello, World!

18
Direct DOM References: inputRef Example
React provides the useRef hook to hold references to DOM elements. To make updates,
we can modify the referenced value directly without causing a re-render.

Importing useRef as named import

Initializing as null i.e., it doesn’t contain any


references

Let’s say we need to attach reference of input to change its


properties directly in DOM

19
useRef: Attaching a Reference
Let’s attach a reference to the input box and use it to change the properties of the input
box.

Using this reference, we can


change the properties of the
input box.

Attached Reference

20
useRef: Changing properties on Events
Here we have added a button that, when clicked, executes an event handler that
manipulates the properties of the input box.

Changing the
properties of input
box using reference

On button click
handleFocus is
executed

21
useRef: Let’s see in the browser
However, React provides the useRef hook to hold references to DOM elements. When
updates

Before button click After button click

22
Workshop

23
In Class Questions

24
References
1. MDN React Guide: Comprehensive and beginner-friendly documentation for React
https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_fram
eworks/React_getting_started
2. Websites and Tutorials:
a. 📌 w3schools: https://www.w3schools.com/REACT/DEFAULT.ASP
b. 📌codecademy: https://www.codecademy.com/learn/react-101
3. Other Useful Resources
a. 📌 React GitHub Repository: https://github.com/facebook/react
b. 📌 React Patterns & Best Practices: https://reactpatterns.com/

25
Thanks
for
watching!

26
The Ultimate Lecture 20:
React Course
Component
Modularity
- Narendra Kumar

@newtonschool
1
Table of Contents
● Importance of component modularity.
● Identifying reusable components in a React application.
● Breaking a large UI into smaller, manageable components.
● Introducing component libraries like MUI and Shadcn/UI
● Example: Refactoring a simple app

2
Component Modularity
Breaking Component into pieces

3
Let’s Build an E-Commerce App
Think in terms of components—what does an e-commerce website include? A header, a
footer, a main content area, and multiple product cards inside it, along with many others.

Header

Main Area
Our app has clearly three
components.
Product 1 Product 2 Product 3

We need to create these three


components and then include
them in our App.jsx file.
Product 4 Product 5 Product 6

Footer 4
Create a new React Project
Create a new React project using Vite, and then create a new folder named “components”
to store all our React components.

We have created
three components
inside components
folder

5
Write Skeleton Code for each of them
Then we will write the skeleton of functional components and then import them in
App.jsx

And then import these


files in the App.jsx
6
Importing files in App.jsx
Let’s import all these files in our App.jsx file:

We have included all the


components inside the Now we can start
components folder to adding code in our
provide structure to our component files.
code.
This is how you
start thinking
about a project.

Here we have used imported


components in our App.jsx
file.

7
Viewing our Project in the browser window
Open the terminal and run the command “npm run dev” and then open the browser and
enter the URL indicated in the terminal window.

Header

Main Area
Our task is to
transform our
Product 1 Product 2 Product 3
components to
look like this

Product 4 Product 5 Product 6

Footer 8
At first we remove default spacing
Open the index.html file and add the following CSS to remove the default spacing. Same
with App.jsx outer div and Header component.

App.jsx

index.html

9
Styling the Header Component
Here we have stored Header styles in a variable and passed them to the outer div of our
Header component.

10
Styling the Footer Component
We can apply the same styles to the Footer also, like this: Doesn’t seem right. Need to
make the height of the
MainArea 100vh.

11
Styling the Main Area
In the MainArea, we will set the height to 100vh and apply appropriate padding all around.

12
Adding container for product cards
Let’s add product container div and add cards inside it:
Product cards are
not styled; let’s
style them in next
slide

13
Styling product card
Let’s properly style the product cards to make them look elegant:

14
Styling product card
Let’s properly style the product cards to make them look elegant:

Here we are repeating the similar code three times;


it is ok for now since each product card is small, but
if it were big, then lots of repeated code would be
written.

We can make a reusable component,


where we will pass product details as
prop and reuse it for all the product
cards

15
Styling product card
Let’s properly style the product cards to make them look elegant:

16
Code is repeating too frequently
Can you observe a pattern?

Good
opportunity to
make a new
Similar code is being component
repeated several times in
the component.

17
Creating Product Card Component
Let’s create a separate product card and use it several times instead of writing the same
product card code again and again.

Observe how much


simpler our
MainArea
component has
become.

ProductCard.jsx MainArea.jsx 18
Key Takeaway
Here, instead of repeating the same code again and again, we converted repeated code
into a modular component and reused it several times.

Rule of thumb

If code is repeated, create a


separate module and import
it.

ProductCard module
19
Component Libraries
Readymade components

20
Websites built on Component Libraries
Many a time we come across beautiful websites and wonder if we could make them. Do
we need to create each and every component?

You need not make your own


components.

You can just utilize popular


component libraries like
Shadcn/UI or Material UI etc.

21
Popular Component Libraries
There are several component libraries accessible in React environment; few of them are

and many more…


22
Shadcn/UI an overview
You can visit the shadcn website to look for components you need:

Click here to get a detailed guide


on appropriate framework/library

https://ui.shadcn.com/
Spend some time in their
websites/read documentation
to get familiar
23
Shadcn/UI: Button Component
For instance, I was looking for a button component in Next.js:

You won’t find React in the list of


frameworks, but it works same in
Next.js, which is basically React.js.

24
Material UI: An overview
Similarly, you can utilize Material UI; you just need some exploration.

Explore their website to learn more

https://mui.com/material-ui/ 25
Workshop

26
In Class Questions

27
References
1. MDN React Guide: Comprehensive and beginner-friendly documentation for React
https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_fram
eworks/React_getting_started
2. Websites and Tutorials:
a. 📌 w3schools: https://www.w3schools.com/REACT/DEFAULT.ASP
b. 📌codecademy: https://www.codecademy.com/learn/react-101
3. Other Useful Resources
a. 📌 React GitHub Repository: https://github.com/facebook/react
b. 📌 React Patterns & Best Practices: https://reactpatterns.com/

28
Thanks
for
watching!

29
The Ultimate Lecture 21:
React Course
Next.js:
Routing Simplified
-Narendra Kumar

@newtonschool
1
Prerequisites
● Core Web Fundamentals
○ Understanding of HTML and CSS
○ how websites work (Client-Server model, HTTP basics)
● JavaScript Proficiency
● React.js Experience
● Development Environment Setup
○ Node.js
○ Package Manager
○ Code Editor
○ Terminal/CLI

2
Table of Contents
● Introduction to Next.js
● Understanding Next.js & Key Features
● Why Choose Next.js? Advantages Over React
● Getting Started: Creating a project, navigating through
● Project Structure & Key Files
● Routing in Next.js
● Building Project: An Introduction
● Conclusion

3
Introduction to Next.js
Building Modern Web

4
What is Next.js?
Next.js is a React framework that speeds up web development with server-side and static
rendering, this makes it the superman of web development frameworks.

Builds pages in server

Also sends
javascript code
to build website
on user
interaction
Also builds pages client-side
on user interaction.

5
How it helps?
By building website in the server and sending website builder code we can have following
advantages:-

Since it builds
pages in server too,
leads to better SEO

Mix of server and Faster Initial Loading Faster Page Better SEO
client side rendering Loading

Initially loads pre-built server It can rebuild on the client side like
pages, so initial rendering is fast React, no server request needed. 6
Next.js: Other Benefits
It also optimizes images to be loaded in the website and also simplifies the routing.

Uses file-based
routing
Next.js is great for
optimally loading
of images in web
page.

7
Getting Started
Creating Project & Navigating Through

8
Installing Next.js
Let’s install Next.js using terminal:-
Run the following command to install Next.js

Then give a project name to it,


and then the following
specifications.

9
Success Message and Project Folder
You will see the following message in the terminal, navigate to your project folder and
you will observe this folder structure:-

10
Exploring Project Folder
Let’s explore project folder:-
Contains your Next.js project

It tells your editor how to understand paths,


modules, and features of your project.

used to customize and configure how your


Next.js app behaves during build time and
runtime.

Configures PostCSS, which processes your


CSS to add features and optimize output.
Next.js uses PostCSS under the hood.

Required when using Tailwind CSS in Next.js.

11
Exploring Project Folder (app)
Let’s explore project folder:-

Contains global styles for It is like telling Hey Next.js, I


your entire app (e.g., want this header, footer,
fonts, resets, layout
or sidebar to show on every
basics)
page of my app.

Defines the root layout


for your app.

Entry point or Homepage


of your app

12
Launching your project
You can launch your project by running this simple command:-

Your project will get


launched on:-

http://localhost:3000

13
Launching your project
You can launch your project by running this simple command:-

14
Routing in Next.js
File based routing

15
File Based Routing
Let’s understand it by writing our code:-

Let’s create these files and


folders and add code inside it.

Since page.js is directly inside the app/


folder—the root routing folder—it serves as the Note: page.js acts
homepage (/) of the entire Next.js project. as the root route
for its folder.
It is accessible by:- http://localhost:3000 in our
case

16
Let’s view our homepage in the browser
Here is the code for our homepage:-
Since it is directly inside our
app/ folder it is accessible
using root url

17
What about page.js inside posts folder
To access the page.js inside the posts folder, we need to add /posts to the URL, as the
folder name defines the route path.
Notice how the folder structure directly maps to
the URL path used to render each page.

18
Let’s build another route inside posts
We just need to create another folder with name of the route we want, let’s name the
folder about and create page.js inside it:-
Can you observe the pattern?

19
Creating Dynamic Routes
We can create dynamic routes in Next.js by using square brackets in folder names, like
[id] or [slug], to capture dynamic URL parameters.

Do you have any intuition


how this page.js would be
accessible?

Accessible using url of this format:-

1. http://localhost:3000/posts/abc
2. http://localhost:3000/posts/123

20
Creating Dynamic Routes
We can create dynamic routes in Next.js by using square brackets in folder names, like
[id] or [slug], to capture dynamic URL parameters.
These dynamic values i.e. abc and 123
etc would be captured in page.js inside
the posts folder like this
Accessible using url of this format:-

1. http://localhost:3000/posts/abc
2. http://localhost:3000/posts/123

Passed values are captured by the name of its folder 21


Note
Next.js is a framework build on React.js so all the component based structure remains
the same i.e. we can still build components and assemble in page.js of respective folder or
other components in other or same folder.

Here we have build about.js as


component for page.js inside
posts/

Apart from that we have


components/ folder intended to
be imported by components
anywhere in the project.

22
Setting up Project
Now we can setup a project using Next.js

23
Thinking about routes and folder structure
Design your folder structure the way you want your app’s routes to appear — folders
become paths, and page.js becomes the UI.

You need to think about


routes while making
folders like this:-

24
Challenge: E-Commerce
Plan folder structure for an e-commerce site. Decide which routes are static (e.g., Home,
About) and which are dynamic (e.g., Product, Category), then organize folders
accordingly.

25
Workshop

26
In Class Questions

27
References
1. MDN React Guide: Comprehensive and beginner-friendly documentation for React
https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_fram
eworks/React_getting_started
2. Websites and Tutorials:
a. 📌 w3schools: https://www.w3schools.com/REACT/DEFAULT.ASP
b. 📌codecademy: https://www.codecademy.com/learn/react-101
3. Other Useful Resources
a. 📌 React GitHub Repository: https://github.com/facebook/react
b. 📌 React Patterns & Best Practices: https://reactpatterns.com/

28
Thanks
for
watching!

29
The Ultimate Lecture 22:
React Course
Props Drilling and
Context API
-Narendra Kumar

@newtonschool
1
Prerequisites
● Basic React Knowledge
○ Know how to create functional components.
○ Know how props are passed from parent to child components.
● JavaScript Fundamentals
● React State and Hooks
● Component Tree Visualization

2
Table of Contents
● What are props?
● The prop drilling problem
● Why It's a Problem
● Introducing useContext
● How to Use useContext
● Best Practices & When to Use
● Quick Recap & Mini Challenge

3
What are props?
Passing data between components

4
What is prop?
A prop (short for property) is a way to pass data from a parent component to a child
component in React. Here is an example:-

5
What’s the problem?
Passing props one or two levels down is fine. But as we pass props through many layers, it
becomes hard to track what was sent and where it needs to go.

App

Header

Navigation

Social Media Links

6
What’s the problem?
Passing props one or two levels down is fine. But as we pass props through many layers, it
becomes hard to track what was sent and where it needs to go.

App

Imagine you need to pass some social media


Header links from the App component to the
SocialMedia component.

Navigation But to get there, the data has to go through


Header and Navigation—even though they
don’t need it. Could we avoid this?
SocialMedia Links

7
What’s the problem?
This is a very simple scenario, we can still use props. But imagine there are 10 nested
components and you need to pass data from topmost to bottommost. Would props be
still efficient.

App App
Ok for this Would it be still
scenario. efficient?

Header Header
I don’t think so

...
Navigation ...
.
ReceivingComponent
SocialMedia Links
8
What if you want to pass data to sibling
If you want to pass data between siblings “SocialMedia” and “Links” then you need to
pass data back to their last common parent and that parent would then pass data down.

To achieve that we
App use useContext
Is there any hook
Why not to hold all data in
better way?
one single place and make
Header changes there?

And reflect those changes


Data passed Parent then
to common Navigation pass it to its to its downstream
parent another child components.

SocialMedia Links
9
useContext
Solution to prop drilling

10
What is useContext hook?
The useContext hook is a feature in React that lets you share data between components
without manually passing props through every level.

Instead of passing props,


useContext lets you define
shared data or functions and
makes them available to all child
components using a Provider.

11
Using useContext: A Step-by-Step Guide
There are three main steps involved in using useContext hook:-

Provider

Step 1 Step 2 Step 3

Wrap Consume the


Create
Component Context with
Context
with Provider useContext

Consumer

12
Step 1: Create Context
Use createContext() to create a context that lets you share data without passing props
through every level. We use provider to pass values to downstream components

We have create a context


which is shared here
Note: Downstream
components are
components
enclosed inside the
provider.

Here we are
Here we have declared
using provider
a context, passed it with
to provide value
a provider
13
Step 2: Passing Values
Use createContext() to create a context that lets you share data without passing props
through every level.
Here we passed value to our
context which are accessible App
to downstream components
Parent

Passed values via provider


Child

GrandChild

14
Step 3: Consume Context
We can use the useContext() hook inside any nested component to access the shared
data directly, without passing props
Similar to this
we could have
used values
stored in the
context in any of
the downstream
components.

User holds all the data passed as value


inside provider, to fetch specific values
we need to use dot operator and the
argument name 15
Practical Use Cases
Easy accessibility of context data

16
User Authentication Data
You fetch the logged-in user's info (like name, email, token) in the App component and
need to display the username in a footer component several layers down.

Intermediate
components must Better to use
pass down the user
prop even if they
don’t use it.

17
Other Use Case
There could be similar use cases:-

Use Cases

Theme Switching Shopping Cart Language Setting

18
Workshop

19
In Class Questions

20
References
1. MDN React Guide: Comprehensive and beginner-friendly documentation for React
https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_fram
eworks/React_getting_started
2. Websites and Tutorials:
a. 📌 w3schools: https://www.w3schools.com/REACT/DEFAULT.ASP
b. 📌codecademy: https://www.codecademy.com/learn/react-101
3. Other Useful Resources
a. 📌 React GitHub Repository: https://github.com/facebook/react
b. 📌 React Patterns & Best Practices: https://reactpatterns.com/

21
Thanks
for
watching!
22

You might also like