0% found this document useful (0 votes)
16 views130 pages

Java Script Road Map

this is the lecture notes of java script.It is useful for beginners

Uploaded by

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

Java Script Road Map

this is the lecture notes of java script.It is useful for beginners

Uploaded by

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

Java script

road map
Basic

• What is Java Script & Its features • Scope

• Variables in JS • Objects

• Data types • Functions

• Operators • Form Validations


Topics to
learn • Conditional &Control statements • DOM Manipulation

• Loops • Events

• Data structures • BOM Elements


Advanced

• Prototyping

• Proto type Inheritance

• Call backs

• IIFE
Topics to • Promises
learn
• Ajax

• Async Await

• Closures

• OPPs Concepts

• JSON
Variables in
Java script
What is variable
How to declare variable
Variables
in js Rules to name a variable
How to create variable :

• var
• let
• const
Variables
in js
Rules for variable names:

• Variable names contain only letters(a-z,A-Z),digits (0-9),_, $

• Should start with letters(a-z,A-Z) or _

Variables • Variable names are case sensitive


in js
• Camel Case is a convention to name variables
Data types in
Java script
primitive Special

• Number • Undefined
• String • Null
• Boolean

Data types
in Js Composite
• Array
• Object
Operators in
Java script
Arithmetic Operators Type Operators

Comparison Operators Bitwise Operators

Operators Logical Operators Ternary Operators


in Js
Assignment Operators
Arithmetic Operators

• Add 2+4→6

• Subtract 2 - 4 → -2

Operators • Multiply 2*4→8


in Js
• Divide 2 / 4 → 0.5

• Modulus 5 % 2 → 1

• Negate -(5) → -5
Comparision Operators

• a == b True if a and b are the same

• a != b True if a and b are not the same

Operators • a>b True if a is greater than b


in Js
• a >= b True if a is greater than or equal to b

• a<b True if a is less than b

• a <= b True if a is less than or equal to b


Comparison Operators

Ex:

if ( x != 0 )
Operators result = y / x;
in Js else
result = “not defined”;
Logical Operators

a && b AND True if both are true

a || b OR True of either or both are true


Operators
in Js !a NOT True if a is false
Assignment Operators

= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
Operators %= x %= y x=x%y
in Js <<= x <<= y x = x << y
>>= x >>= y x = x >> y
>>>= x >>>= y x = x >>> y
&= x &= y x=x&y
^= x ^= y x=x^y
|= x |= y x=x|y
**= x **= y x = x ** y
Bitwise Operators

Operator Description Example Same as Result Decimal

& AND 5&1 0101 & 0001 0001 1


| OR 5|1 0101 | 0001 0101 5
~ NOT ~5 ~0101 1010 10
^ XOR 5^1 0101 ^ 0001 0100 4
<< Zero fill left shift 5 << 1 0101 << 1 1010 10
>> Signed right shift 5 >> 1 0101 >> 1 0010 2
>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2
Ternary Operator
in
Java script
Syntax

condition ? expression_1 : expression_2;

Ex: big = a>b ? a : b;


Ternary Operator
in Js
Conditional Statements
in
Java script
Types of control statements: Conditional statements
Loops/iterative statements
Types of conditional statements:
1. if statement
2. if-else statement
Conditional statements
in Js 3. if-else if - else statement

4. Switch statement
Syntax of if statement

if(condition){

statement 1
statement 2
Conditional statements .
in Js .
.
statement n

}
Syntax of if –else statement
if(condition){

statement 1
statement 2
.
.
.
statement n
Conditional statements
}
in Js
else{
statement 1
statement 2
.
.
.
statement n

}
Syntax of if-else-if statement :

if(condition 1 is true) {
// code is executed

Conditional statements else if (condition 2 is true) {


in Js
// code is executed
}

else {
// code is executed
}
Syntax of switch statement

switch (expression) {

case choice1:
run this code
break;
Conditional statements
case choice2:
in Js run this code instead
break;

default:
no case matches run this code

}
Loops
in
Java script
Why loops(iterative statements) are needed:

• Time will be saved

Loops • Code length will be reduced


in Js
• Readability increases
Types of loops :
for loop

while loop

do-while -loop
Loops
in Js
for-in-loop

for-of-loop
Syntax of for loop :

for(initialization; condition; increment) {

// Code to be executed

Loops }
in Js
Syntax of -while loop :

do {

// Code to be executed

}
Loops
in Js while(condition);
Syntax of do-while loop :

while(condition) {

// Code to be executed
Loops
in Js }
for in vs for of
loops in
Java script
Functions
in
Java script
Topics:

• What is function

• Why functions

• How to create functions


Functions
in JS • How to call function

• What is function expresion


What is Function:

A block of code written to do a particular task

What is Block:
Anything that enclosed between { }

Functions Ex: {

in JS statement 1 ;

statement 2 ;

statement n ;

}
How to create function/Function definition:
function functionName(parameter1,parameter2 …parameter n) {

body

return value;

Functions ***return & parameters are optional***


in JS
Ex: function sum(num1,num2) {

var result = num1+num2

return result;

}
How to call functions:

functionName(parameters)

Ex: sum(7,8)

Functions
in JS
What is function expression:
Assigning function to a variable
Ex:
add = function sum(num1,num2) {

var result = num1+num2

Functions return result;


in JS
}

add(7,8) => 15
sum(7,8) => Error
Types of Functions
in
Java script
Types:
• Named functions

• Anonymous function

• Immediately Invoked function expression(IIFE)

Functions • Arrow function


in JS
Named function:

function functionName(parameter1,parameter2 …parameter n) {

body

return value;

Functions
in JS Ex: function sum(num1,num2) {

var result = num1+num2

return result;

}
Anonymous function:
function (parameter1,parameter2 …parameter n) {

body

return value;

Ex: function (num1,num2) {


Functions
in JS var result = num1+num2

return result;

***we cannot write anonymous function directly***


***we have to assign it to a variable***
Anonymous function:

Sum = function (num1,num2) {

var result = num1+num2

return result;

Functions }
in JS
IIFE:
When we want to execute a function immediately where they
Created,IIFE used.

Syntax: (function definition) ( );


(

Ex: function product (num1,num2) {


Functions
var result = num1*num2
in JS
return result;

) ( 6,8 );
Arrow function:

var any name = (parameter1,parameter2 …parameter n) =>{

body

return value;

Ex: var product = (num1,num2) => {

Functions var result = num1*num2


in JS return result;

Calling: product(5,8)
Arrow function forms :

1. If only one statement in function body

var product = (num1,num2) => num1*num2

2. If only one parameter

var cube = num1 => num1*num1*num1

Functions var cube = (num1 )=> num1*num1*num1


in JS
var cube = (num1 )=> { return num1*num1*num1 }

Calling: cube(5)
Arrow function forms :

3. If no argument

Var greet = ( ) => console.log(“Good Morning");

Var greet = _ => console.log(“Good Morning");

Functions Calling: greet( )


in JS
Default and Rest
parameters in
Java script
parameters

Function definition:
function product(num1,num2) {

var result = num1*num2

Function return result;


}
parameters
in JS
Function call: product(8,4) ->32

product(8) -> ?
Default parameters:
function product(num1,num2=1) {

var result = num1*num2

return result;
}
Functions
in JS Sum(8) -> 8

Sum(8,7) -> 56

Sum(8,7,9) -> 56
Rest parameters:
We can make function to accept unspecified number of parameters
Rest parameter
function product(num1=1,num2=1, …arr) {

var result = num1*num2

return result;
Functions }
in JS

***Use … before rest parameter ***


Rest parameters:

function product(num1=1,num2=1, …arr) {

var result = num1*num2

for (num of arr){

result = result*num
Functions
in JS }

return result;
}
forEach in
Java script
For every element present inside array the specified function
will be executed.

Syntax :
arr.forEach (function funName(currentItem,index,arr)) {

//code here

});
forEach
in JS
currentItem :Required

Index : optional

arr : optional
For every element present inside array the specified function
will be executed.

Syntax : arr.forEach (functionName);

arr.forEach (test);

forEach function test(item, index, arr) {

in JS code

}
Objects in
Java script
Object:
• object is collection of elements in the form of properties and

methods.
• Property is a key-value pair.

Ex: Var user1 = {


name:‘xyz',
Objects email: xyz@gmail.com,
in JS mobile: 9898987898 ,
login : function (){
console.log(“login success”)
}
};
Ways to create object :
1.Object Literal

2.Using a new keyword with Object constructor

3.Using a new keyword with a constructor function


Objects 4.Object.create() method
in JS
5.Classes
1. Using Object Literal :
let movie1 = { } -> Create an empty Object

let movie = { ->Object with properties (key: value pairs)

name: “RRR"

Create object release : 2021


in JS director : “Rajamouli"

}
How to access object values :
We can access values by using keys in 2 ways

1. obj["key"] -> quotes are mandatory

Ex: movie[“name"] ->valid

movie[name] ->Invalid

Objects
in JS 2. obj.key

Ex: movie.name
How to add new properties to object:
We can add properties by using keys in 2 ways

1. obj["key"] = value

Ex: movie[“budget"] = “400 crores”

Create object
2. obj.key = value
in JS

Ex: movie.budget =“400 crores”


How to update values of object :
We can update values by using keys in 2 ways

1. obj["key"] = value

Ex: movie[“budget"] = “500 crores”

Create object
2. obj.key = value
in JS

Ex: movie.budget =“500 crores”


2. Using new Operator Object Constructer:

let movie1= new Object();

movie1 .name = “RRR”;

movie1 .director = “Rajamouli”;


Create object
in JS
3. Using new Operator with Constructer function:
Step1: create constructor function :

function user(name, age,place) {


this.name = name;
this.age = age;
this.place = place

}
Create object
in JS Step2: create object with constructor function call :

let movie1= new movie(“abc", 25,”Hyderabad”);


4. Object.create method:
let movie2 = Object.create(movie);

let movie3 = Object.create(movie, {


name: {
value: “RRR

Create object },
in JS Music: {
value: “Keeravani”
}
})
Console Methods
in
Java script
• console.log() • console.count()

• console.info() • console.countreset()

• console.warn() • console.time()

Console Methods • console.error() • console. Timelog()


in JS
• console.table() • console.timeend()

• console.clear() • console.group()

• console.assert() • console.groupend()
DOM
in
Java script
What is DOM

• DOM : Document Object Model

• By using HTML DOM JavaScript can access, change or remove any


elements of HTML document and also can create new elements at

DOM any position.


in JS
• When a webpage loaded, browser create DOM of webpage
Document Object has • Properties

• Methods

Using this document object properties& methods we can

• Select HTML elements

Document • Modify HTML elements


Object in JS
• Remove/delete HTML elements

• Create HTML elements

• Add/Remove /Change styles to HTML elements


Methods to select HTML Elements :
1.document.getElementById(“idname”)
Returns element with the specified id

2. document.getElementsByClassName(“classname”)
Returns list of all elements belongs to the specified class

3. document.getElementsByTagName(“tagname”)
Returns list of all elements with the specified tag

4. document.querySelector(“.class/#id/tagname”)
Returns the first object matching CSS style selector

5. document.querySelectorAll(“.class/#id/tagname”) )
Returns all objects Matches the CSS Style Selector
DOM properties to select HTML Elements :

• document.body

• document.head

• document.title

• document.anchors

• document.forms

• document.images

• document.scripts
DOM Manipulation
in
Java script
<html >

<head>
<title>My HTML Document</title>
</head>

<body>

<h1>Heading</h1>
<div id="div1">
<p>P Tag 1</p>
</div>
<div id="div1">
<p class="p2">P Tag 2</p>
</div>
</body>

</html>
Topics :

• How to create HTML elements

• How to set content to element

• How to append a new element

• How to insert an element before another element


DOM Manipulation
• How to remove an element
in JS
• How to remove child element

• How t0 replace an element


Add/change styles
in
Java script
Topics :

• How to change style of element

• How to get attribute value of an element

CSS Styling
• How to set/change attribute of an element
in JS
Modal Windows in
Java script
3 modal windows :

• Alert – to show message to user

• Prompt- To take some input from user

Modal windows
Java script • Confirm – to get confirmation from user
Events
& Event handling in
Java script
Topics :

• What is event & types of events in JS

• What is event handler

Events
& Event handling in • Ways to handle events in JS
Java script
Event
• Event is nothing but an action

• In webpage also what ever user do everything is an event

Who generates events:


• user –> keypress,scroll,focus,….

Events & • System ->load,error,abort..


Event handling in
Java script Types of user generated events:
• Browser specific events ->scrollup/down resize browser….

• DOM /web page specific events -> click,hover,focus ….

Event handler is function we write to run when an event happens


Commonly used events in JavaScript:

Mouse Events Keyboard Events Focus events


click Key down
focus
double click Key up
blur
mouseover Key press
focusin
mouseout
focusout
Events & mouse move
Event handling in
Java script Form Events

submit
reset
change
Ways to handle events:

• Inline event handlers(using event attributes in HTML)


Ex: <button onclick=“JavaScript code">

• using event properties in JavaScript

Ex: let btn =document.getElementById(‘b1’)


Events &
Event handling in button.onclick = function name/anonymous function
Java script

• using addEventListener() method in JavaScript

Ex: let btn =document.getElementById(‘b1’)

button.addEventListener(eventname,function name/anonymous fun)


Higher order
functions in
Java script
• Higher order function is a function that receives another

function as argument or return another function or both

Example of receiving another function as argument:

function first(fun){
Higher order
fun()
functions in
Java script }

function second(){
console.log("This is second function")
}

first(second)
Example of returning a function:

function first(){

return second

function second(){
Higher order console.log("This is second function")
functions in }
Java script
let res = first()

res()
This keyword
in
Java script
Value of this keyword outside a function /object

Value of this keyword inside a regular function

Value of this keyword inside a method


This
in Js Value of this keyword inside event handler

Value of this keyword inside a function in strict mode


Math Object
in
Java script
Methods of Math Object

• ceil()
• Sign()
• floor()
• abs()
• trunc()
• sqrt()
• random()
• pow()
Math Object • exp()
• max()
• log()
• min()
• log2()
• round()
• log10()
String Methods in
Java script
Window Object in
Java script
properties of Window Object

• document

• innerWidth

• outerWidth

• innerHeigth

Window Object • outerHeight

• location

• closed

• Name

• navigator
Open() & close()
browser window
with sJava script
Methods of Window Object
• Open()

• Close()

• moveBy()

• moveT0()

• alert()
Window Object • Prompt()

• confirm()

• reSizeTo()

• reSizeBy()

• print()
open() Method syntax:

Window.open(URL , name/target , specifications)

Window Object • width


• _blank
• height
• _self
• left
• _parent
• Top
• _top
• Resizable

• scrollable
moveTo() & moveBy()
resize()
browser window
with Java script
• moveTo()

• moveBy()

Window Object • reSizeTo()

• reSizeBy()
Asynchronous
Java script
AJAX
• AJAX – Asynchronous JavaScript And XML

• AJAX helps in fetching data asynchronously from a remote web server

• Data loaded by AJAX call is done asynchronously with out page refresh

AJAX • Web server will send response which contains data that we have requested

• Data can be of any format like JSON,XML …

• Initially servers used to send data in XML format


My Website
Request(GET/POST..)

AJAX Response

Load
• In JavaScript we have to use XMLHttpRequest object to make AJAX call

to exchange data from webserver.

• AJAX request can be send to sever in with 3 steps

1. Create XMLHttpRequest object


AJAX
Ex: let xhr = new XMLHttpRequest()

2. Create request with that object open() method


Syntax : open(method,url,async,username,password)

3. Send the request using send() method


AJAX
My Website
Request(GET/POST..)

AJAX Response

Load
Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
open(method, url, async, user, psw) Specifies the request

method: the request type GET or POST


url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password
Methods
send() Sends the request to the server
Used for GET requests
send(string) Sends the request to the server.
Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be sent

abort() Cancels the current request


getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
Property Description
onload when the request is complete and the response is fully downloaded.

onreadystatechange Defines a function to be called when the readyState property changes

onprogress triggers periodically while the response is being downloaded, reports how much
has been downloaded.

readyState Holds the status of the XMLHttpRequest.


0: request not initialized
1: server connection established
2: request received
3: processing request
Properties 4: request finished and response is ready

responseText Returns the response data as a string

responseXML Returns the response data as XML data

status Returns the status-number of a request


200: "OK"
403: "Forbidden"
404: "Not Found"

statusText Returns the status-text ("OK" or "Not Found")


What is
Call Back Hell
Promises
In JavaScript
• Promise is an object
let p = new promise()

• Promise object takes a callback function

let p = new promise( function(){})

Promise
• This object returns some data either success data or error

information.

let p = new promise( function(resolve,reject){

})
• States of promise
Pending

fulfilled

rejected

Promise
Fetch API
In JavaScript
• fetch() is a method of browser window Object which helps to make AJAX call

Syntax : fetch ( url,[options] )

options: Optional parameters like method, headers…

• fetch() method returns a promise

• So to use the data from server we have to use then() method of


Fetch API
promise return by fetch() method

let promise = fetch("https://restcountries.com/v3.1/name/india")

promise.then(function(response){
console.log(response)

})
Prototype & _ _proto_ _
In JavaScript
function movie(name,director){
this.moviename=name
this.director = director
this.getGetails = function(){
console.log("Director of ",this.moviename,":",this.director)
}
}

Prototype
pushpa RRR
Sukumar RajaMouli

getDetails() getDetails()

movie1 = new movie("Pushpa","Sukumar") movie2 = new movie("RRR","Rajamouli")


• Regular expression is a sequence of characters, helps to create a search

pattern

Ways to create regular expressions:


1. RegExp literal notation

Syntax : /pattern/[flags]
Regular
Ex: /hello/
Expressions
/^[0-9]{10}$/
2. Using RegExp Constructor function

Syntax : new RegExp(‘pattern’,[flags])

Ex: new RegExp(“hello”)

new RegExp(“^[0-9]{10}$”)
Regular Expressions
In JavaScript
• Regular expression is a sequence of characters, helps to create a search

pattern

Ways to create regular expressions:


1. RegExp literal notation

Syntax : /pattern/[flags]
Regular
Ex: /hello/
Expressions
/^[0-9]{10}$/
2. Using RegExp Constructor function

Syntax : new RegExp(‘pattern’,[flags])

Ex: new RegExp(“hello”)

new RegExp(“^[0-9]{10}$”)
Brackets:

Expression Description Example

[……..] Any one character between the [a89] => a or 8 or 9


brackets.

[^……] Any one character not between [a89] => everything except a , 8 and 9
the brackets
[0-9] Any number from 0 -9 0 /1/2 …./9

[a –z ] Any lower case alphabet a/ b/ c/ …………../z

[A - Z] Any Upper case alphabet A/B/…………./Z

[a-Z] Any lower case or uppercase . a/ b/ c/ …………../z , A/B/…………./Z


Quantifiers: For specifying the number of occurrences of a character

Quantifier Description Example

* Match zero or more times. Bm* => "B", "Bm", "Bmm", "Bmmm", and so on…

+ Match one or more times. j+ => “j", “jj", “jjj“ ….

? Match zero or one time. bS? => “b" or “bs", but not “bss” ….

{n} Match exactly n times. Jab{5} . => “Jabbbbb"

{ n ,} Match at least n times. mb{3, } => “mbbb", “mbbbb“ …..

{n,m} Match from n to m times. br{3,5}a => “brrrr“ or “brrrrr“ or “brrrrrr“


Split() & join()
In JavaScript
Split():It divides a string into an array of substrings based on separator

let movies = "RRR BhemlaNayak Pushpa Sarainodu";

console.log(movies.split(' '))

Output: ['RRR', 'BhemlaNayak', 'Pushpa', 'Sarainodu']

Syntax: string.split(separator, limit)

console.log(movies.split(' ', 2))

Output: ['RRR', 'BhemlaNayak']


Join(): It concatenate all elements of an array & returns new string

separated by separator
let movies = ['RRR', 'BhemlaNayak', 'Pushpa', 'Sarainodu'];

console.log(movies.join('-'))

Output: "RRR-BhemlaNayak-Pushpa-Sarainodu"

Syntax: array.join(separator)

console.log(movies.join())

Output: "RRR,BhemlaNayak,Pushpa,Sarainodu"
Multi dimensional
Arrays
In JavaScript
let product = [1,"Samsung Galaxy A53",30000]

Multi 1 Samsung Galaxy A53 30000


dimensional
array 0 1 2
let product = [1,"Samsung Galaxy A53",30000]

1 Samsung Galaxy A53 30000

Multi 0 1 2
dimensional
array
let products = [
[1,"Samsung Galaxy A53",30000],
[2,"Vivo Y75",20000],
[1,"Redmi 10 prime",13000],
]
let products = [
[1,"Samsung Galaxy A53",30000],
[2,"Vivo Y75",20000],
[1,"Redmi 10 prime",13000],
]

0 1 2 0 1 2 0 1 2
1 Samsung Galaxy A53 30000 1 Vivo Y75 30000 1 Redmi 10 Prime 30000

0 1 2
let products = [
[1,"Samsung Galaxy A53",30000],
[2,"Vivo Y75",20000],
[1,"Redmi 10 prime",13000],
]

0 1 2 0 1 2 0 1 2
1 Samsung Galaxy A53 30000 1 Vivo Y75 30000 1 Redmi 10 Prime 30000

0 1 2
products[0] =[1,"Samsung Galaxy A53",30000]

products[0][0] = 1
products[0][1] = Samsung Galaxy A53
products[0][2] = 30000

You might also like