Javascript
Javascript
Placement:
<Head>
<Body>
<External>
Variable:
Primitive:
Not-Primitive:
Operators
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
Inheritance
Polymorphism
Events:
Event Bubbling
Event Capturing
Types Of Events
Mouse
Keyboard
Form
Window
Document
Cookie:
Storing Cookie
Reading Cookie
Deleting Cookie
Exceptions:
Try-Catch
Finally
Throwing Exception
Custom Exception
Error Object
Web API:
DOM API
GEOLOCATION API
FETCH API
HTTPREQUEST API
CANVAS API
FORMS API
HISTORY API
WORKER API
Asynchronous:
Promises
AJAX
JSON
JQUERY
GRAPHICS
DEBUGGING
MODULES
ANIMATIONS
ES6 FEATURES:
LET, CONST
ARROW
MODULES
MAP AND SET
CLASS
PROMISES
STRING METHODS
… OPERATOR
FOR / OF
SYMBOL
DEFULAT PARAMTER
OBJECT ENTITIES
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.
JavaScript uses:
JavaScript is scripting lang which is based on the objects. Which is used for develop the interactive and
Dynamic Web applications.
Sliders
JavaScript is Case-Sensitivity.
PLACEMENT:
Data Types:
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
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.
Non-Primitive Datatypes.
Object
Array
Variables:
Variables are used to store the values we can manipulate the values with the help of variables.
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
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.
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.
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.
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.
These functions are Automatically executed when the code is JavaScript code is run.
(function() {
})();
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 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.
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.
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
help of these we find the errors and prevent the errors and We can write the cleaner code.
REGULAR EXPRESSION:
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
Js is template based not class based that means we can create the object directly without the class.
Object literal
Object_name.property=value;
Object_name.property_1=value_1;
We need to create a function with arguments and that arguments are directly assigned to current object with
help of this keyword.
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
setdate
setday
setmonth
setfullyear
sethour
setmilliseconds
setMinutes
setsecond
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() {
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() {
}, 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;
console.log(i);
i++;
}, 1000);
Clear 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.
Properties:
MIN_VALUE
MAX_VALUE
POSITIVE_INFINITY
NEGATIVE_INFINITY
NAN
Methods:
Toprecision—specify the precision with the help of these method we can specify
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.
Set interval()
Navigator Object:
Properties:
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:
Screen:
Screen object is used to know the screen information of the current window or tab.
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.
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.
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:
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.
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
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 .
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.
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(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:
Get m2()
{
return this.name;
Method:
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 marks;
Name=value;
}
{
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.
constructor() {
}}
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
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:
Event Capturing:
Mouse events:
Click
Dbclick
Mousedown
Mouseup
Mouseover
Mouseout
Keyboard events:
Keypress
Keydown
Keyup
Form events:
Submit
Reset
Change –it occurs value of form element changes such as input, select etc.
Blur – occurs when the mousemove from the element.clicked outside of the element
Window events:
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.
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:
JavaScript runtime environment provides then necessary Components to executed the JavaScript code.
JavaScript Engine:
API
Event Loop
Call back 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
Web apis:
Web APis are used to communicate the different web application over a network.
REST API:
GraphsQL
Soap 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.
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:
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);
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.
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.
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
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.
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.
7. Call stack is executing the call back function after it removed from the call stack.
ASYNCHRONOUS PROGRAMMING:
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");
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.
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 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
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..
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.
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:
Object:
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.
var emp={
name:"abhi",
age:55,
display:function()
{
console.log(this.name+" "+this.age);
}
In above example
This object is referring to the different object depending upon how it is used.
Example,
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:
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.
Object literal
New keyword
Object constructor
Obj.name
obj[“name”]
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”.
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.
Prototype is an object that can be used for creating the new Objects and that contains the properties and
methods.
We have the default Object Constructor and used to create new Objects.
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.
Callbacks:
Promises uses the two-callback function to handle the outcome the asynchronous data.
Reject: callback function is called when an asynchronous operation is got error or failure.
Chaining:
. 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:
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.
Body
Head
Title
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():
getElementsByClassName():
Returns a collection (HTML Collection []) of elements with the specified class.
Elements not found return the HTML collection.
getElementsByTagName():
Returns a Node list collection [] of elements with the specified tag name.
querySelector():
querySelectorAll():
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.
InnerHTML :
InnerText:
TextContent:
You need to work with all text content inside an element, visible or not.
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”):
document.createElement(element)
document.removeChild(element)
document.appendChild(element)
document.replaceChild(new, old)
document.write(text)
BOM:
Window:
All the properties and methods, objects are attached to the global object window.
Properties:
inner Height:
inner width:
Name: when we use anchor tag we have attribute target=name that we redirect the new window and
override.
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
Hostname
Port
Pathname
Prototypes are used to implement the inheritance and enable objects to inherit the properties and methods
from other objects.
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:
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.
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.
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
Geolocation API
Notification API
History API
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.
Methods:
getAllresponseheader()
Properties:
OnreadyStatechange: these properties is having the callback function when the request state is change
callback function is called.
0 request initialized.
2- request received
3.processing request
Response Text:
responseXML:
Fetch API:
In the promise we use. then () and. catch () methods to handle the response.
fetch('https://api.example.com/data')
.then(response => {
})
.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',
})
.then(response => {
})
.catch(error => {
});
Used to stores the client data the form of key-value pair in the web browser.
Local storage
Session storage
Form data
Local Storage: