0% found this document useful (0 votes)
10 views

Javascript

The document outlines the syllabus for JavaScript including: 1. Placement of JavaScript code, variables and data types, operators, control structures, functions, objects, OOP concepts, events, cookies, exceptions, web APIs, asynchronous programming, AJAX, JSON, jQuery, graphics, debugging, modules, animations and ES6 features. 2. Key concepts covered include variable types, functions, objects, events, exceptions, asynchronous programming and AJAX. 3. The syllabus provides a comprehensive overview of JavaScript from basic syntax and programming concepts to advanced topics like OOP, asynchronous programming and ES6 features.

Uploaded by

Abhishek
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Javascript

The document outlines the syllabus for JavaScript including: 1. Placement of JavaScript code, variables and data types, operators, control structures, functions, objects, OOP concepts, events, cookies, exceptions, web APIs, asynchronous programming, AJAX, JSON, jQuery, graphics, debugging, modules, animations and ES6 features. 2. Key concepts covered include variable types, functions, objects, events, exceptions, asynchronous programming and AJAX. 3. The syllabus provides a comprehensive overview of JavaScript from basic syntax and programming concepts to advanced topics like OOP, asynchronous programming and ES6 features.

Uploaded by

Abhishek
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

Java Script Syllabus:

Placement:

<Head>

<Body>

<External>

Variable:

Primitive:

Var, Let, Const,

Not-Primitive:

Object, Array, String

Operators

Conditional Structures – If, Else, Else If, Switch

Control Structures—For, While, Do While, Break, Continue, Foreach

Functions

Declaration

Expression

Anonymous

Arrow

Higher Order

Function Constructor

Call

Bind

Apply
Closures

Scope Chain

Mix:

Hoisting

Strict Mode

Regular Expressions

Objects:

Math

Number

Date

BOM

DOM

OOPS:

Class

Constructor

Encapsulation—Setter And Getter

Inheritance

Polymorphism

Static And This Keyword

Events:

Event Bubbling
Event Capturing

Types Of Events

Mouse

Keyboard

Form

Window

Document

Cookie:

Storing Cookie

Reading Cookie

Deleting Cookie

Setting Cookie Expiry Date

Exceptions:

Try-Catch

Finally

Throwing Exception

Custom Exception

Error Object

Web API:

DOM API

WEB STORAGE API

GEOLOCATION API

FETCH API

HTTPREQUEST API

CANVAS API
FORMS API

HISTORY API

WORKER API

Asynchronous:

Call Back Function

Promises

Async And Await

AJAX

JSON

JQUERY

GRAPHICS

DEBUGGING

MODULES

ANIMATIONS

ES6 FEATURES:

LET, CONST

ARROW

MODULES
MAP AND SET

CLASS

PROMISES

ASYNC AND WAIT

STRING METHODS

NUMBER PROPERTIES AND METHOD

… OPERATOR

FOR / OF

SYMBOL

DEFULAT PARAMTER

FUNCTION REST PARAMETER

OBJECT ENTITIES

PROXY AND REFLECT

Prototype Inheritance

Language:

Programming Languages and Scripting Languages both are used to writing the computer programs and
interact with computer.

Programming Languages are using the compiler then compiler convert Source code into Machine code
before execution.

Scripting Languages are using the interpreter then interpreter directly execute the source code line by line
without compilation

Programming languages are strong typing that means variables must have the specified the data type.
Scripting Languages are dynamic typing that variable can store the variables with specified data type
automatically It Detect.

Programming languages used for Developing the complex application like mobile , desktop, Enterprise
applications.

Scripting Languages used in web Development and writing small code for the specific task.

Programming language are faster and efficient because source code is compiled to machine code.

Scripting language slow because it execute the code line by line.

JavaScript uses:

JavaScript is scripting lang which is based on the objects. Which is used for develop the interactive and
Dynamic Web applications.

Client side validation

Drop down menus

Pop UP windows and Dialog boxes

Sliders

JavaScript is Case-Sensitivity.

PLACEMENT:

<head>------ Place is head Section.

<body>-------place in body section

<external File>------Create in the Js File.

Data Types:

Datatypes which are used to store the different types of values.

JavaScript meanly having the two types of Datatypes.

Primitive Datatypes

Non-Primitive Datatypes.
JavaScript is a dynamically typed language. The type of a variable is determined at runtime, not at
compile-time. This means you don't need to explicitly declare the datatype of a variable when you define it;
the datatype is identified based on the value assigned to the variable.

Primitive datatype:

Primitive datatype means which will store only single value in the variable.

String

Numbers ---both floats and integers.

Boolean

Undefined--- Undefined value is automatically assigned to variable when variable value is not assigned any
value. If We use explicitly then that means absence of value.

Null—Null value is representing the we explicitly say there is no value.

Non-Primitive Datatypes.

Non-Primitive Datatypes are used to multiple values in the single variable.

Object

Array

Variables:

Variables are used to store the values we can manipulate the values with the help of variables.

Variables are Declared with the var, let, const keyword

Var:

Variable is declared with var keyword then that variable can gets the function scope or Global scope
depending on where they are declared.

Example: when you create a variable within the function then that variable is having function scope that
means it can access only within the function.
When you declared a variable outside function so you can access anywhere in the code.

Var variable are hoisted that means the variable is moves to the top of their scope which means when we try
access the variable before variable is declared so hoisted moves the variable to top of scope then default
value is print Undefined.

Var keyword allows the variable to be declared and reassign within the same scope

Let and const

Variable is declared with let and Const keyword then variable can get the Block scope

Example: when we create a variable within the block then that variable is accessed within the block and we
cannot access from outside.

When you declared a variable outside Block so you can access anywhere in the code.

Let and const are not hoisted that mean we cannot access the variable without declaration suppose we try to
access the variable before declaration then Temporal Dead zone situation is Raises.

Let keyword allows variable not to be redeclared but we can reassign the value.

Const keyword Immutable that means value cannot be re-assigned one value is assigned then we cannot
change the value of variable.

Functions:

Functions are containing the block of code that is defined once in a programme and it is used to perform the
specific task and functions, we reusable to use we can use as many times in the programme and functions are
used to organize the code into the modules.

Functions stored the input as parameters and it given the values as arguments.

When the Function is called it executed the block of code and it returns the result of code where function is
called.

First class functions:

Function are called as first class function or Citizens in JavaScript because functions are treated as just the
value then we can assign the functions to variable, we pass the function as a parameter and one function
returned another function as a value.

Function Declaration or statement:

It means function is defined with function keyword and along with parameters, return type.
Function Expression:

It means function is assigned to variable as a value then that function is called function expression.

Difference between the function statement and Expression is hoisting function statement is support hoisting
and function expression is not supports the hoisting because variable is moves to top of scope but but
function value is not hoisted and not move to top the scope and it is executed at runtime after that value is
assigned to the variable.

Anonymous Function

Anonymous function means functions with without name is called anonymous functions.

It is commonly used to callback functions.

It used to create the Immediately Invoked Functions.

These functions are used to create the closures.

arrow function can be creating Anonymous functions

Without specifying the function name, we can assign the function to a value.

Arrow Functions:

Arrow function is the short hand way to create the function in js and It introduced in the ES6 version.

Immediately Invoked Function:

These functions are Automatically executed when the code is JavaScript code is run.

(function() {

// Function body or code block

})();

()---Enclose the anonymous function

();--Anonymous function is called

Function Constructor:

It is a built-in function which is used to create the function dynamically at runtime and with the help of built
in Function constructor and we defines the parameters only in String format.
Var a=new Function(‘a’ , ‘b’ , ‘ return a* b ‘ ---- function operation write.);

Console.log(a(5,5)

bind, apply, and call are methods that can be used to control the value of this keyword in a function and
that function is invokes in different ways

Call Function:

Call is a function that helps you change the context of the invoking function. And it helps you replace the
value of this inside a function with whatever value you want.

Example:

let obj={
firstname:"abhi",
lastname:"shek",
fullname:function(){
console.log(this.firstname+" "+this.lastname);
}
}
let obj2={
firstname:"abhi",
lastname:"shek",
}

obj.fullname.call(obj2);

One object contains the function I need to use that function and replace the current this object values.

let fullname=function(address){
console.log(this.firstname+" "+this.lastname+” +”address);
}
let obj={
firstname:"abhi",
lastname:"shek",
}
let obj2={
firstname:"raju",
lastname:"babu",}
fullname.call(obj , “hyd”);

Apply function:

Apply is very similar to the call function. The difference is

Apply method accepts only the list of Elements not the individual. We pass the object directly then try to
print the value it prints only the first value and then we pass like array of object.

Call method accepts the individual and list of entire collection values.

let a=["mumbaii", "mahastarta"];

details.call(emplyoee, "mumbaii", "mahastarta");

details.apply(emplyoee, a) ;

Bind function:

Bind Function it combines the Function and Object or Data and returns a new Function that contains the
Function information and object information. Then directly call that function.

This is useful when you want to create a function with a fixed this value that can be invoked later.

const boundGreet = obj.greet.bind(obj);


boundGreet(); // Output: Hello, John!

CLOUSER:

Crouser is a Function That is bundled with its lexical environment is known as a closure. Whenever parent
function is return the inner function or parent function is vanished in execution context but still it remembers
the reference it was pointing to. It’s not just that function alone it returns but the entire closure. When we try
to print the data, it will print because it still has the reference to the parent function (parent lexical
environment).

function office()
{
var name="abhi";
var rollno=44;
function emploee()
{
var none="klll";
console.log(name+" "+rollno+" "+none);
}
return emploee;
}
let a=office();
a();

HOISTING:

Hoisting is a Concept in JavaScript where variable and function declarations are moved to the top of
their containing scope during the compilation phase, before the code is executed.

it's important Thing is only declarations are hoisted, not the initializations values.

Variable:

Console.log(x) // Undefined.

Var x=5;

Function:

Hello();

Function Hello()

{
}
USE STRICT: “use strictmode”

Strict mode is providing the Stricker rules for the JavaScript code. Like

Variable must be declared with var, let, const before use

Assigned a variable to undeclared variable is not allowed

When we specify this silent error are treated as actual errors

help of these we find the errors and prevent the errors and We can write the cleaner code.

Example: x=20; // silent error will come but not display

When use strict mode // Reference error will be comes.

REGULAR EXPRESSION:

Regular Expression is collection of sequence of character

it is used in validation{email} and Searching{know the name in the list}, Manipulation{modify the
String}, URL parsing{extract the data from

Object Methods:

When we Create the Methods in the Function as a Property and they are accessed and called with the help of
object references and property name.

List of Functions:

String Functions

Array Functions

Math Functions

Date Functions
Dom Functions

Asynchronous Functions

Objects:

Object is a real-world thing (entity) and object contains the state and behaviour, state is represented as
properties and behaviour is represent as methods

Everything in the js is Object and js is object -based language.

Js is template based not class based that means we can create the object directly without the class.

3 ways to create the object in JavaScript

Object literal

Using Instance of object directly

Using object constructor

Var object={property: value, property1:value1}

Var object_name=new Object();

Object_name.property=value;

Object_name.property_1=value_1;

Using object constructor

We need to create a function with arguments and that arguments are directly assigned to current object with
help of this keyword.

Function emp(id, name , salry)

This.id=id;

This.name=name;
}
Var person=new person(“abhi’);

JavaScript is having the several Objects and each object is having the properties and methods that are
used to perform the various operations.

Global objects:

Global object are contains all the Pre-defined object and other objects. That Global object is Window

Dom Object

Bom Objects

User-Defined Objects

Built in Objects

Date:

Date Object it is used to work with date and times. date object provides the various method and properties
for manipulating and formatting dates.

Methods:

Get--- these below methods are used to get the current date and time.

Getdate

Getday

getmonth

Getfullyear

Gethour

Getmilliseconds

getMinutes

getsecond

UTC-time for every above methods


Set—These below methods are used to set the time and date. Set methods are used change the specific date
and we can provide our own date.

setdate

setday

setmonth

setfullyear

sethour

setmilliseconds

setMinutes

setsecond

UTC-time for every above methods ---setUtcdate, setutcday..

Set Timeout:

set Timeout is a function which is used to execute the function or block of code after specified delay

It takes the two Parameters one is functions to be executed and second one is Delay time in milliseconds.

The function is executed only once after the specified delay time is over and it doesn’t the executed the
function Repeatedly.

Set Timeout(function() {

// Code to be executed after the delay

console.log("Timeout function executed");

}, 2000); // Execute after 2 seconds (2000 milliseconds)

Clear Timeout:

Clear Timeout which is used to stopped the execution set timeout when we uses these function the set
timeout method will not work.

clearTimeout(timeoutvariable);

or
clearTimeout(Set Timeout(function() {

// Code to be executed after the delay

console.log("Timeout function executed");

}, 2000););

Set Interval():

These function is used to repeatedly execute a function or a ode block at a specified time interval.

It takes two parameters: a function to be executed and the time interval in milliseconds.

The function is executed continuously at specific time interval is completed and it not stop automatically it
manually stopped the set interval with clear Interval or page is removed.

let i = 1;

set Interval(() => {

console.log(i);

i++;

}, 1000);

Clear Interval:

Clear interval it is used to stop the execution of a function in set interval

Clear interval takes the single parameters that where that parameter is set interval entire function or the set
interval function is stored in one variable.

We use direct Clear interval to stop the set Interval function execuction or we can use the set timeout to
delay the execution of clear interval bcz I I want to execute some set interval after set timeout time is over
then clear interval is executed.

setTimeout(function() {

clearInterval(intervalId);

}, 5000);

(Or)

Clearinterval(set_timeout_variable);
Math Object:

This object is providing the several properties and Methods that are used to perform the mathematical
operations.

Math object is static object it means it don’t have any constructor so no need to create the object then we
directly with the class name.

Abs---it returns the absolute value of the given number. -4---4 , -6,6—6.6

Ceil- increase the given number to the closet integer value. 0.2—1 , 1.2—2 ------ (-0.2)—0 //(-1.2)--1

Floor---it decreases the closed number to the closed integer value. . 0.2—0-- 1.2—1 ------ (-0.2)—1 //(-
1.2)--2

Round—it rounds the gives number to the closed integer value. ---7.2---7 ----0.6—1---(-7.2)—(-7) // (-1.2)
—(-1)

Sqrt

Pow

Round

Min(2,3)

Max(1 ,2)

Number Object:

Number object it is used to represent the numeric values, Numeric values may contain the integer or floating
values.

Number object having the constructor so we can create the object with the help of constructor.

Var n=new Number();

Properties:

MIN_VALUE

MAX_VALUE

POSITIVE_INFINITY
NEGATIVE_INFINITY

NAN

Methods:

To String—convert integer value to string.

Is Integer---check the value is integer or not

Parse Float—convert the string to floating point number.

Toprecision—specify the precision with the help of these method we can specify

Var a=44; OR b=44.44434

a.toprecision(2)----44.00--------44.44

BOM Object:

Browser object model is a collection of objects that every object is different and each object will interact the
web browser component.

Window object

Window object is representing the browser tab and the tab is contains the current web page.

Window object is having the method and with the help of window object we can access the methods

These methods are used to perform the operations on the current tab and indirectly on current web page.

No need to specify the window object to access the method it automatically understands.

Alert() --It display the dialog box and that dialog box contains the message and ok button.

Prompt() – It display the dialog box and it contains the one input field and with Ok button and cancel
button

Confirm()—It display the dialog box and It contains the message and Ok and cancel button. Used for
before closing tab we provide the message that you really want to close the tab then ok then tab is closed.

Open() –these method used to open the new window or tab

Close()---These method is used to close the current window or tab


Set timeout()

Set interval()

Navigator Object:

Navigator object is used to know the browser information’s.

These object contains the properties and methods.

Properties:

Appname -- return the app name

Appversion --- return the app version

Appcodename ---return the code name

Cookieenabled ----return true or false depend upon the cookie is there or not.

Useragent -- each browser is having the own user agent user agent is like information about the browser
like Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.43 these the browser send the http request to web server
the user agent also included

Online

Platform

Language

Methods:

JavaEnabled --- check java is enabled or not in the browser.

Screen:

Screen object is used to know the screen information of the current window or tab.

Width –return the width of the screen

Height—return the height of the screen

Availwidth --- return the available width of the screen.


Availheight-- return the available height of the screen.

History Object:

History object is used to store the URLs visited by the user. So By using the history method we load the
next page and load the previous page.

Forward –load the next page.

Back—load the previous page

Go –load the webpage with given number

Length—returns the length of history URLs.

DOM:

When the html document is loaded in the browser, it becomes the document object.

The document object is representing the root element of the entire html document. This object is having the
methods and properties.

With the help of Dom, we can change the dynamic content of the webpage.

Every Object is becoming the property of root document object.

When we load the html in the browser the browser converts every html element into the object and Every
element attributes are converted into the properties of object.

Suppose when we want to access the html document so with the help of DOM API I can interact with the
Html document.

Example: suppose when we load the html code in the browser the browser create the document object

And with the help of document object provide a access to the Dom API , because with help of document
object we cannot access the Html elements so that’s why we use dom api with the help of Dom API we can
access the html document Elements, after accessing we can change the content of the Html elements these
dom apis are attached to the document object and document object is attached to the global object window.

Window.document.getelementbyId();
Document properties and Methods:

Write()—Write the content to the document.

Writeln()—write the content in the form of String to the document it end the present line

getelementByid() ---these method return the element where the given html attribute id matches with the
value.

getelementbyclassname()

getelementbytagname()

getelementbyname()

QuerySelector()—select the first element that matches with the specified CSS selector.

QueryselectorAll()—select the all elements that matches with the specified CSS selector.

createElement()

appendchild() and append()—append child and append methods both are used to add the html element to
the document and appendchild takes the only single parameter and append() method takes the two
parameters.

Appendchild() method accepts only the element nodes such as div , li , and all elements called as nodes.

Append() method accepts any kind of element nodes such as div, li –(element node), “hello”---(text node)

Createtextnode()—these method return the text node it is directly print the text in the document.

Removechild() – removes the element from the document.

Replacechild(new node, oldnode)--

Set attribute— create the attribute of the html element and it takes the two parameters one is attribute
name , attribute value.

Get attribute-- these method is used to return the attribute name and it take the single parameter that is
attribute name

Remove attribute—removes the attribute on an element.

AddEventListner()—Attaches an event Listener to the html element.

removeEventListener()—removes an event listener from an element.

Remove()—remove an element from the dom.


Properties:

InnerHtml--- these properties which is used to access the html content in the html elements tag it is used to
retrieve or modify the html element .

Innertext—these properties which is used to retrieve or modify the html element

The difference between them is when you try to return the child element content innerhtml return the
complete tag and innertext not returns only the content.

bgcolor

Parent node

Child node

First child

Nextsibling

Previous sibling

Class:

Class is a template that is used to define the properties and methods of an object and with help of class we
can able to create the more number of objects.

Class is encapsulate the data and code into the single unit.

Classes are called as special functions because class are treated as like functions that means by using the
function expression we able to add the function to variable in the same way we can able to add the class to
the variable that is class expression.

Class contains the Methods , constructors.

instance variables(properties) are not created directly within a class because JavaScript does not have
explicit support for instance variables. But with the help of constructor function and defining instance
variables within the constructor.
Constructor:

Constructor is a method which is used initialize to create the object and it is called when memory is
allocated for object.

Constructor keyword is used to create the constructor

Class contains only one constructor method

We use this keyword we differentiate the local and instance variable.

Constructor is used to add the instance variable directly to object.

Constructor(name, rollno)

{
this.name=name;

This.rollno=rollno;

Below method are written inside the class with help of function calling we access directly.

Setter Methods:

This method is used to access the instance variable and set the values of the instance variables.

Set m1(value)

{
this.name=value;

Getter methods:

These method is used to get the instance variable

Get m2()
{
return this.name;

Method:

Methods are created directly with method name.

Check()

{
this.name=40;

Console.log(this.name);

Static method:

Static keyword mainly used for memory management and we create the static method that belongs to class
rather that instance of class.

Static display()

//code.
}

Encapsulation

Encapsulation is a process of binding the variable and function into a single unit is called as Class and
Encapsulation which is used provide the security internal data and No one can access the internal data from
outside

Which that help of var keyword we make the data members private

We use the setter and getter methods to set the data and getter method is used to get the data from the class.
Constructor

Var Name; // Making the data private

Var marks;

Set set_date(value) // Setter method to set the data

Name=value;
}

Get get_date() //getter method to get the data

{
return Name;

Inheritance:

Inheritance which is used to create a new class based on existing class and Provide the child class to reuse
the method and properties and methods of parent class.

class Moment extends Date {

constructor() {

super(); // calling the date object.

}}

var m=new Moment();

document.writeln("Current date:")

document.writeln(m.getDate()+"-"+(m.getMonth()+1)+"-"+m.getFullYear());

Polymorphism:
Polymorphism means singe action can be performed in different ways.

MethodOverloading

MethodOverriding

Events:

Event is an action that performs on the web browser and web browser responds according to the event.

Event is Handled by the Event Handler, we write the event Handler in the form of method

We have the addeventListener method which is used to combine the event and event Handler

element. Add EventListener (eventname, event Handler)

When the event is occurred then Js engine create the event object and object is passed as parameter to the
event handler and with the help of Event object we can access the properties and methods of the particular
event object.

button.addEventListener('click', function(event) {
console.log(event);
});

Event Bubbling:

It is the default behaviour. When the event Is occurred on element,

Event Capturing:

Types of Events: (triggered—start)

Mouse events:

These events are triggered by user interactions with the mouse

Click

Dbclick

Mousedown
Mouseup

Mouseover

Mouseout

Keyboard events:

These events are triggered by user interactions with the keyboard

Keypress

Keydown

Keyup

key method used to returns the name of key

keycode method used to return the keyboard asci value.

Form events:

These events are triggered by user interactions with form elements

Submit

Reset

Change –it occurs value of form element changes such as input, select etc.

Focus—occurs when input is select.

Blur – occurs when the mousemove from the element.clicked outside of the element

Window events:

These events are triggered by changes in the browser window

page loading-load –page is loading is occurs when the entire page is loading

page unloading—unload—page is removes from the browser then these event is occurs.

window resizing
scrolling

Document events:

These events are triggered by changes in the DOM tree, such as element creation, element deletion, and
attribute changes.

Touch events:

These events are triggered by user interactions with touchscreens, such as tap, swipe, and pinch.

Drag and drop events:

These events are triggered by user interactions with draggable elements, such as dragstart, dragend,
dragover, and drop.

Media events:

These events are triggered by changes in media elements, such as audio and video playback, volume
changes, and seeking.

Cookie:

Cookie is storing the information about the user in the users’ browsers.

We stores the different kind of information user preferences like when user select the English option in
website the information is stored in cookie so when the user again visit the website then website is display in
English.

Client sent a request to the webserver then web server has response in the form of a web page to browser ,
the connection is gone then server forgot everything about the user. when user again visit the same website
That server take as new request because server don’t know the about the user .

Cookie are invented to solve the problem of remembering the user information

When the user visits the a web page his information stored in the cookie
Cookie contains the Properties and Methods.

Required:

Name –It specify the Name of Cookie like username, Language etc.

Value—It specify the value for name like given the name of user.

Expires—It specify how much time cookie will store the data in the browser. If we not specify the any
expiry date then cookie data will store temporary when you close the website the cookie is deleted.

Optional:

Domain: The domain specifies the scope of the cookie. By default, it is set to the domain of the current web
page. However, you can explicitly set a different domain using the domain attribute. For example:
domain=example.com.

Path: The path indicates the URL path within the domain where the cookie is valid. If not specified, it
defaults to the current path. You can set a specific path using the path attribute. For example: path=/myapp.

Secure: The secure attribute indicates that the cookie should only be transmitted over a secure HTTPS
connection. It is set by including the secure attribute. For example: secure.

__

Browser:

Browser is having the JavaScript runtime environment.

JavaScript is running because of JavaScript runtime environment

JavaScript runtime environment provides then necessary Components to executed the JavaScript code.

If we want to run JavaScript code in anywhere simply we need the JRE.

JavaScript runtime environment consist several things

JavaScript Engine:

API

Event Loop
Call back Queue

Micro Task Queue

API:

API is a set of rules that defines how the software application or components should interact with each other.
It specifies the methods , properties the developer can use the access the software components.

Types of Apis

Web apis

Third party apis

Web apis:

Web APis are used to communicate the different web application over a network.

REST API:

GraphsQL

Soap API

Web browser API:

Web browser API:

Browser is built in the browser so with the help of web apis we can able to interact with the browser and
access the browser components and we can manipulate the web page elements.

DOM API

GEOLOCATION API

FETCH API

HTTPREQUEST API

CANVAS API
GEOLOCATION API

It used to know the Location information of user devices such as latitude and longitude .

These Api allows the web application to request location of the user's and after the approval it provides the
latitude and longitude coordinates of the user locations.

navigator is global Object in the browser.

Geolocation is a Object and it is a property of navigator object it provides the access to the Geolocation
api.

Navigator.Gelocation. methods()

METHODS:

getcurrentPosition(sc , er) --- These method is request the current position of the user device. And Take
three parameters.

Success callback- (required)--when the getcurrentpostion method successfully retrieve or find the current
user location then we need to provide the call back function and it executed only when the getcurrentpostion
successfully retrieve the location and after the successful location retrieved is pass one argument to the call
back function that is POSITION OBJECT These object contains the properties and method to know the
location.

error Callback (optional): A function that is called when an error occurs while retrieving the position. It
takes a Position Error object as a parameter, which contains details about the error. When the user block
the location then we show the message to them.

Properties:

Cords—it is object contains the properties like latitude, longitude.

Watch Position(success callback)-- These methods monitor the user-location in Realtime, it continuously
tracks the device location and updates the position wherever he is and it returns the position that position is
said to success callback function then it show the location

clear Watch()-- This method stops watching the device's location. It takes the unique ID returned by the
watch Position() method as an argument we store in the variable then we pass to clear watch method , we
must specify how much time to after it close using the set timeout function.
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(success , failure);

}
function success(position)
{
const lat=position.coords.latitude;
const lang=position.coords.longitude;
console.log(lat+" "+lang);
}
function failure(PositionError)
{
console.log("failteuere.")
}

const watch=navigator.geolocation.watchPosition(success);

setTimeout((watch) => {
console.log("cleardd..")

}, 6000);

WEB AUDIO API

JavaScript provides the two mechanisms to store the user information in the browser

Local storage

Session storage

Local storage:

Local storage object allows you to store the data permanently in the browser and when the user closes the
browser and open later that data is there in browser.
Session storage:

Session storage object allows you to stores the data temporarily within the session when user visit the
website the user’s data is stored in the browser after use close the browser his data will be gone.

HTTPREQUEST API

Http request api is used to allow the developer to make the http request from the web application to the web
server.

With the help of these we can send the data and receive the data over the http protocol to application to
server and server to application.

JavaScript Engine:

JavaScript engine is Not a Machine it is a piece code is used to execute java Script code.

Java script engine takes code as input.

Java script engine do the 3 steps

Parsing: The JavaScript engine parses the JavaScript code by breaking it down into tokens and constructing
an Abstract Syntax Tree (AST). It is Hierarchical representation of the code.

It represents the relationship between the all elements.

Parser used to Analize the source syntax code it checks if any rules and grammar are followed or not. It
identifies errors in the code like missing semicolon, mismatched parentheses.

Compilation: JavaScript engines typically use a combination of interpretation and just-in-time (JIT)
compilation to convert the code into machine code

The AST generated during parsing is passed to the interpreter, which executes the code line by line. As the
interpreter encounters frequently executed code called as hotspots, it hands them over to the compiler for
optimization. The compiler converts the frequently executed code into Machine code then interpreter
directly use the machine code

To Execute the code.

Execution: The execution is done in the call stack and call stack is executes the code and code is stored in
the memory heap.
Event Loop:

 The event loop is a mechanism in JavaScript that handles asynchronous operations and ensures that
they can run in the background while other code is executed.

Components of the Event Loop:

1. Call Stack: The call stack is a data structure that keeps track of function calls in the programme.
When a function is called, it is added to the call stack. The engine executes the functions in the call
stack form top to bottom because stack follow the LIFO order.

2. Callback Queue: callback queue is data structure which is that stores the callback functions in the
FIFO order. These callback functions are added to the queue when an asynchronous operation is
created in the programme such as a timer or an event listener

3. Microtask Queue: The microtask that stores the microtask callbacks. Microtasks callback have a
higher priority than regular callbacks and are executed before the next rendering or UI update.
Promises and Mutation Observer callbacks are examples of microtasks.

Execution Flow:

1. The JavaScript engine starts executing code from the call stack.

2. If there are asynchronous operations (e.g., timers, network requests), they are initiated and run in the
background.

3. When an asynchronous operation is completed, its associated callback function is placed in the
callback queue.

4. Once the call stack is empty, the event loop checks the callback queue.

5. If there are callback functions in the queue, the event loop takes the first function and adds it to the
call stack for execution.

6. The executed function is removed from the callback queue.

7. Call stack is executing the call back function after it removed from the call stack.

ASYNCHRONOUS PROGRAMMING:

Java script is performing the Asynchronous operations.

Synchronous Programming means operations are executed sequentially and It blocking the execution
of another operation till current programmes is completes execution , when we performing the
synchronous operation one operation is executing another operation must it executes after the execution
of current operation.

console.log("Operation 1");

console.log("Operation 2");

console.log("Operation 3");

Asynchronous Programming : The operations are executed in the background and without blocking
the execution of other operations. When we performing an asynchronous operation , current operation is
executing in the background and other operations can continue to executing without waiting for the
completion of the current operation.

console.log("Start");

/ / Asynchronous operation

setTimeout(function() {

console.log("Async Operation");

}, 2000);

console.log("End");

output: start End asyn operation is displayed after the execution.

ASYNCRHONOUS OPERATIONS:

Timer Functions:

 Functions like setTimeout and setInterval are used to execute the code after a specified
delay

 They allow you to perform tasks asynchronously by setting a timer and executing the code
when the timer expires.

User Input and Events:

 We Handles user interactions in asynchronously.

 Event listeners are used to register callbacks that get executed when the specified event
occurs.

 The program continues its execution while waiting for the event to happen.
Promises and Asynchronous Functions (async/wait):

Network Requests:

 Making HTTP requests to external servers using methods like fetch, XMLHttpRequest, they
p

 The request is sent to the server, and the program execution continues without waiting for
the response.

 Once the response is received, a callback function or a promise is used to handle the
response data.

CALL BACK FUNCTION:

Call back function is function that is passed as an argument to another function then after and it executed
its need or event is occurs.

The function is having the capability to take an argument as parameter that function is called as Higher
order functions. Higher order function is used to Handle call back function

Callback function used to handle the asynchronous operations. It specifies the what should happen when
asynchronous operation is completed

SET TIMEOUT EXAMPLE:

Settimeout(function ab()=>{
console.lof(“hello”)

},2000);

Set timeout method is perform the asynchronous operation and it takes the two parameters call back function
, timer During execution js engine identifies set timeout as a asynchronous operation and the call back
function is stored in call back queue and it is attached with 2000 msecs and other operation are executed set
timeout method is executing in the background when timer is over then call back function handles the
asynchronous operation and display the result..

ADD EVENT LISTENER:


When we add the event listener to a button then event listener takes the parameter as a call back function and
event that call back function is stores in the call back queue when the even is occurs or happened the call
back function is called and executed.

Types of Errors

1. Syntax Error: When a user makes a mistake in the syntax then syntax error occurs

2. Runtime Error: When an error occurs during the execution of the program, such an error is known
as Runtime error. The codes which create runtime errors are known as Exceptions. Thus, exception
handlers are used for handling runtime errors.

3. Logical Error: An error which occurs when there is any logical mistake in the program that may not
produce the desired output, and may terminate abnormally. Such an error is known as Logical error.

EXCEPTION HANDLING:

Exception Handling is used to handle and detecting and managing exceptions that occurred during the
execution of the programme.

Try-catch:

The try-catch statement is used to catch and handle exceptions in JavaScript. The try block contains the
code that may throw an exception, and the catch block is used to handle the exception if it occurs.

Finally Block:

The finally block is an optional block that can be used along with the try-catch statement. The code in the
finally block is executed regardless of whether an exception is thrown or caught. It is typically used to
perform cleanup tasks or release resources.

Throwing Exceptions:

We can manually throw an exception using the throw statement. This is useful when you want to explicitly
raise an exception based on certain conditions or errors in your code.

Custom Exception Types:

JavaScript allows you to create custom exception types by defining your own classes that inherit from the
Error object. This allows you to create more specific and meaningful exceptions for your application.

ERROR OBJECT:
When a runtime error occurs, it creates and throws an Error object. These error object provides the
information about the error.

Properties:

Name: represents the name of error

Message: It contains the user defined error message.

Stack: It represents the sequence of function calls

Object:

Object is a collection of key/value pair.

Global execution Context:

When we run the JS code global execution context is created.

Inside Global execution context Js engine create the two things.

Global Object

This variable

Lexical Environment

Hoisting:

Hosting is a concept used to move the variable and method declaration to top the scope.

These hoisting is happening at compile time phase. JavaScript's syntax parser scans through the code and
identifies variable and function declarations. These declarations are then "hoisted" to the top of their current
scope.

The declaration only moves to the top does not value because values are initialized at execution time.
Javascript uses:

websites.

single page applications.

react Native or Native Script to build the Hybrid Mobile Apps.

Electron.js to build the Cross Platform Desktop Applications.

Build 2D and 3D Games.

Node Js and Express Js for server-side applications.

Build Interactive Maps and data visualization.

Create the Browser Extensions.

Create the Web servers and API.

Can create AR and VR Applications.

JavaScript All functions are object methods.


Suppose if the function is not a method of object that function is a method of global object.

var emp={

name:"abhi",
age:55,
display:function()
{
console.log(this.name+" "+this.age);
}

In above example

Name, age both the properties of emp object

Name, age both are properties of this object.

This object is referring to the different object depending upon how it is used.

Example,

Normally this keyword is referring to the Global Object.

In function this keyword is referring to the global object.

When we use strict mode, this keyword is not referring to any object that is undefined.

The Main use we can borrow the function from another object without creating the same method in the
object. So here that object is having this keyword is refers to that particular object only so with the help of
these we can refers to our object.

Or

Normally use create the function Outside object for display purpose so we that function to print the values of
other objects so with the help of these methods we that function are link the this keyword to our object.

Call ():

Thes take the parameter as single and array but in array we must accessed with index position otherwise
normally we cannot add same list of parameters don’t work.

var c=["param1","param2"];
var b=display.call(emp1, c);
var display=function(a)
{
console.log(a[0]+" "+a[1]);
console.log(this.name+" "+this.age);
}

Apply:

We pass the array and no need to access with index position just add same number of parameters in the
function it directly print.

var display=function(a,b,c)
{
console.log(a+" "+b+" "+c);
console.log(this.name+" "+this.age);
// console.log(this);

Bind():

It is do the same work but it bind the function and object and create new function that function is returned
so above both they are called instantly these is called later.so we can reuse that function no need to call the
function directly.

Objects:

Everything in the JavaScript is object.

Datatypes are objects,

Function are objects.

Except the primitive values because they don’t have no properties or methods.

For example primitive are immutable that means values cannot be changed

Var x=10; 10 values is primitive value that value cannot change x value can change.

Object are mutable that means they addressed by reference not by value if the x object change that linked
values are chaged.

Values in the object called as properties.

Methods in the object used to perform the actions.


Creating the object

Object literal

New keyword

Object constructor

Access the Properties:

Access with objects.

Obj.name

obj[“name”]

Prototype:

Every object is having the properties by default is prototype.

Normally when the object is created we add some properties and methods so with the help of . operator we
can access how we are accessing is they are part of object.

When we create the variable, function, objects some properties and methods are automatically added by the
JS Engine with the help of Prototype.

Same with the dot operator only we can access the other object properties and methods without knowingly
they relate to the other object properties and methods.

__Proto__ : is a object it contains the all the hidden properties and methods are put.
Prototype:
in JavaScript Object can inherit the properties and methods from another Object Via Prototypes. So These
Creates the Chain of Objects called “Prototype Chain”.

This creates the chain called Prototype Chaining.

The Prototype Chain ends with the prototype has value is null.

For example,

When you try to access a property or method on an object, JavaScript first checks if that property or method
exists on the object itself.

If it doesn't find it, it looks up the prototype chain until it finds the property or method or reaches the end of
the chain.

Then value is display is undefined.

Every Constructor function in JS has a property called Prototype.

Prototype is an object that can be used for creating the new Objects and that contains the properties and
methods.

JavaScript has the built-in Object() function:

We have the default Object Constructor and used to create new Objects.

Var obj=new Object();

Obj.name=”abhi”;

Obj.age=55;
Object.prototype object has some useful properties and methods such as toString() and valueof(),
constructor() that reference to the Object() function.

Promises:

Promises are used to perform the asynchronous operations such as making HTTP request, task may take
more time to complete.

It is provides structured way to work with asynchronous operation compared to normal callback functions.

States of promises:

Pending: initial state when promises is created. That means asynchronous operations is going in
background.

Fulfilled : asynchronous operations is competed successfully.

Rejected : asynchronous operations not performed due an errors or failure.

Callbacks:

Promises uses the two-callback function to handle the outcome the asynchronous data.

Resolve: this callback is called when the asynchronous is successfully completed.

Reject: callback function is called when an asynchronous operation is got error or failure.

Chaining:

Asynchronous operations performed in chain format.

. then(): these method called when the promises state is fulfilled that means asynchronous is completed and
then function fill the data into the promise object as the response.

.catch(): these method is called when the promise state is rejected and typically used at the end to handle
the errors
DOM:

Document is the root object.


Document object doesn’t have the direct connection because html document is complex, so it is hard to
access the properties directly one by one it is hard, and it take more memory and processing speed to access
and manipulate the html document.

Another things is allowing direct access to elements could be security problems like some part of the
webpage should be not accessed so that situation is not possible and easily add the malicious script.

Direct accessed elements:

Body

Head

Title

Document element: return the complete html document.

URL : return URL of the current document.

Domain : set or get the domain of the document.

Charset : return the character encoding of the document.

DOM API:
These API are provided by the web browser that allows developer to interact with the HTML and XML
documents.

They provide a way to access manipulate, and modify the content, structure, style of web documents.

Finding Elements:

getElementById():

Finds an element by its unique id attribute.

Returns the first element with the specified id.

Element not found return null value.

getElementsByClassName():

Retrieves elements by their class names.

Returns a collection (HTML Collection []) of elements with the specified class.
Elements not found return the HTML collection.

getElementsByTagName():

Retrieves elements by their tag names.

Returns a Node list collection [] of elements with the specified tag name.

querySelector():

Retrieves the first element that matches a CSS selector.

Returns the first matching element or null if no match is found.

querySelectorAll():

Retrieves all elements that match a CSS selector.

Returns a Node List containing all matching elements.

Elements are not found it return the empty Node list.

Node List:

querySelectorAll(selector)

getElementsByTagName(tagName)

getElementsByClassName(className)

childNodes

attributes

childNodes

HTMLCollection:

getElementsByTagName(tagName)

getElementsByClassName(className)

children

images
forms

anchors

rows

cells

Node List used when you want to work with the various types of nodes not just html elements and When can
apply the methods like foreach, map.

For example, quearyselectorAll is select all elements of the different nodes like div, h3, h1.

HTML Collection when you want to work with the single html elements and accessed by their name.

Changing HTML Elements

InnerHTML :

You need to manipulate the HTML structure inside an element.

You want to insert or replace html content dynamically.

More used for user-generated html content,

For example, element.innerHTML = '<p>This is <b>bold</b> text.</p>';

InnerText:

You want to work with visible text inside an element.

Used for user-readable content.

TextContent:

You need to work with all text content inside an element, visible or not.

It will display the content even content is not visible.

You want to manipulate text content while preserving whitespace and line breaks.

Style:
It allows you to access and manipulate the inline CSS styles ( we add the styles one by one not all at once
like CSS )of an HTML element.

With these we can access direct style attributes and we can change after.

For example,

b.fontSize="60px";

b.color="red";

SetAttribute(“name”, “value”):

These method used to set or change the value of an attribute in HTML.

Adding and Deleting Elements

document.createElement(element)

document.removeChild(element)

document.appendChild(element)

document.replaceChild(new, old)

document.write(text)

BOM:

BOM is created the Browser when we execute the webpage.

We can interact with the Browser and perform some functionalities.

Window:

Window is the global objects.

All the properties and methods, objects are attached to the global object window.

Properties:
inner Height:

inner width:

commonly used methods related to windows:

window.open(url, name, specs, replace)

url ; page to be displayed in new window.

Name: when we use anchor tag we have attribute target=name that we redirect the new window and
override.

Specs: specifying windows height, width.

Replace: replace the current page or new page. If true. Otherwise, false it will open in new tab.

Window.close();

Screen:

Location:

These objects uses to know the current URL information and manipulate

Href: it returns complete URL path.

Protocol: http or https

Hostname

Port

Pathname

Search : searching information.

Reload() : reload the current webpage.

Replace (): we can replace the new URL.


Prototype:

Each object is having one property called [[Prototype]].

This property is reference to another objects.

That how prototype inheritance is works

Prototypes are used to implement the inheritance and enable objects to inherit the properties and methods
from other objects.

So we can access the properties and methods of an object.

If the method or properties not found in the that particular object JS engine looks for their prototype object.

When we create any object JS engine automatically add the Objects and their properties and methods to that
our object with the help of prototype then we can access easily.

Uses:
The main uses to enable inheritance among the objects.

Easily add the new methods and properties to that particular object.

__proto__ Property:

It is not a standard way to access and manipulate the objects prototypes.

It can be used to read or set the protype of an object.


Cookies:
Cookie is a small piece of data that server sends to the user web browser.

The web Browser may store it and send it back with the next request to the same server.

Uses:

Session management: when use login the website the cookie stores the information then next time user no
need to enter the login credentials in the next time visit.

Personalization: store user personalization such as themes, languages, settings.

Shopping cart: stores shopping cart items. Even the browser close or even login.

Tracking and Analytics: Cookies are employed by websites and advertisers to track user behavior. This data
can be used for analytics, retargeting ads, and understanding user preferences.

Remember Me Functionality: When you check the "Remember Me" option on login pages, a persistent
cookie is often set. This cookie allows you to stay logged in even after closing the browser.

Authentication: When you log into a website, a session cookie is often created to remember your login
status. If the session is active, you don't have to enter your credentials repeatedly.

Cookie are stores information in key value pair.

Web Api’s:

We have the number of Api’s are provided by web browsers allow developers to perform various types of
applications.
DOM API

AJAX API

Event API

Storage API

Audio and Video API

Canvas and WebGL API

Form Data API

Drag and Drop API

Geolocation API

Notification API

History API

AJAX API’s: Asynchronous JavaScript and XML

AJAX is combination of XMLHTTPRequest (request for get the data from the server) Object and JavaScript and
HTML DOM. (display the data and access the data ).

It contains some methods are used send the receive the data from the web server asynchronously without
need to reload the entire webpage.

AJAX is doesn’t referring to the specific API and it provide the concept and it contains technique, methods
to perform the operations.

XMLHTTPRequest Object:

These Objects is used to send the request and get the response in the different format.

var xhttp = new XMLHttpRequest();

Methods:

Open(“method”, URL, async value true of false, user name, password)

Send() send the request to the server.

Send(string) send the request along with the parameters.


getResponseHeader:

getAllresponseheader()

abort(): Cancel the request.

Properties:

OnreadyStatechange: these properties is having the callback function when the request state is change
callback function is called.

Readystate: these property return the value

0 request initialized.

1 -server connection established

2- request received

3.processing request

4.request finished, and response is ready.

Response Text:

responseXML:

status: we get the status number of request.

Fetch API:

It is a new API for fetching the data from the server.

Fetch API uses the promises to handle the asynchronous operations.

In the promise we use. then () and. catch () methods to handle the response.

Mainly used for JSON data.

fetch('https://api.example.com/data')

.then(response => {

// Handle the response here

})

.catch(error => {
// Handle errors here

});

Fetch supports various HTTP request methods such post, get, put, delete, etc.

fetch('https://api.example.com/data', {

method: 'POST',

body: JSON.stringify({ key: 'value' }),

})

.then(response => {

// Handle the response here

})

.catch(error => {

// Handle errors here

});

Web storage API:

Used to stores the client data the form of key-value pair in the web browser.

Two ways we can store information.

Local storage

Session storage

Stores user-preferences such as theme setting, language choice , font-size etc.

Shopping items stores.

Form data

Local Storage:

Store the data permanently.

It can store 5-10 mb per domain data.

You might also like