Web Merge PDF
Web Merge PDF
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.
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
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
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
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.
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.
31
Types of Comments
You can use either single line comments or multi-line comments in javascript.
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?
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.
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
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
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
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.
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.
31
Types of Comments
You can use either single line comments or multi-line comments in javascript.
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?
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
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:-
PRIMITIVES
Sounds overwhelming! Don’t worry
We all find it difficult when we start but it gets easier as we go along
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.
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
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.
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:-
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.
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.
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.
Here we used:-
Types
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.
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
02
Conditional Statements
in Javascript
3
What are conditional statements?
PRIMITIVES
Types of conditional statements
if-else-if
if if-else switch
else
if statement
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
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
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
/
Assignment Operators: Example
Let’s have a look at an example:-
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:-
40
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)
Output:
1
2
Control statement: break (without)
Output:
1
2
3
4
5
Control statement: continue
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:-
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:-
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.
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:
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.
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:-
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:-
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.
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:
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.
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:
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.
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:
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:
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.
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:
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
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”.
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
MyArray true
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.
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:-
C++|Java|Python
join(): Example
Let’s understand join method with few examples:-
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
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.
Memory
num2 stored in
new location
obj2 stored in
same location
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
Types of loops
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.
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:-
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.
Similarly we would
have a look into more
higher order functions
in upcoming slides.
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.
Sum of reduce
1 2 14
3 4
reduce() example 1
Let’s implement that example:-
Do this one by
yourself..
reduce() example 3
Let’s have a look at the solution:-
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).
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.
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.
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.
12
How objects are different from primitives
They differ in the following ways:-
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.
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
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.
Modifying Objects
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.
Caution
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.
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.
Observation #1
Observation #2
Data Retrieval Utility Methods
We have these three methods for retrieving data:-
Methods
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.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:-
Shallow Copy
Deep Copy
holds Contents in
Reference variable 1 28208
memory
Location where
contents are stored
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
Reference variable 1
Updated
Copied to 28208 contents in
memory
Location where
Reference variable 2 contents are stored
Memory: 2432
person
anotherPerson
Reference variable 1
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.
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.
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.
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.
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
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.
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.
9
Ways to implement async programming
There are three main ways to implement asynchronous programming in JavaScript:
Async Programing
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.
13
Executing callbacks after a while
Let’s add a delay of 2000 milliseconds before the callback executes using setTimeout().
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.
Output:
Hello
16
setTimeout: example 1
The same example can be rewritten like this using named functions and arrow
functions.
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
Output:
Interval cleared
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.
26
Build a timer using setTimeout
A quick solution lets you set a one-time reminder to alert you after a delay.
Output:
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:
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.
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.
Alert!
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.
34
Common Causes of Errors
There are several reasons due to which errors can occur:
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:
37
Real Example: try/catch
Let’s use proper fetch function to fetch the data from the server
Output:
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.
4
Pre-discussed: Ways to implement
There are three main ways to implement asynchronous programming in JavaScript:
Async Programing
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.
6
Pre-discussed: Callbacks
Let’s add a delay of 2000 milliseconds before callback executes using setTimeout().
7
Callbacks: Don’t make function async
Callbacks don’t make functions asynchronous!
Output:
Hello, Alice
Goodbye!
8
Callbacks: Handle async operations
Let’s have a look at end to end comparison of performing async operations without
and with callbacks.
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.
11
Challenge with Callbacks
Callbacks facilitate asynchronous operations, but when multiple operations need to be
performed sequentially, they can lead to callback hell.
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.
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.
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()
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()
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
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
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
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.
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.
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.
34
.catch(): Example
It might be possible that error occurred while consuming the promise which can be
caught using the .catch() block.
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.
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.
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
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.
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.
52
Asynchronous Flow in Promises
In promises we chain the tasks using then() and catch() blocks. Hence program is
executed in chain like manner.
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.
Name
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.
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.
4
Pre-discussed: Ways to implement
There are three main ways to implement asynchronous programming in JavaScript:
Async Programing
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.
6
Pre-discussed: Callbacks
Let’s add a delay of 2000 milliseconds before callback executes using setTimeout().
7
Callbacks: Don’t make function async
Callbacks don’t make functions asynchronous!
Output:
Hello, Alice
Goodbye!
8
Callbacks: Handle async operations
Let’s have a look at end to end comparison of performing async operations without
and with callbacks.
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.
11
Challenge with Callbacks
Callbacks facilitate asynchronous operations, but when multiple operations need to be
performed sequentially, they can lead to callback hell.
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.
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.
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()
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()
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
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
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
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.
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.
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.
34
.catch(): Example
It might be possible that error occurred while consuming the promise which can be
caught using the .catch() block.
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.
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.
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
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.
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.
52
Asynchronous Flow in Promises
In promises we chain the tasks using then() and catch() blocks. Hence program is
executed in chain like manner.
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.
Name
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.
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.
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.
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.
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),
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.
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
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
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
.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
Either returns a
response data or
throws an error
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().
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?
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.
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.
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
35
fetch() - PUT method
Similarly we can perform PUT request:-
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:-
39
GraphQL API: Sending Request Query
Instead of fetching everything, you can query only what you need:
40
GraphQL API: Sending Request Query
Instead of fetching everything, you can query only what you need:
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()
…..
43
Handling Errors
There are following types of errors which can be thrown during the execution of a
promise/promise handling.
Errors
44
Promise Rejection
Promise rejection errors occur when a promise is explicitly rejected or if an operation
inside the promise fails.
45
Promise Rejection: Manual rejection
Promise rejection errors occur when a promise is explicitly rejected or if an operation
inside the promise fails.
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.
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.
51
Recovering from errors
Or we can retry by sending one more fetch request to the server:-
52
Recovering from errors
Or else we can graceful show minimal or different content
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
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.
57
Promise.all(): Example
Let’s say one of the promise is not getting resolved.
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.
59
Static Method: Promise.race()
Let’s say first settled promise gets rejected, Promise.race() would also be settled as
rejected.
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.
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.
63
Workshop: Solution
Let’s consume the promise:-
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.
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
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.
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.
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.
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),
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.
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
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.
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
.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
Either returns
response data or
throws an error
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().
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?
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.
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.
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
35
fetch() - PUT method
Similarly we can perform PUT request:-
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()
…..
39
Handling Errors
There are following types of errors which can be thrown during the execution of a
promise/promise handling.
Errors
40
Promise Rejection
Promise rejection errors occur when a promise is explicitly rejected or if an operation
inside the promise fails.
41
Promise Rejection: Manual rejection
Promise rejection errors occur when a promise is explicitly rejected or if an operation
inside the promise fails.
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.
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.
47
Recovering from errors
Or we can retry by sending one more fetch request to the server:-
48
Recovering from errors
Or else we can graceful show minimal or different content
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
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.
53
Promise.all(): Example
Let’s say one of the promise is not getting resolved.
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.
55
Static Method: Promise.race()
Let’s say first settled promise gets rejected, Promise.race() would also be settled as
rejected.
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.
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.
59
Workshop: Solution
Let’s consume the promise:-
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.
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
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:-
72
GraphQL API: Sending Request Query
Instead of fetching everything, you can query only what you need:
73
GraphQL API: Sending Request Query
Instead of fetching everything, you can query only what you need:
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.
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.
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:-
12
Popular websites built on React
The following are few popular websites which uses React:-
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.
Newton Box
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.
19
Project Structure
Here we have two more files:-
20
Project Structure: src folder
Let’s open the src folder and see its contents:-
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.
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.
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
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.
Header Footer
30
Creating Component: Header.jsx
For now we will create components in the same file i.e. App.js:-
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:-
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:-
34
Let’s have a look of it in the browser
Let’s open the browser and see how it looks:-
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.
36
How to Style our Component - Inline?
To write inline styles we use style attribute and write our style inside 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.
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
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! 🐪
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.
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:-
7
Pre-discussed: Including Header in App.js
We can simply import it in App.js file and use it here:
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.
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. 🚀
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
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.
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.
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
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.
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
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
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.
37
Missing Keys in Lists
Including keys in an iterable list makes the React rendering process efficient.
No
errors
after
including key
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.
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.
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!
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.
10
Managing Data in React
Let’s understand how it works:- Initial State
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?
12
Why did it happen?
It happened because React doesn’t track normal variable changes. React only
re-renders when state or props change.
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.
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.
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]
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.
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.
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:-
Setter Function
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:
24
Testing our app: Decrement Button
Let’s try clicking on the ‘Decrement’ button:
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
31
Forms in React
Let’s also add an event on form submission:-
32
Workshop
33
Workshop: Build a ToDo App
Create a To-Do App using React that allows users to add, and display tasks.
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
When user clicks the button, Todo is added to the todos array
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.
4
Recap: Import Files
Let’s dissect each part of our import statement:-
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
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”.
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?
10
Use used promises to handle async ops
We used promises to handle async operations in JS. Here is an example:
11
Use used promises to handle async ops
We used promises to handle async operations in JS. Here is an example:-
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.
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.
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
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.
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…
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.
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.
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.
Header Footer
26
Creating Header.jsx
Here we have created Header component in the separate named Header.jsx:-
Header Component
27
Pre-discussed:Including Header in App.js
We can simply import it in App.js file and use it here:-
28
Recap: Creating Footer Component
Similarly we can create Footer component and use it in inside App like this:-
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.
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
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
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
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:-
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.
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
28
Using Error State to Manage Errors: try/catch
We can achieve same using try/catch instead.
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.
……………..
……………..
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.
This entire
process is called
CleanUp.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:-
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.
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.
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.
……………..
……………..
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.
This entire
process is called
CleanUp.
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.
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:
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.
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.
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.
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.
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
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
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
Perform
Any
Changes
Changes
Efficiently
HEAD BODY
React Code
TITLE H1 Others
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
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.
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.
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
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
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
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
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:
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.
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
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?
21
Popular Component Libraries
There are several component libraries accessible in React environment; few of them are
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:
24
Material UI: An overview
Similarly, you can utilize Material UI; you just need some exploration.
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.
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
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
11
Exploring Project Folder (app)
Let’s explore project folder:-
12
Launching your project
You can launch your project by running this simple command:-
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:-
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.
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
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.
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
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
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?
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.
11
Using useContext: A Step-by-Step Guide
There are three main steps involved in using useContext hook:-
Provider
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
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
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.
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
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