JavaScript Notes (1)
JavaScript Notes (1)
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.
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;
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.
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
Given that y=5, the table below explains the arithmetic operators:
* 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
+= X+=Y X=X+Y X = 15
*= X*=Y X=X*Y X = 50
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:
=== Is exactly equal to (value and type) x===5 is true, x==="5" is false
4
n
>= Greater than equal to x>=8 is false
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:
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
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”)
}
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
9
suhas@[Link]
}
Output:
0
1
2
3
4
5
6
7
8
9
10
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
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
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.
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 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.
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.
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
};
objectName["property"]
Eg:
[Link](penson[age])
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
}]
19
suhas@[Link]
[Link](obj[0].name)//print the value of name of object at 0 index and key name.
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
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.
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')
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'
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>
<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.
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>
28
suhas@[Link]
</html>
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.
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.
The finally statement defines a code block to run regardless of the result.
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)
}
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')
}
})
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);
});
}
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);
}
});
});
}
});
}
});
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
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]