Javascript
Javascript
By RIDDHI RANA
What is Javascript?
• JavaScript is a Scripting Language.
• It is a lightweight programming language.
• It is usually embedded directly into HTML pages.
• It is an interpreted language (means that scripts execute without
preliminary compilation).
• Everyone can use it without purchasing a license.
• It consists of lines of executable computer code.
• It is used to validate the data at the client side.
Why Scripting ?
1. <HTML>
<HEAD>
<SCRIPT language = “JavaScript”>
// Code is Written Here
</SCRIPT>
</HEAD></HTML>
2. <HTML><HEAD></HEAD>
<BODY>
<SCRIPT language = “JavaScript”>
// Code is Written Here
</SCRIPT>
</BODY></HTML>
JavaScript Comments and variable
TYPE Example
String: “Hello”
Number: 4.5
Boolean: true
Null: null
Concat :- +
Control Structures
•If construct
if (condition)
{
statement[s] if true
}
• If . . . else construct
if (condition)
{
statement[s] if true
} else {
statement[s] if false
}
Loops
• for Loop
for ([initial expression]; [condition]; [update expression])
{ statement[s] inside loop}
• for . . . in Loop
for (foobar in object ){ statements }
• while Loop
while (condition){ statements}
• do-while Loop
do {
statements
} while (condition)
Display prime Numbers
<html>
<body>
<script language=“javascript”>
for(i=1;i<=100;i++)
{ c=0;
for(j=1;j<=i;j++)
{ if(i%j==0)
{ c=c+1; }
}
if(c==2)
{ Document.write(i+”prime”);}
}
</script>
</body>
</html>
Arrays
.
•The array is a special type of variable
Syntax :
var arrayname = new Array (size)
Example :
• To declare an array of size 5.
var foobar = new Array (5)
• To assign values to the array
foobar [0] = “Yellow”
foobar [1] = “Red”
foobar [2] = “Orange”
foobar [3] = “Green”
foobar [4] = “Black”
JavaScript Array Sorting
• Values in an array are accessed by the array name and location.. Example: myArray[2];
<HTML><HEAD>
<SCRIPT LANGUAGE = "JavaScript">
var foobar = new Array(4)
foobar[0] = "one“;
foobar[1] = 2;
foobar[2] = 4;
foobar[3] = “4.5”;
for (var i in foobar)
{alert (i + “: ”+foobar[i]+" "+ typeOf(foobar[i]))}
</SCRIPT></HEAD></HTML>
Dense Array
• Array is initialized during declaration called dense array.
• Days=new array{‘mon’,’tue’,’wed’,’thu’,’fri’,’sat’,’sun’}.
Syntax:
function functionName ( [parameter1]. . . [,parameterN] )
{//Satements}
Example:
<HTML><HEAD><TITLE>My First Function </TITLE><SCRIPT>
function showMsg(msg)
{ alert ("The Button Sent: " + msg) }
</SCRIPT></HEAD>
<BODY><FORM>
<INPUT TYPE="BUTTON" NAME="FOOBAR"
VALUE=" Click Me "
onClick=" showMsg('The Button Has Been Clicked')">
</FORM></BODY></HTML>
Document Object Model
window
frame sel to parent
f p
Methods:
• alert()
• confirm()
• prompt()
• open()
• close()
• alert():A small pops up dialogue box and appears in front of the web page
currently in focus.
•It inform the user about the error and its problem.
Example:
<HTML>
<HEAD>
<SCRIPT>
alert ("This Is a JavaScript Alert Dialog")
</SCRIPT>
</HEAD>
</HTML>
Window Object
Methods:
• write()
Accessing document methods:
window.document. methodName ([parameters])
or document . methodName ([parameters])
Example:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
document.write ("<H1 align='center'>Hello World </H1>”)
</SCRIPT></HEAD></HTML>
Location Object
Properties:
• href
• pathname
Accessing location properties:
window.location. propertyName
or location.propertyName
Location Object
Example:
<html><head><title>Location Object</title></head>
<body onLoad="newwindow()">
<h1>Location Properties</h1><hr>
<script language = "javascript">
function newwindow(){
newwindow=window.open("","","HEIGHT=200, WIDTH=300")
newwindow.location.href="hello.htm"
}
document.write("<b> Location pathname = "+ location.pathname +
"</b>.")
</script></body></html>
Location Object
• Methods:
• reload()
Accessing location methods:
window.location. methodName ([parameters])
or location.methodName ([parameters])
<html><body>
<h1>This is the file for location methods !!!!!!!!</h1>
<form ><input type = "text" name = "txt" >
<input type = "button" value = "reload" width = "20" onclick = "toreload()"></form>
<script language = "javascript">
function toreload(){ location.reload(); }
</script></body></html>
History Object
• Methods
• back()
• forward()
• go(number)
Accessing document methods:
window.history. methodName ([parameters])
or history.methodName ([parameters])
Event Handlers
Form Attributes/Properties:
name, action, method, elements[ ]
Form Elements:
• Text object
• Button object
• Checkbox object
• Select object
• Textarea
Accessing a Form:
document.forms[0] or document.formName
Accessing Form elements:
document.forms[0].elements[0] or document.forms[0].elementname or
document.forms[0].element[0] or document.formaname.elementname
Forms and Form Elements
Example:
<html><body>
<form name="frm1">
Name: <input type="text" name="myname">
<input type="button" name="sub1" value= " Show My Name " onClick="showname()">
<script language="JavaScript">
function showname(){
alert ("Your Name is " + document.frm1.myname.value)
}
</script></form>
</body>
</html>
Forms and Form Elements
Example:
<HTML><HEAD><TITLE>JavaScript</TITLE><SCRIPT LANGUAGE="JavaScript">
function checkform(form){
for (var i=0; i< form.elements.length; i++) {
if (form.elements[i].value == "") {
alert ("Fill Out All the Fields")
return false
}
return true}}
</SCRIPT></HEAD><BODY>
<FORM name="frm2" method=“post" onSubmit="return checkform(this)" action=“hello11.htm"> <pre>
<b>UserName:</b><input type="text" name="name1"><br>
<b>Password:</b><input type="password" name="passwd"><br>
<input type="submit" name="sub1" value=" Submit ">
</pre></FORM></BODY></HTML>
String Object
• Property:
length
Example : var len = “Hello World”.length //len=11
• Methods:-
• charAt(position):- Returns the character at that specified position.
Example:
var x = “banana”.charAt(0) //x=“b”
• indexOf(Str [, startIndex]):- Returns the index of the first
occurrence of the search string (Str).
Example: var y = “banana”.indexOf(“a”) //x=1
var y = “banana”.indexOf(“a”,2) //x=3
String Object
• Methods:-
• lastIndexOf(Str [, startIndex]):- Returns the index of the last occurrence of
the search string (Str).
Example var y = “banana”.lastindexOf(“a”) //x=5
substr(start [, len]):- Returns a substring within a string .
Example
var str1 = “Hello”.substr(0,4) //str1 = “Hell”
• toUpperCase():-
"var upstr =“hello”.toUpperCase() // upstr=“HELLO”
• toLowerCase():-
"var lowstr =“HELLO”.toLowerCase() // lowstr=“hello”
Math Object
Properties:
• isNAN(value) : Checks whether the value is a number or not
• parseInt(string) : Converts a string to an integer.
• parseFloat(string) : Converts a string to a float.
Math Object
Example:
<html><body>
<script language="javascript">
var str = "40.6"
document.write ("<br>str is <b>" + str + "</b> str is of type <b>" + typeof(str))
Methods:
• getDate() : Returns the day of the month. (Range is 1 to 31)
• getDay() : Returns the day of the week. (Range is 1 to 7)
• getHours() : Returns the number of elapsed hours in the day. (Range- 0 to 23)
• getMinutes() : Returns the number of elapsed minutes in an hour. (Range- 0 to
59)
• getSeconds() : Returns the number of elapsed seconds in a minute. (Range- 0 to
59)
• getMonth() : Returns the month of the year. (Range- 0 to 11)
• getYear() : Returns the calendar year. (Range- 1970 onwards)
• getTime(): Returns the number of milliseconds elapsed since January
1970.
Date Object
Usage:
new Date (“Month, dd, yyyy, hh:mm:ss”)
new Date (“Month, dd, yyyy”)
new Date (yy,mm,dd,hh,mm,ss)
new Date (yy,mm,dd)
new Date (milliseconds)
Example:
Example:
<html><body>
<script language="javascript">
var today = new Date();
var myBirthDay = new Date(“MAY 14, 1980")
document.write ("Today is <b>" + today)
document.write ("<br></b> MyBirthDay is<b> " + myBirthDay + "</b>")
document.write ("<br>My Date of Birth is<b> " + myBirthDay.getDay() + "</b>");
document.write ("<br>My Year of Birth is<b> " + myBirthDay.getYear() + "</b>");
myBirthDay.setYear(80)
document.write ("<br>My New Year of Birth is<b> " + myBirthDay.getYear() +
"</b>");
</script></body></html>
LOCAL STORAGE &SESSION
STORAGE
Local storage is a feature in web browsers that allows
developers to save data in the user’s browser. It’s part
of the web storage API, together with session storage.
• Local storage works by accepting data in key-value
pairs. It retains the data even when the user refreshes
the page or closes the tab or browser.
DIFFERENCE
The key differences between the two are the lifespan of
the stored data and their scope.
Data in local storage remains available even when the
tab/browser is closed. But closing the tab/browser clears
any data stored in session storage.
• Also, data in local storage is accessible across multiple
browser tabs and windows. On the other hand, data in
session storage is only accessible within specific
browser tabs and is not shared.
How to Store Data in Local
Storage
• To store data in local storage, you use the setItem()
method. This method takes in two arguments, a key and
a value.
• localStorage.setItem(key,value);
How to Read Data From Local
Storage
• To retrieve and use data from local storage, you use the
getItem() method. This method takes in a key as an
argument.
• localStorage.getItem(value);
How to Store and Read Complex Data Values in Local
Storage
1.Persistent data: When you use local storage, the stored data
remains even when the user closes the tab or the browser. This
is useful for saving user preferences, settings, and other
relevant data. It can help create a seamless user experience.
2.Offline access: You can use local storage as a means to cache
data which can be accessed even with limited or no internet.
This makes it a useful feature for apps that rely on caching data
for offline use like news readers, productivity apps, and so on.
3.More storage capacity: Compared to other storage means,
local storage has a relatively high capacity. For example,
cookies are limited to 4 kilobytes per domain. But local storage
can store up to 5 megabytes of data per domain.
Limitations
1.Stores only strings: As you learned earlier, local storage can only store string
values. You can use the JSON stringify and parse methods to work around it.
But some web developers may not prefer it as it can lead to writing complex code
that’s difficult to debug.
2.Security concerns: Data in the local storage can be prone to attacks like
cross-site scripting (XSS). As such, you should be cautious when working with
sensitive information. It’s advisable to assess security implications and consider
other alternatives where necessary.
3.Not accessible to web workers: Local storage is part of the Window object.
As such, it’s tied to the main execution thread of the web page. This means it's
not accessible to web workers. So if you run any background processes, you
cannot use local storage within the web worker scripts.