0% found this document useful (0 votes)
52 views233 pages

Javascript

JavaScript was created by Brendan Eich at Netscape in 10 days to enable dynamic web applications, moving beyond static HTML and CSS. It is an interpreted, open-source language that allows for the creation of interactive content and can be used on both the client and server sides through engines like Node.js. Key features include variable scoping, hoisting, and various data types, along with the ability to perform operations using different types of operators.

Uploaded by

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

Javascript

JavaScript was created by Brendan Eich at Netscape in 10 days to enable dynamic web applications, moving beyond static HTML and CSS. It is an interpreted, open-source language that allows for the creation of interactive content and can be used on both the client and server sides through engines like Node.js. Key features include variable scoping, hoisting, and various data types, along with the ability to perform operations using different types of operators.

Uploaded by

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

Javascript

Who created JavaScript?

Brendan Eich when working at NetScape


It was created in 10 days
Why JS was developed ?
 Earlier there was only HTML and CSS were
there to build applications, these
applications were static.
 Static applications are the ones in which
you cannot take in any user’s input and
make some changes in styling or structure
of application, so we needed to make the
applications dynamic.
 Dynamic applications are the ones in
which you can take user’s data and save
his information. And capturing data is
the most important part of the
application development.
History of JS
 In 1990s, at the time of internet when
Microsoft Internet Explorer and Netscape’s
Navigator were getting released.
 One of the Netscape’s developer named Brandan
Eich developed JS in 10 days.
 JS used to known as Mocha , then it used to
get called as Livescript and then finally
Javascript.
 Javascript used to get confused with JAVA,
but on the other hand they have nothing in
common, Javascript is an interpreted language
and Java is a compiler language.
 Because of all this confusion and to maintain
proper standardization in Javascript,
Netscape introduced a body called ECMA
(European Computer Manufacturers Association)
Why should you learn JS
COMPILER INTERPRETER

It takes a single line of a code at a


It takes an entire program at a time.
time.

Compilation is done before Compilation and Execution takes


execution place simultaneously.
Slower because it translates each
Faster because it translates the line and then execution happens
complete code at one go. which at last takes more time than
compiler
It requires memory because it
It does not require any memory.
create object code
Display errors after each line if
Display all errors at the last.
exists.

C, C++ Python, PHPD


What is Javascript ?

Javascript is a scripting language that


enables you to create dynamically updating
content, control multimedia, animate images,
and pretty much everything else.
What is JavaScript ?
JavaScript is an interpreted language It
means it doesn't need a compiler It
executes instructions directly without
compiling. It is platform independence,
dynamic typing The source code is
evaluated just before executing it. It
is open-source and cross-platform
compatible. It is created by
NetScape .It has object-oriented
capabilities
Why do you love JavaScript?
• It is easy to start using

• JavaScript can be used on any platform

• It performs well on every platform

• You can build web, IOT, mobile apps using


JavaScript

• 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
Stages of a Code Execution

Compilation : The stage in which the


complete source code will be
converted into machine language
code.

Execution : In this stage the code will


be executed means all the functions
which are written will be executed.
Stages of a Code Execution
Compilation :
Compilation process
means the code will
be converted into
machine language
(10101101..) code
and make sure that
the source code
follows the correct
syntax, if the
syntax is not
followed then the
error will be
thrown.
JS Engine
 Now to run JS code we need JS engine,
earlier it was believed that JS code can
be run only in browser and only client
side applications can be created.
 So all the browsers are having their own
JS engines to run JS code.
 Later Ryan Dahl wrote some C++ and tried
to run it using JS Engine, and it worked
and we call it Node.JS.
 So JS can be used for client-side
application and server-side application
as well, it just requires JS engine to
run the code.
JS Engine

Google Chrome = V8 Engine Mozilla Firefox = Spider Monkey Engin

Internet Explorer = Chakra


Client side Server side
Add JS to HTML Page

 We can use script tag in <body> tag of HTML


file.
 This script tag should be placed at the end of
body tag means after complete HTML code.
 <script src=“./index.js”></script>
JS Code Execution

Below are the few terminologies which comes


under JS code execution :

 Global Execution Context


 Execution Context
 Call Stack
 Memory Allocation
 Code Execution
JS Code Execution
JS Code Execution
 In the first stage “Memory allocation”, all the
variables will get memory but will not be
initialized means their value will not be given
and it will be undefined, but functions will get
their value or definition at the time of memory
allocation only.

 In the second stage “Code Execution”, variables


will get assigned with their true values and
functions will be executed.
JS Code Execution

var number = 2;
function Square (n) {
var res = n * n;
return res;
}
var newNumber = Square(3);
Your First Hello World Program

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
console.log("Hello World");
</script>
</body>
</html>
Variables

80 marks in history

Percentage of marks(80/100)
Grade she got if(80>75)..Distinction
Print the marks console.log(80)
Variables

var num = 1
var name = “PrepBytes”
var isCapital = true
Variables
Variables are containers
They store data values
For ex: var Variables are containers
They store data values
For ex: var x = 5 Click to add text

5 is the value stored in variable x


In programming, just like in mathematics, we use
variables to hold values
x = 5
5 is the value stored in variable x
In programming, just like in mathematics, we use
variables to hold values
Variables
var message;

Click to add text


Variables
var message;

Click to add text


Primitive Data types

Strings Non - Primitive Data types


Numbers
Boolean Objects

undefined
null
Data types
Click to add text
Non –Primitive Data type

In Js Other than primitive data types everything


are Objects
Click to add text
Click to add text
Variables

Variables can be created in JS using


these:

var
let
const
var vs let vs const
• var declarations are globally scoped or function scoped
while let and const are block scoped.

• var variables can be updated and re-declared within its scope

• let variables can be updated but not re-declared

• const variables can neither be updated nor re-declared.

• Vars are hoisted

• While var and let can be declared without being


initialized, const must be initialized during declaration
var vs let vs const
var vs
let vs
const
Scoping of a Variable
Global Scope = Variables declared in global
scope will be accessible at every point in
the file, even inside a function.

Block Scope= Variables declared in a


specific block like loops, if-else, or
functions, these variables will not be
accessible outside the blocks. It will be
only accessible in the block where they have
been declared.
What are these blocks ??

A block is a piece of code inside a set


of curly braces {} and groups code
statements together.
Global scope

A variable exists inside or outside a


block. If a variable is declared outside
all functions or curly braces ({}), it
exists in the global scope. The global
variables can be accessed by any line of
code in the program, including inside
blocks.
Global scope
Block scope
So far, we’ve seen variables defined with
the var keyword. Var can declare a
variable either in the global or local
scope. The variables that are declared
within the block scope are comparable to
local ones. They are available within the
block that they are defined.

The main difference between the local


scope and block scope is that the block
statements (e.g. if conditions or for
loops), don't create a new scope. So the
var keyword will not have an effect,
because the variables are still in the
Block scope

ES6 introduced block scope by using the let and


const keywords. These two keywords are scoped
within the block which are defined.
Block scope
Hoisting in JS
• In JS each and every variable declared using either var, let
or const gets some memory space.

• If variable is declared using var then it will get memory


space in global scope. So if you will try to access the

variable in this case before initialising it then it will

return “undefined”.

• If variable is declared using either let or const then it will


get memory space in separate scope not in global scope. So if

you will try to access the variable in this case before

initialising it then it will return Reference error saying you

cannot access the variable before initialization.


Hoisting in JS
Hoisting is a default behaviour of javascript
where all the variable and function
declarations are moved on top.
Hoisting in JS
hoistedVariable = 3;
console.log(hoistedVariable); // outputs 3 even
when the variable is declared after it is
initialized
var hoistedVariable;

*Note - Variable initializations are not hoisted, only


variable declarations are hoisted:

var x;
console.log(x); // Outputs
"undefined" since the initialization
of "x" is not hoisted
x = 23;
Conclusion : Hoisting in JS
• It is a concept which says that you should always declare and
initialise all the variables is JS before using them.

• If we will not initiate the variables (means giving or assigning the


value to a variable) before using it , then it will throw errors. So

to avoid such errors we should follow the concept of Hoisting in

JS
Variables naming convention
• Variable names can consist only of letters (a-z),(A-Z) numbers (0-9),
dollar sign symbols ($), and underscores (_)

• Variable names cannot contain any whitespace characters (tabs or


spaces)

• A JavaScript identifier must start with a letter, underscore ( _ ), or


dollar sign ( $ )

• There are several reserved keywords which cannot be used as the


name of a variable

Variable names are case sensitive


Reserved keywords as of

ECMAScript2015 - ES6
Keywords reserved only in strict mode

Keywords reserved only if it is not used in current module

Keywords reserved for future


Type Coercion

Type coercion is the automatic or implicit conversion


of values from one data type to another
Type Coercion
Type Coercion
Type Coercion
Type Coercion
Operators

Arithmetic Operators
Comparison Operators
Bitwise Operators
Increment,Decrement Operators
Logical Operators
Ternary Operators
Comma Operator
Arithmetic Operators

%,- , +,/, *
Arithmetic Operators
Comparison Operators

==, ===, !=, !==, >, <, >=, <=


Comparison Operators
Operators
Comparison Operators
Bitwise Operators

Bitwise And - a&b


Bitwise OR - a|b
Bitwise XOR - a^b
Bitwise NOT - ~a
Left Shift - a << b
Sign Propagating Right Shift - a >> b
Zero fill Right shift - a >>> b
Bitwise Operators
Increment and Decrement Operators

Postfix increment - a++


Prefix increment - ++a

Postfix decrement - a--


Prefix decrement - --a
Increment and Decrement Operators
Logical Operators

&&, ||, !
Logical Operators
Conditional or Ternary Operators

Condition ? Val1 : val2


Conditional or Ternary Operators
Comma Operators

,
Exercise-1
1.Take two numbers and print the addition of that number.
Input:2 5
Output:7

2.Problem:Given a four-digit number N , print its first digit.


Input:4567
Output:4
Decision Making

If it rains, I won’tIfgo
it doesn’t rain ,I will go
Decision Making
You can use if-else statement, if-elif-else statements
when you are having very few conditions to check. If
you have more that 4 conditions than switch statement
will be more preferred.

let weather;
weather = "raining";
if (weather === "raining")
console.log(”I won't go for the party");
else
console.log(”I is will go to the party")
If else
If else
Switch Statement

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
//code block
}
Switch Statement
Switch Statement
LOOPS
Below are the loops available in JS :

 for loop
 for-in loop
 for-of loop
 while
 do-while loop
Loops

labeled statement
break statement
continue statement
Exercise-2
Problem:A school has following grading rule:
1.below 10 and 10-E
2.11-20-D
3.21-30-C
4.31-40-B
5.41-50-A
ask user to enter marks out of 50 and print the grades
using switch statement.

Input:30
Output:C
Exercise-3
Problem:Write a program which takes a number from user
and print the table.
Input:3

Output:
3*1=3
3*2=6
3*3=9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
Functions
In JS, there are 3 ways
to create a function:

1. Regular function
2. Arrow function
3. Function Expression
Function

Function definitions (function declaration, or function


statement)

Function calling / invocation


Function

Function without parameters

Function with parameters and no return

Function with parameters and with return


Function
Function
Function
Excercise-4
1.Create one function with zero parameter having a
console statement

2.Create one Arrow function with zero parameter having


a console statement

3.Create one function which takes three parameter as


first name and last name and age and return the
statement as "A is 99 years old"2.;
Arrow Function
Strings

console.log(name[1]);

console.log(name.charAt(1));

console.log(“PrepBytes”.charAt(1));

console.log(“PrepBytes”[1]);
Strings comparison
let a = 'a'
let b = 'b'
if (a < b) { // true
console.log(a + ' is less than ' + b)
} else if (a > b) {
console.log(a + ' is greater than ' + b)
} else {
console.log(a + ' and ' + b + ' are equal.')
}
More string methods

var name = You will be an amazing developer

let index = name.indexOf(“developer”);

index = name.lastIndexOf(“developer”);

index = name.indexOf(“will”, 10);


Strings concatenation

Var string1 = Prep;

Var string2 = Bytes;

Var string3 = string1 + string2;

Console.log(string3);

Output : PrepBytes
Strings concatenation
Slicing

var name = You will be an amazing developer

var newMessage = name.slice(7,13);

newMessage = name.slice(-7, -13);

newMessage = name.slice(7);

newMessage = name.slice(-7);
Slicing
Substring
Substring does not support negative index
For substr second parameter is length

Var name = You will be an amazing developer

Var newMessage = name.substr(7,13);

newMessage = name.substring(7);
Substring
Replace
var name = You will be an amazing developer

name.replace(‘ ’, ‘-’);

name.replaceAll(‘ ’, ‘-’)

name.trim();
Replace
split

var name = You will be an amazing developer

var nameList = name.split(“ ”);


split
Word.length

var newMessage = PrepBytes;


console.log(newMessage.length);

Output = 9
Word.length
Strings comparison
let a = 'a'
let b = 'b'
if (a < b) { // true
console.log(a + ' is less than ' + b)
} else if (a > b) {
console.log(a + ' is greater than ' + b)
} else {
console.log(a + ' and ' + b + ' are equal.')
}
Excercises-5
Problem:You are provided with a string you have to slice the
name from the string.
and print the sliced string.

(using slice)

Input:Hi Prepbytes

Output:Prepbytes

I am utkarsh
Regular Expression - RegExp in JS

Regular Expression are patterns used to match


character combinations in string

 ^ : It matches the position just before the first


character of the string.
 $ : It matches the position just after the last
character of the string.
 . : matches a single character. Does not matter
what character it is, except newline
 * : matches preceding match zero or more times.
Arrays
An array is an ordered list of values that you refer to
with a name and an index.

An array is an ordered list of values stored in continuous


memory location.

11 34 45 56 78 89 90 54 67 78 54 32
Arrays

let arr = new Array(element0, element1,……,elementN)


let arr = Array(element0, element1…elementN)
let arr = [element1, element2, element3]

let arr = new Array(arrayLength)


let arr = Array(arrayLength)
let arr = []
Arrays
Arrays
Arrays
Arrays
Arrays
Arrays
Arrays
Arrays
Filter
Array
Arrays
Arrays
Arrays Methods

let myArr = [1,2,3]


myArr.concat(5,6,7)

let myArr = [“Hi”,”How”,”Are”,“You”]


myArr.join(“-”)
Arrays Methods

let myArr = [1,2,3]

myArr.push(7)
myArr.pop()

myArr.shift()
myArr.unshift(‘4’,’5’)
Arrays Methods

let myArr = [1,2,3,4,5,6,3]

myArr.slice(1,3)
myArr.splice(1,3,’a’,’b’,’c’,’d’)

myArr.reverse()
myArr.sort()

myArr.indexOf(3)
myArr.lastIndexOf(3)
For each

let myArr = [“Hi”,”How”,”Are”,“You”]

myArr.forEach(function(item) {
console.log(item)
})

myArr.map((item)=> {
console.log(item)
})
Filter

let myArr = [“Hi”,”How”,”Are”,“You”]

let myNewArr = myArr.filter((item)=>


return typeof item == String)
Some and Every

yArr = [“Hi”,”How”,”Are”,“You”]
yNewArr = myArr.filter((item)=> return typeof item ==
Maps
let sayings = new Map()
sayings.set(‘dog’, ‘woof')
Saying.set(‘cat’, ‘meow’)
sayings.size
sayings.get(‘dog’)
sayings.get(‘fox’)
sayings.has(‘fox’)
sayings.delete(‘fox’)
saying.size

for(let[key,value] of sayings) {
console.log(key + ' goes ' + value);
}
Maps

let sayings = new Map()


sayings.set(‘dog’, ‘woof')
Saying.set(‘cat’, ‘meow’)
sayings.size
sayings[‘dog’]

map.forEach()
Sets

let mySet = new Set();


myset.add(1)

for(let[key,value] of sayings) {
console.log(key + ' goes ' + value);
}
Exercise-6
Problem: you are provided an array of integer you have to print
the sum of array.

Input:
1234

Output:10
10
Javascript Objects
What are Objects?

object is a collection of related data and/or functionality


hich usually consists of several variables and functions —
ich are called properties and methods when they are inside obje
Objects
var user= {
name: ”Rahul”,
profession: “Teacher”,
hobbies: [“Reading”, “Dancing”]
}

How to access object keys or attributes

user.name gives “Rahul”


user.profession gives “Teacher”
Objects
var Rahul= {
name: ”Rahul”,
profession: “Teacher”,
hobbies: [“Reading”, “Dancing”],
bio: function() {
console.log(`Hi! I am ${name}, my profession i
${profession})
}
}
Objects
Objects
What are Object Literals?

tializer is a comma-delimited list of zero or more pai

const a = 'rahul';
const b = 24;
const c = {};
const object = { name: a, age: b, personalInfo: c };
Objects using Constructor
In Javascript, we can create objects using function
constructor and class constructor.

Both class and function constructors returns an


empty object.

“this” keyword will be associated with the new


object.

There will be one prototype object will also be


added to this new object. This prototype object
contains the information that if newly created object
is created by class constructor or function
constructor.
Create objects using Function Constructor

function Car(make, model, year) {


this.make = make;
this.model = model;
this.year = year;
}

const car1 = new Car('Eagle', 'Talon TSi', 1993);


Create objects using Class Constructor

class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}

const square = new Rectangle(10,10);


Object.keys

const user = {
a: 'student',
b: 42,
};

console.log(Object.keys(user));
// expected output: Array ["a", "b"]
Object.values

const user = {
a: 'student',
b: 24,
};

console.log(Object.values(user));
// expected output: Array ["student", 24]
Exercise-7

Question : Create a object using function and class


constructor both, and give two properties to it name
and age.
Spread Operator in JS
This operator allows an iterable such as an array
expression or string where zero or more arguments
for function calls are expected or an object
expression

const str = "abc"


console.log(…str);

Output : “a” “b” “c”


Spread Operator in JS
First class functions in JS
Functions which gets treated as a variable. It can be
passed as an argument to other functions, can be
returned by another function and can be assigned
as a value to a variable.

const foo = function() {


console.log(“Hello World”);
}
foo();

O/P : Hello World


First class functions in JS
Higher order functions in JS
Functions which receives another function as an
argument or returns another function.

const foo = function() {


return function(){
console.log(“Hello World”);
}
}
foo()();

O/P : Hello World


Higher order functions in JS
Call back functions in JS
Call back functions in JS
Call back functions in JS
Call back functions in JS
Call back functions in JS
Call back functions in JS
Call back functions in JS
Call back functions in JS
Why we need Call back functions
Exercise-8

Write one example explaining how you


can write a callback function ?
Asynchronous
Asynchronous
Asynchronous
Asynchronous
Asynchronous
Asynchronous
API
API
API
API
API
API
API
API
Prototypes in JS

Prototypes are the mechanism by which Javascript


objects inherit features from one another.

__proto__ object will be created inside the object


which will refer to the Prototype of its class
constructor or function constructor whenever an
object will be created.

Using prototype property we can also add more


elements to an object which will be accessible by
other objects also(the objects which will be created
by same function or class constructor).
Prototypes in JS & Prototype Chaining
Inheritance in JS
A class created with a class inheritance inherits all
the properties from other class.

Output :

My name is
PrepBuddy
Closures
A closure gives access to variables or other
properties of outer function or parent to
inner function or child function by creating
a lexical environment.

function test() {

var name = 'Prepbytes'; // name is a local variable defined inside

test

function showName() { // showName() is the inner function, a closure

console.log(name); // use variable declared in the parent function

showName();

test();
Event Loop
The event loop has one
simple job : to
monitor the call stack
and callback queue. If
the call stack is
empty, the event loop
will take the first
item from the callback
queue and will push it
to call stack, which
will effectively runs
it
Event Loop
What is DOM?
The Document Object Model (DOM) is the data
representation of the objects that comprise the
structure and content of a document on the web.

It represents the page so that programs can


change the document structure, style, and
content. The DOM represents the document
as objects. That way, languages like Javascript
can connect to the page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1>Javsacript</h1>
<button>Click Me</button>
<ul>
DOM?
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head> head meta
<body>
html h1
<h1>JavaScript</h1>
<button>Click Me</button> body button li
<ul>
<li>Item 1</li> ul li
<li>Item 2</li>
li
<li>Item 3</li>
</ul>
</body>
</html>
DOM functions

Finding the existing HTML elements from DOM

 Find an element by its id attribute :


document.getElementById(id)

 Find an element by its tag name :(div, span)


document.getElementsByTagName(name)

 Find an element by its class attribute :


document.getElementsByClassName(name)
DOM functions
Changing the html elements value :

 element.innerHTML : Changes inner html of an


element

 element.style.property : changes the style of


an html element

 element.getAttribute(“id”) : gives the


attribute value of element

 element.setAttribute(“id”,”test”) : set a new


attribute or existing with the given value
DOM functions - Adding Dynamic HTML

Adding dynamic html elements in DOM:

 document.createElement(element) : create an
HTML element

 document.appendChild(element) : add an HTML


element
EXERCISE-9

<h1>Hello </h1>

Change the heading from "Hello" to "Hello World"


using DOM functions
jQuery

It is a javascript library which simplifies DOM


manipulation , event handling and animation in
HTML. It’s most important feature is Ajax.

Selectors :
1. By class name of element = .classname
2. By id of the element = #id
3. By tag name of element = tag
4. By this keyword = this
jQuery Event handlers

Mouse Events Keyboard Events Form Events Document/Window


Events

click keypress submit load

dblclick keydown change resize

mouseenter keyup focus scroll

mouseleave blur unload


jQuery - Ajax

Ajax allows you to update the DOM or the


webpage without reloading the page. Means
you can get the data from the server and
display it on the page without reloading it.
jQuery - Ajax
jQuery - Ajax
jQuery - Ajax
jQuery - Ajax
jQuery - Ajax
jQuery - Ajax
jQuery - Ajax
jQuery - Ajax
Call, Apply and Bind in JS - Call

Call invokes the function and allows you to pass


in arguments one by one.

var person1 = {firstName: 'Prepbytes', lastName: 'Students'};

function test(greeting, year) {

console.log(greeting + ' ' + this.firstName + ' ' + this.lastName + '


' + year);

test.call(person1, 'Hello'); // Hello Prepbytes Students 2021


Call, Apply and Bind in JS- Apply
Apply invokes the function and allows you to pass
in arguments as an array.

var person1 = {firstName: 'Prepbytes', lastName: 'Students'};

function test(greeting, year) {

console.log(greeting + ' ' + this.firstName + ' ' + this.lastName + '


' + year);

test.apply(person1, [‘Hello’, 2021]); // Hello Prepbytes Students


2021
Call, Apply and Bind in JS - Bind

Bind returns a new function, allowing you to pass


in a this array and any number of arguments.

var person1 = {firstName: 'Prepbytes', lastName: 'Students'};

function test(greeting, year) {

console.log(greeting + ' ' + this.firstName + ' ' + this.lastName + '


' + year);

var user = test.bind(person1);

user(“Hello”,2021) // Hello Prepbytes Students 2021


Callbacks in JS

Callback function is a function which gets passed as


an argument to another function , so that we can
achieve this that callback function should be called
only after the execution of main function.
Promises in JS
The Promise object represents the eventual
completion or failure of an asynchronous operation
and its resulting value.

It takes in two parameters resolve and reject , if we


are getting success response then we will use
resolve to give response, if error comes then we will
use reject to give error.

It provides two functions .then and .catch. If you


want to access response use .then, if you want to
handle error use .catch function.
Promises in JS
Promises in JS
Promises in JS
Promises in JS
Promises in JS
Promises in JS
Promises in JS
Promises in JS
Promises, async, await in JS

async function try() {


let myPromise = new Promise(function(resolve, reject) {
resolve(“Hello World");
});
const result = await myPromise;
return result;
}

try();
Async and Await in JS
An async keyword will be added to a function when
you want that function to perform in a
asynchronous way in JS.

For this asynchronous behaviour we have to write


await keyword in the line where we want the code
to hold.

Note : If async keyword is not added in the function


then we cannot write await in that function.
Debouncing and Throttling in JS
These two techniques are used to limit the number
of times a function can execute.

Normally its developer who decide how and when


the functions should be called, but with event
listeners this job becomes difficult. Example: If
we have an event listener that on maximising and
minimising the screen we are calling a function
then this function will get called a lot of times
if the user will keep on increase and decrease
the screen size.
Debouncing and Throttling in JS

Throttling : It is technique in which no matter


how many times the user fires the event, the
attached function will be executed only once in a
given time interval.

Debouncing : In this technique no matter how many


times user fires the event, the attached function
will be executed only after the specified time
once the user stops firing the event.
Event Listeners

 An event listener is a function applied on


any HTML element.
 Event listener takes minimum two parameters.
 First parameter is event name like click,
mouseout, mousemove, resize
 Second parameter will be the function which
needs to be executed after the event has
happened.
 addEventListener, removeEventListener
Event Listeners
Example : addEventListener

document.getElementById(“submitBtn")
.addEventListener(“click”,function(){alert(“Hello World !!”)});

Example : removeEventListener

document.getElementById(“submitBtn")
.removeEventListener(“click”,function(){alert(“Hello World !!”)});
ES6 v/s ES5

 New variable declaration ways got added like let


and const in ES6 , earlier in ES5 we had only var.
 In ES6, we have got arrow functions which was
not present in ES5.
 Spread operator which gets used while working
with objects also got added in ES6.
 New primitive datatype got added known as
“symbol” Ex: var user = Symbol();
Storage in JS : Local, Session and Cookies
Cookies :

 Cookies stores very small amount of data.


 This data can be sent back to the server with
the server calls
 This data’s expiration can be set from either
client or server side
 They are mostly used by server side.
 They are accessible from any window and tab
 Example : JWT Tokens
Storage in JS : Local, Session and Cookies

Local Storage :

 It stores very large amount of data.


 It has no expiration data and store data in
key-value pair.
 This data can never be accessed by server.
 It can be accessible from any window.
 Example : User credentials
Storage in JS : Local, Session and Cookies

Session Storage :

 It stores very large amount of data.


 It has no expiration data and store data in
key-value pair.
 This data can never be accessed by server.
 It cannot be accessible by every window,
although can be accessible in the same tab.
 Example : Banking
Type Error, Syntax Error, Reference Error

Reference Error : It occurs when you try to use a


variable that does not exist in the code at all.

Example : var a = 10;


console.log(b);

Output : ReferenceError : b is not defined.


Type Error, Syntax Error, Reference Error
Type Error : It occurs when you try to use a
variable that does exist in the code, but the
operation you are trying to perform is not valid.

Example : var a = 10;


console.log(a());
const b = 20;
B = 30

Output : TypeError : a is not a function. B


Assignment to constant variable.
Type Error, Syntax Error, Reference Error

Syntax Error : These errors are detected while


compiling or parsing the source code. These
errors are human made errors

Example : If you have not closed any curly


braces{ } while defining the function.

You might also like