0% found this document useful (0 votes)
3 views44 pages

JavaScript Notes (1)

JavaScript is a widely used object-based programming language essential for enhancing web functionality and interactivity, with over 80% of websites utilizing it for client-side scripting. It supports various data types, operators, conditional statements, loops, and functions, allowing developers to create dynamic web applications. Key features include its lightweight nature, case sensitivity, and the ability to be embedded directly within HTML.

Uploaded by

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

JavaScript Notes (1)

JavaScript is a widely used object-based programming language essential for enhancing web functionality and interactivity, with over 80% of websites utilizing it for client-side scripting. It supports various data types, operators, conditional statements, loops, and functions, allowing developers to create dynamic web applications. Key features include its lightweight nature, case sensitivity, and the ability to be embedded directly within HTML.

Uploaded by

ambadi29072003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA SCRIPT

Java script is one of the most popular scripting language /popular programming
language/object based programming language.
Java script is used in millions of website to improve design validate the form detect the
browser and many more.
More than 80% of the website use the JavaScript for client side scripting.
Client side scripting means the JavaScript code will compile on the web browser/client
system.
All the browser will have a default JavaScript compiler.
o chrome: V8 engine.
o safari: JavaScriptCore
Why JavaScript:
 It is used to add functionality and interactivity to the web page.
 It is a light weight and object based programming language.
 Java Script can be directly embedded to HTML page.
 JavaScript is an interpreted language.
 It is an open-source language.
 JavaScript is case sensitive language.
JavaScript was invented by Brendan Eich in 1995.
In html we can add the JavaScript using the script tag in head tag or the body tag.
<script>…</script>
Or
we can create a separate file and add the JavaScript code and add the link to the html
document with script tag.
Eg:
<script src="[Link]"></script>

JavaScript Variables
Variables are "containers" for storing information. JavaScript variables are used to hold
values or expressions.

Rules for JavaScript variable names:


 Variable names are case sensitive (y and Y are two different variables)
 Variable names must begin with a letter or the underscore character

Note: Because JavaScript is case-sensitive, variable names are case-sensitive.

Syntax:

1
n
Keyword variable_name=value;
Eg:
var a=10;
let b=10;
const c=20;
declaring a variable in js.
Declaring the variable means creating the variable but the value for the variable is not
assigned.
Eg:
var a;
let b;
Assigning the value to the variable
After declaring the variable, the value of the value can be assigned.
a=10;
b=20;

Redeclaring JavaScript Variables


If you redeclare a JavaScript variable, it will not lose its original value.

var x=5;

x;

After the execution of the statements above, the variable x will still have the value of 5. The
value of x is not reset (or cleared) when you redeclare it.

Data Types in javascript.


Number
The numbers are values that can be processed and calculated. You don't enclose them in
quotation marks. The numbers can be either positive or negative floating and decimal
numbers.
Eg:
var a=10;
The datatype of a is Number.
let a=20.34
the datatype of b is Number.

2
n
Strings
String is a series of letters and numbers enclosed in quotation marks.
Eg:
let name="Suhas"
let b;
b="good morning"
Boolean (true/false)
let’s you evaluate whether a condition meets or does not meet specified criteria.
let isLoggin=false;
var accept=true;
Null
Null is an empty value. null is not the same as 0 it is calculable number, whereas null is the
absence of any value.
let a=null;
[Link](a)
Undefined
The undefined represents the value is not defined but at later time the value will be
assigned.
let a;
[Link](a)
Operators in JavaScript

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y=5, the table below explains the arithmetic operators:

OPERATOR DESCRIPTION EXAMPLE RESULT

+ Addition X=y+x X=7

- Subtraction X=y–x X=3

* Multiplication X=y*x X = 10
X = 2.5
/ Division X=y/x

3
n
X=1
% Modulus X=y%x
X=6
++ Increment X = ++y
X=4
-- Decrement X = --y

JavaScript Assignment Operators


Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators:

OPERATOR EXAMPLE SAME AS RESULT

= X=Y X=Y X=5

+= X+=Y X=X+Y X = 15

-= X-=Y X=X–Y X=5

*= X*=Y X=X*Y X = 50

/= X/=Y X=X/Y X=2

%= X%=Y X=X%Y X=0

Comparison Operators
Comparison operators are used in logical statements to determine equality or difference
between variables or values.
Given that x=5, the table below explains the comparison operators:

OPERATOR DESCRIPTION EXAMPLE

== Is equal to x==8 is false

=== Is exactly equal to (value and type) x===5 is true, x==="5" is false

!= Is not equal to x!=8 is true

> Greater than x>8 is false

< Less than x<8 is true

4
n
>= Greater than equal to x>=8 is false

<= Less than equal to x<=8 is true

Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:

OPERATOR DESCRIPTION EXAMPLE

&& And (x < 10 && y > 1) is true

|| Or (x==5 || y==5) is false

! not !(x==y) is true

String concatenation
String concatenation means adding two or more string to one string
The + operator is used to concatenate two strings in JavaScript.
let fname="Suhas "
let lname="S J"
let name=fname+lname
[Link](name)
output:
Suhas S J

Adding Strings and Numbers

let x=5+"5"

[Link](x)
output is 55
when you try to concatenate a string and the number then the number is explicitly convert to
string and then the output will be 55.

let x=5+5

5
n
[Link](x)
output is 10
when you try to add 2 numbers then there will be no type casting so that the output will be
10.

Conditional Statements
Very often when you write code, you want to perform different actions for different
decisions. You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
 if statement - use this statement if you want to execute some code only if a specified
condition is true
 if...else statement - use this statement if you want to execute some code if the condition
is true and another code if the condition is false
 if...else if.....else statement - use this statement if you want to select one of many blocks
of code to be executed
 switch statement - use this statement if you want to select one of many blocks of code
to be executed

If Statement
You should use the if statement if you want to execute some code only if a specified
condition is true.
Syntax

If(condition)

Code to execute

Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a
JavaScript error!

Eg:
let age=18
if(age<18) {

6
n
[Link](“not eligible for DL”)
}

If...else Statement
If you want to execute some code if a condition is true and another code if the condition
is not true, use the if.....else statement.

If(condition)

Code to execute

else {
other code execute
}
Eg:
let age=18
if(age<18) {
[Link] (“not eligible for DL”)
}
else {
[Link] (“eligible for DL”)
}
If...else if...else Statement
You should use the if.... else if...else statement if you want to select one of many sets
of lines to execute.
If(condition)

Code to execute

else if {

7
n
some other code executes
}
else {
other code
}

Eg:
let age=18
if(age<18) {
[Link] (“age should be greater than 18”)
}
else if (age>60) {
[Link] (“age less than 60”)
}
else {
[Link] (“eligible for DL”)
}

The JavaScript Switch Statement


You should use the switch statement if you want to select one of many blocks of code to be
executed.
Eg:
let a=5
switch(a) {
case 1:
[Link] ("1 is executed")
break
case 2:
[Link] ("2 is executed")
break
case 3:
[Link] ("3 is executed")

8
suhas@[Link]
break
case 4:
[Link] ("4 is executed")
break
case 5:
[Link] ("5 is executed")
break
case 6:
[Link] ("6 is executed")
break
}

Output:
5 is executed

JavaScript Loops
Very often when you write code, you want the same block of code to run over and over
again in a row. Instead of adding several almost equal lines in a script we can use loops to
perform a task like this.
In JavaScript there are two different kind of loops:
 for - loops through a block of code a specified number of times
 while - loops through a block of code while a specified condition is true

The for Loop -


The for loop is used when you know in advance how many times the script should run.
for (initialization; condition; increment/decrement)
{
Statement to execute
}
Eg:
for (var i = 0; i <= 10; i++) {
[Link](i)

9
suhas@[Link]
}
Output:
0
1
2
3
4
5
6
7
8
9
10

The while loop


The while loop is used when you want the loop to execute and continue executing while
the specified condition is true.

while (var<=end value)


{
// code to be executed
}
Eg:
var i=0;
while (i<=10)
{
[Link]("The number is " + i);
[Link]("<br />");
i=i+1;
}

Output:

10
suhas@[Link]
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

The do...while Loop


This loop will always execute a block of code once, and then it will repeat the loop as long as
the specified condition is true. This loop will always be executed at least once, even if the
condition is false, because the code is executed before the condition is tested.
do
{
//code to be executed
}

while (var<=end value);

Example
var i=0;
do
{
[Link]("The number is " + i);
[Link]("<br />");
i=i+1;
}
while (i<0);

11
suhas@[Link]
Result:
The number is 0

JavaScript Break and Continue Statements


There are two special statements that can be used inside loops: break and continue.
Break
The break command will break the loop and continue executing the code that follows after
the loop (if any condition).
Example
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
[Link]("The number is " + i);
[Link]("<br />");
}

Result
The number is 0
The number is 1
The number is 2

Continue
The continue command will break the current loop and continue with the next value.
Example
var i=0
for (i=0;i<=10;i++)
{
if (i==3)

12
suhas@[Link]
{
continue;
}
[Link]("The number is " + i);
[Link]("<br />");
}
Result
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

JavaScript Functions
A function is a self-contained piece of code that performs a particular task. You can
recognize a function by its format - it's a piece of descriptive text, followed by open and close
brackets. A function is a reusable code-block that will be executed by an event, or when the
function is called.

The syntax for creating a function is:


function function_name(var1, var2..., varX)
{
some code
}
var1, var2, etc. are variables or values passed into the function. The {and the} defines the
start and end of the function.
Note: A function with no parameters must include the parentheses () after the function name:
function function_name()

13
suhas@[Link]
{
some code
}
Note: Do not forget about the importance of capitals in JavaScript! The word function must
be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must
call a function with the exact same capitals as in the function name.

The return Statement


The return statement is used to specify the value that is returned from the function. So,
functions that are going to return a value must use the return statement.
Example
The function below should return the product of two numbers (a and b):
function prod(a,b)
{
x=a*b;
return x;
}
When you call the function above, you must pass along two parameters:
product=prod (2,3);

The returned value from the prod () function is 6, and it will be stored in the variable called
product.
The Lifetime of JavaScript Variables
 When you declare a variable within a function, the variable can only be accessed
within that function.
 When you exit the function, the variable is destroyed. These variables are called local
variables.
 You can have local variables with the same name in different functions, because each
is recognized only by the function in which it is declared.
 If you declare a variable outside a function, all the functions on your page can access
it. The lifetime of these variables starts when they are declared, and ends when the
page is closed.

Arrays in Java Script


An array is a special variable, which can hold more than one value
In Java Script arrays are heterogeneous means they can hold any type of variable.

14
suhas@[Link]
In Java Script arrays are dynamic in nature which means they can be dynamically updated the
value stored in java script can be easily updated at any time.

Ways of creating an array

Using an array literal


Syntax:
const array_name = [item1, item2, ...];
Example
const array = [1, "suhas", true];
You can also create an array, and then provide the elements:
const array=[]
array[0]=1;
array[1]= "suhas"
array[3]=true;

using new Keyword


const array=new Array(1,"suhas”, true)

Note: Array indexes always start with 0.

JavaScript Array Methods

length:
The length property returns the length (size) of an array.
Ex:
const array=[10,20,11,23,42,87,34]
[Link]([Link]) //output:7

toString():
The JavaScript method toString() converts an array to a string of (comma separated) array
values.
Eg:

15
suhas@[Link]
const array=[10,20,11,23,42,87,34]
let a=[Link]()
[Link](a)
output:
10,20,11,23,42,87,34

join():
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator.
const array=[10,20,11,23,42,87,34]
let a=[Link](";")
[Link](a)
Output:
10;20;11;23;42;87;34

pop():
The pop() method removes the last element from an array.
The pop() method returns the value that was popped out.
Eg:
const array=[10,20,11,23,42,87,34]
let a=[Link]()
[Link](a)
output:
34

Push():
The push() method adds a new element to an array at the end.
The push() method returns the new length of array.
Eg:
const array=[10,20,11,23,42,87,34]
let a=[Link](100)
[Link](a)
output:

16
suhas@[Link]
8

Shift():
The shift() method removes the first array element and "shifts" all other elements to a lower
index.
The shift() method returns the value that was removed.
Eg:
const array=[10,20,11,23,42,87,34]
let a=[Link]()
[Link](a)
output:
10

unshift():
The unshift() method add the element at first index.
The unshift() method returns the new array length.
Eg:
const array=[10,20,11,23,42,87,34]
let a=[Link]()
[Link](a)
output:
8

Slice()
The slice(start index, end index) method slices out a piece of an array into a new array.
The slice() method creates a new array and does not remove any elements from the source
array.
Start index included
End index excluded(end-1)
Eg:
const array=[10,20,11,23,42,87,34]
let a=[Link](2,6)
output:
11,23,42,87

17
suhas@[Link]
JavaScript Object:
Objects are used to store the data in key-value pair.
const person = {
firstName : "Suhas",
lastName : "S J",
age : 23,
height : 5.7
};

Accessing JavaScript Properties


Syntax:
[Link]
Eg:
[Link]([Link])

objectName["property"]

Eg:
[Link](penson[age])

Adding New Properties


You can add new properties to an existing object by simply giving it a value.
If property is already existing, then that property will be overridden.
[Link] = "India";

Deleting Properties
The delete keyword deletes a property from an object.
const person = {
firstName : "Suhas",
lastName : "S J",
age : 23,
height : 5.7

18
suhas@[Link]
};
delete [Link]
The delete keyword deletes both the value of the property and the property itself.

JavaScript ArrayOfObjects
We can store an objects inside the array.
let obj=[{
name:'Suhas S J',
age:23,
place:'Bangalore',
Height:5.7
},{
name:'Abhi ',
age:24,
place:'Delhi',
Height:5.9
},{
name:'raj',
age:29,
place:'Bangalore',
Height:5.7
},{
name:'pratheek',
age:20,
place:'Bangalore',
Height:6.0
}]

We can acess the individual objects according to the indexes.


We can acess the object property using the index of object and key of object.
[Link](obj[0])//print object at 0 index.

19
suhas@[Link]
[Link](obj[0].name)//print the value of name of object at 0 index and key name.

JavaScript String methods


Length:
The length property returns the length of a string.
Let name= "Suhas S J"
[Link]([Link])

charAt()
The charAt() method returns the character at a specified index in a string.
Let name= "Suhas S J"
[Link]([Link](4))

charCodeAt()
The charCodeAt() method returns the code of the character at a specified index in a string.
Let name= "Suhas S J"
[Link]([Link](4))

slice()
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters
o start position included
o end position excluded

Let name= "Suhas S J"


[Link]([Link](2,7)
slice () will take negative index.
Let name= "Suhas S J"
[Link]([Link](-6,-1))

substring()
substring() is similar to slice().

20
suhas@[Link]
The difference is that start and end values will not take negative index it will be treated as 0.
Let name= "Suhas S J"
[Link]([Link](2,7))

substr()
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part
Let name= "Suhas S J"
[Link]([Link](2,4))

toUpperCase()
convert text to upper case.
Let name= "Suhas S J"
[Link]([Link]())

toLowerCase()
convert text to lower case.
Let name= "Suhas S J"
[Link]([Link]())

trim()
The trim() method removes whitespace from both sides of a string.
Let name= " Suhas S J "
[Link]([Link]())

trimStart()
The trimStart() method will removes whitespace only from the start of a string.
Let name= " Suhas S J "
[Link]([Link]())

trimEnd()
The trimEnd() method will removes whitespace only from the Ending of a string.

21
suhas@[Link]
Let name= " Suhas S J "
[Link]([Link]())

padStart()
The padStart() method pads a string from the start.
Accept 2 parameter
1) max length of the string
2) string to add
Eg:

let a="10"
[Link]([Link](3, "0"))

padEnd()
The padEnt() method pads a string from the End.
Accept 2 parameter
1) max length of the string
2) string to add
Eg:
let a="10"
[Link]([Link](3, "0"))

replace()
This method is used to replace a string with another String.
let name="Suhas"
[Link]([Link]("Suhas","Suhas S J"))

output:
Suhas S J

DOM
DOM Abbreviates to document object model

22
suhas@[Link]
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects with the document as the parent
element.
With the help of DOM, we can access and manipulate the html element in JavaScript.

DOM methods for accessing the element


 accessing HTML elements by id
 accessing HTML elements by tag name
 accessing HTML elements by class name
 accessing HTML elements by CSS selectors

accessing HTML elements by id


Here we will acess the element by id name.
let element=[Link]("id_name")
If the element is found, the method will return the element as an object.
If the element is not found, myElement will contain null.
Eg:
<div id="container"></div>
let element=[Link]('container')

23
suhas@[Link]
accessing HTML elements by tag name
var elem = [Link]("h1")
Here we will acess the element by Tag name.
Eg:
<div id="container"></div>
let element=[Link]('div')

accessing HTML elements by class name


If you want to find all HTML elements with the same class name, use
getElementsByClassName()
var elem = [Link]("main");
Eg:
<div id="container" class="divs"></div>
let element=[Link]('divs')

accessing HTML elements by CSS selectors


If you want to find all HTML elements that matches a specified CSS selector (id, class
names, types,), use the querySelector() method
var elem = [Link](".main")
Eg:
<div id="container" class="divs"></div>
let element=document. querySelector('.divs')

createElement:
This method is used to create an html element.
Eg:
const heading= [Link]('h1')

appendChild:
This method is used to add the element created to html document.
[Link](heading);
Here the element will be added to the body of page
let heading=[Link]('h1')

24
suhas@[Link]
[Link]('container').appendChild(heading)
Here the element will be added in between the element with the id container.

innerHTML:
it is used to add the html content inside the element.
[Link]('container').innerHTML='<h1>Heading 1 created in DOM</h1>'

innerText:
it is used to add the text content inside the element.
[Link]('container').innerText='Text added in dom'

To add the style for the element:


[Link]('container').[Link]='blue'
here we need to write the properties in camelCaseConvention and the value need to be
specified in string format.

remove:
It is used to remove an element from the document.
let heading=[Link]('h1')
[Link]()

setAttribute:
It is used to add an attribute for the element.
let heading=[Link]('h1')
[Link]('class','h1')

let heading=[Link]('h1')
[Link]('id','headings')

removeAttribute:
It is used to remove the attribute from the element.
let div=[Link]('container')
[Link]('id')

25
suhas@[Link]
programme to take input from the user and print the sum in html
document using DOM
<!DOCTYPE html>
<html>
<head>
<title>DOM DEMO</title>
</head>
<body>

<p> The Sum is <span id="sum"> </span></p>

<script>
let num1=Number(prompt("Enter Value of number 1"))
let num2=Number(prompt("Enter Value of number 2"))

let sum=num1+num2

[Link]('sum').innerText=sum
</script>

</body>
</html>

Events in JavaScript
Event are the action or occurrence that happen in the web browser such as click, keypress,
form submission, mouse hover.
JavaScript provide a build in mechanism for handling the events, allow you to create an
interactive web application.
Event Event Handler
click onclick
mouseover onmouseover
mouseout onmouseout

26
suhas@[Link]
mousedown onmousedown
keyup onkeyup
keydown onkeydown
Focus onfocus
Submit onsubmit
onload onload

EventLitesner:
This function that wait for the event to occur and response to it.
Event listener listen for the event and response for the event by calling a function.
addEventListener():
This function is an example of higher order function which will take event as one argument
as a string and a callback function which will affect when the event occurs.

Inline Event Handlers.


Event handlers can directly add as an attribute to the html element .
Eg:
1)
<!DOCTYPE html>
<html>
<head>
<title>DOM DEMO</title>
</head>
<body>
<button onclick="toggle()">Click Here</button>
<script>
function toggle(){
[Link]('Button Clicked By User')
}
</script>
</body>
</html>
2)
<!DOCTYPE html>

27
suhas@[Link]
<html>
<head>
<title>DOM DEMO</title>
</head>
<body onload="loaded()">
<button>Click Here</button>
<script>
function loaded(){
alert('page loaded')
}
</script>
</body>
</html>

DOM Event Handler:


Accessing the element using DOM methods and adding the events using the
addEventListener method.
Eg:
<!DOCTYPE html>
<html>
<head>
<title>DOM DEMO</title>
</head>
<body>
<button id="btn">Click Here</button>
<script>
let btn=[Link]('btn')
[Link]('click’, function(){
alert('Button Clicked')
})
</script>
</body>

28
suhas@[Link]
</html>

Form Validation using DOM and Events


<!DOCTYPE html>
<html>
<head>
<title> JS EVENTS</title>
</head>
<body>
<form id="myform">
<input type="email" id="email" placeholder="Enter Email"><br>
<input type="Password" id="pwd" placeholder="Enter Password"><br>
<input type="Password" id="cpwd" placeholder="Enter Conform Password"><br>
<input type="button" value="Submit" onclick="validateForm()">
</form>
<script>
function validateForm()
{
let email=[Link]('email').value;
let password=[Link]('pwd').value;
let password1=[Link]('cpwd').value;

if(email==''||password==''){
alert('email or password cannot be null')
}
else if(password!=password1){
alert('password mismatch')
}
else{
alert('data saved successfully')
[Link]('email').value=''

29
suhas@[Link]
[Link]('pwd').value=''
[Link]('cpwd').value=''
}
}
</script>
</body>
</html>

This keyword
In JavaScript, the this keyword refers to current object.
Eg:
<!DOCTYPE html>
<html>
<head>
<title>this demo</title>
</head>
<body>
<script>let persion={
fname:'suhas',
lname:'s j',
age:'22',
place:'shivamogga',
detail:function(){
[Link]("Name is "+fname+" "+lname+"age is "+age+" from"+" "+place)
}
}
[Link]()
</script>
</body>
</html>

30
suhas@[Link]
Above code will result in error
To resolve the error we need to use this keyword
Bellow is code for same
let persion={
fname:'suhas',
lname:'s j',
age:'22',
place:'shivamogga',
detail:function()
{
[Link]("Name is "+[Link]+" "+[Link]+"<br> age is "+[Link]+"<br> place
is"+" "+[Link])
}
}
[Link]()

Hoisting:
Hoisting is the default behavior of moving all the declarations at the top of the scope before
code execution.
Note: JavaScript only hoists declarations, not initializations.
JavaScript allocates memory for all variables and functions defined in the program before
execution.
[Link](a)//output undefined
var a=10;

function declarations are hoisted but function expressions are not hoisted.

sayHello() //output: Hi Good Morning


function sayHello(){
[Link]("Hi Good Morning")
}

Here the bellow code will result in error

31
suhas@[Link]
[Link](add(10,20))//error
var add=(a,b)=>{
return a+b
}

Callback Function:
A callback is a function passed as an argument to another function and is invoked after the
execution of main function.
Example:
function getdata(callback){
var name=prompt('enter name')
callback(name)
}
function showdata(name){
[Link](name)
}
Here the getdata function will accept a callback function and after that function executed
completely the show data function will execute.

Example 2:
function getAPIData(callback){
[Link]("Connecting to API")

setTimeout(function(){
[Link]("Accessing data From API")
let status="Success"
callback(status)
},4000)

}
function ShowAPIData(status){
[Link]("Status From API is "+status)

32
suhas@[Link]
}

Here getAPIData will execute first and then that will intern return the ShowAPIData method
and return the status.

JavaScript Error handling:


The try statement defines a code block to run (to try).

The catch statement defines a code block to handle any error.

The finally statement defines a code block to run regardless of the result.

The throw statement defines a custom error.

Try and catch will come in hand to hand if any statement that lead to error then place it in try
block and the corresponding error will be handled by the catch block.

try {
// Block of code to try
}
catch(error) {
// Block of code to handle errors
}
Example:
try{
[Link]("opening file operation")
const a=10;
a=20
[Link]("closing file")
}
catch(error){
[Link]([Link])

33
suhas@[Link]
[Link]([Link])
[Link]([Link])//similar to [Link](error)
}

Finally: it is a block which will execute irrespective of the error.


try {
//Block of code to try
}
catch(err) {
//Block of code to handle errors
}
finally {
//Block of code to be executed regardless of the try / catch result
}

Example:
try{
[Link]("opening file operation")
const a=10;
a=20
[Link]("closing file")
}
catch(error){
[Link]([Link])
[Link]([Link])
[Link]([Link])//similar to [Link](error)
}
finally{
[Link]("closing file operation")
}

34
suhas@[Link]
Asynchronous programming
Programming paradigm where control flow of the programme is not determined by the order
of the statement in programme but the availability of the resource or data.

Promise in JavaScript
These are the way to handle the asynchronous operations.
The promise that represent a value that may be available now or in the future or never.
The promise object can be in any 3 states
1)pending
2)fulfilled
3)Rejected

Creating a promise:
Create a promise using the promise constructor take a function with two parameter resolve
and reject.
Here the promise will be either be resolved or it will be rejected.

Example:
let promDemo=new Promise((resolve, reject)=>{
if(true)
{
resolve('Promise Resolved')
}
else{
reject('Promise Rejected')
}
})

Handling promise result:


We can use .then method to handle the promise result.
If any error occurs, then we use .catch method to handle the result.

35
suhas@[Link]
Eg:
let promDemo=new Promise((resolve, reject)=>{
if(true){
resolve('Promise Resolved')
}
else{
reject('Promise Rejected')
}
})
[Link]((result)=>[Link](result))
.catch((error)=>{ [Link](err
or)
})

Fetch:
Fetch method is used to make a network request or to call a API in Js.
Fetch will return a promise in js.
Eg:
fetch('[Link]
.then((result)=>[Link]())
.then((data)=>[Link](data))
.catch((error)=>[Link](error))

Callback Hell
Callback hell is used to describe the nested callback stacked over bellow one another
formatting a pyramid structure.
Every callback depends/wait for previous callback.

Example:
function getUserDetails(userId, callback) {
fetch(`/user/${userId}`)
.then(response => [Link]())
.then(data => {

36
suhas@[Link]
callback(null, data);
})
.catch(error => {
callback(error, null);
});
}

function getUserPosts(userId, callback) { fetch(`/posts/$


{userId}`)
.then(response => [Link]())
.then(data => {
callback(null, data);
})
.catch(error => {
callback(error, null);
});
}

function getPostComments(postId, callback) { fetch(`/comments/$


{postId}`)
.then(response => [Link]())
.then(data => {
callback(null, data);
})
.catch(error => {
callback(error, null);
});
}

getUserDetails(1, (userError, userData) => {


if (userError) {

37
suhas@[Link]
[Link]('Error fetching user details:', userError);
} else {
getUserPosts([Link], (postsError, userPosts) => {
if (postsError) {
[Link]('Error fetching user posts:', postsError);
} else {
[Link](post => {
getPostComments([Link], (commentsError, comments) => {
if (commentsError) {
[Link]('Error fetching comments for post:', commentsError);
} else {
[Link]('User:', userData);
[Link]('Post:', post);
[Link]('Comments:', comments);
}
});
});
}
});
}
});

async and await:


async: declare a function or method as asynchronous and can pause its execution to wait for
completion of other process.
await: make a suspension point where execution may wait for the result of async function or
methods.

Example:
async function fun1(){
let result=await fetch('[Link]
.then((result)=>[Link]())

38
suhas@[Link]
.then((data)=>[Link](data))
.catch((error)=>[Link](error))
}
fun1()

Template Literals
Template literals provide an easy way to interpolate variables and expressions into strings.
Template literals use back-ticks (``) rather than the quotes ("") to define a string.

Example:
let obj={
name:`suhas`,
age:23,
place: `Bangalore`
detail:function(){
[Link](`name is ${[Link]} and age is ${[Link]} and place is ${[Link]}`)
}
}

[Link]()

Array Destructuring
It is a feature that allow you to extract the value from the array and assign them to different
variable in more concise and reliable manner.

const arr=[10,20,12,13,15]
const[a,b,c]=arr
[Link](a,b,c)//10,20,12
We can swap the value using Destructuring
let a=10;
let b=20

39
suhas@[Link]
[a,b]=[b,a]
Consolelog(a,b)//20,10

Spread operator in Destructuring.


const arr=[10,20,12,13,15] const[a,b,…
c]=arr
[Link](a)//10
[Link](b)//20
[Link](c)//[12,13,15]

default value
we can provide the default value if value not present.
Let a=[10]
const[x,y=20]=a
[Link](a,b)//10,20

object Destructuring
it is a feature that allow you to extract the value from object and assign them from variable.

let obj={
fname:`suhas`,
lname:`sj`
age:23,
place: `Bangalore`
detail:function(){
[Link](`name is ${[Link]} and age is ${[Link]} and place is ${[Link]}`)
}
}

const[fname,lname]=obj

40
suhas@[Link]
Spread operator in Destructuring.

let obj={
fname:`suhas`,
lname:`sj`
age:23,
place:`Bangalore`
detail:function(){
[Link](`name is ${[Link]} and age is ${[Link]} and place is ${[Link]}`)
}
}

const[fname,lname,...detail]=obj

JavaScript closures
A closure can be defined as a JavaScript feature in which the inner function has access to the
outer function variable. In JavaScript, every time a closure is created with the creation of a
function.
The closure has three scope chains listed as follows:
 Access to its own scope.
 Access to the variables of the outer function.
 Access to the global variables.
Example 1:
function outerFunc()
{
var a = 4;
function innerfun()
{
return a;
}
return innerfun;

41
suhas@[Link]
}

var output=outerFunc()
[Link](output())

Example 2:
function fun(a)
{
function innerfun(b){
return a*b;
}
return innerfun;
}
var output = fun(4);
[Link](output(4));

Date Object
Date objects are created with the new Date()
constructor. let date=new Date()
[Link](date)
Wed Feb 07 2024 17:53:52 GMT+0530 (India Standard Time)
Methods of date object:
getDate() method is used to get the current date
[Link]([Link]())//print current date
getMonth() is used to get the current
month. Note: month always start from 0.
[Link]([Link]()+1)//current month (start from 0)
getFullYear() method is used to print current
year. [Link]([Link]())//current year
getHours() method is used to print the current
hour
[Link]([Link]())//print current hour

42
suhas@[Link]
getMinutes() method is used to print current minutes

43
suhas@[Link]
[Link]([Link]())//print current minutes
getSeconds() method is used to print current seconds.
[Link]([Link]())//print current seconds

Math Object
Math is an inbuilt object in JavaScript which can be used to perform some specific math
operation.

[Link]([Link])//print value of PI
[Link](Math.E)//print value of e
[Link]([Link](12,4))//print square root of number
[Link]([Link]())//print random number from 0 to 1
[Link]([Link](2.5))//floor it to nearest integer value
[Link]([Link](2.44))//round to nearest number

44
suhas@[Link]

You might also like