Java Script
Java Script
UNIT – II
JavaScript (JS)
JavaScript
JavaScript
lightweight,
interpreted,
object-oriented language.
JavaScript
➢ JavaScript, which was originally developed at Netscape by Brendan Eich,
was initially named Mocha but soon after was renamed LiveScript.
➢ Easy to learn.
Limitations
Corporation.
writing code
<html> <html>
<body>
<body>
<script>
<scrip t>
document.write("<h1>This is a heading</h1>");
document.write("Hello World!")
document.write("<p>This is a paragraph</p>");
</script>
</script>
</body> </body>
</html> </html>
JavaScript Comments
Single-line Comment
<script>
// It is single line comment
document.write("Hello Javascript");
</script>
Multi-line Comment
<script>
/* It is multi line comment. It will not be displayed */
document.write("Javascript multiline comment");
</script>
JavaScript Data Types
➢ The data type is a basic type of data that can be used in a program.
• Varfirstname= “Sriram”;
• Varnumber=99;
JavaScript Variables
➢ Rules for variable names
• Variable names can also begin with $ and _ (but we will not use it)
An Integer or a Floating-Point
Number 3, 3.234, 3e-2 etc.
Number
➢Java script is interpreted by the browser when browser finds <script>tag in body of HTML document.
➢Document object has a method write which is used to create script output.
1. Alert box
2. Prompt box
3. Confirm box
Screen output and keyboard input
➢Prompt box:
Screen output and keyboard input
➢Confirm box:
JavaScript Display Possibilities
<script>
document.write(5 + 6);
</script>
</body>
</html>
JavaScript Display Possibilities
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
JavaScript Display Possibilities
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
External JavaScript
➢If you have the same javascript written in different HTML files, you may want to
• Write the script in a separate file
• Give it the extension .js and
• Point to it in the src attribute of the <script> tag
Note: .js file can not contain <script> tag
External JavaScript
➢External Javascript-places script in external file
Methods of window object
Method Description
confirm() Displays the confirm dialog box containing message with ok and cancel button.
Performs action after specified time like calling function, evaluating expressions
setTimeout()
etc.
JavaScript Object
➢Everything in javascript is an object- a String, a Number, an Array, a Date....
➢Even Booleans, Numbers, Strings can be objects (if defined with the new keyword)
➢JavaScript variables can also contain many values. Objects are variables too. But objects can
➢Object values are written as name : value pairs (name and value separated by a colon).
➢Objects are variables too. But objects can contain many values.
➢JavaScript objects are containers for named values called properties or methods.
➢Example:- car
Example:
(Or)
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
JavaScript Object
Example:
person.name=“ John”;
person.age=“20”;
person.height=“6f”;
JavaScript Object
iii. new operator is used by the constructor method
Example:
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
</script>
JavaScript Object method
• Methods are actions that can be performed on objects.
• this keyword:
objectName.methodName()
function definition:
name = person.fullName;
JavaScript Object method
<script>
// Create an object:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
};
document.getElementById("demo").innerHTML = person.fullName();
</script>
Math object in JavaScript
➢Math is not a constructor. All properties and methods of Math are static
<html>
<body>
<script>
function myFunction()
document.getElementById("demo").innerHTML=Math.E;
</script>
</body>
</html>
Math object in JavaScript
Method Description
abs(x) Returns the absolute value of x
x
exp(x) Returns the value of E
max(x, y, z, ..., n) Returns the number with the highest value
min(x, y, z, ..., n) Returns the number with the lowest value
pow(x, y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Returns the value of x rounded to its nearest
integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
The Number object
➢Number objects are created with new Number().
var num = new Number(value);
The Number object
Date object
➢ Displays current date and time of a system.
➢ Date object created with new operator
var today= new Date();
<!DOCTYPE html>
<html>
<body>
<script>
var d=new Date(); Output
document.write(d);
</script>
</body>
</html>
Date object
JavaScript Operators
Arithmetic Operators
Assignment Operators
Logical Operators
Comparision Operators
String Operator
Conditional Operator
Conditional Statement
Conditional Statement
<html>
<head>
var stdmarks;
if(stdmarks>=60)
document.write("passed");
</script>
</head>
</html>
If…else Statement
If…else Statement
<html>
<head>
<title>
</title>
var stdmarks;
if(stdmarks>=60)
document.write("passed");
else
document.write("failed");
</script>
</head>
</html>
If…else if… else Statement
If…else if… else Statement
<html>
<head>
<title>
</title>
var stdmarks;
if(stdmarks>=90)
document.writeln("GRADE A");
elseif(stdmarks>=80)
document.writeln("GRADE B");
elseif(stdmarks>=70)
document.writeln("GRADE C");
elseif(stdmarks>=60)
document.writeln("GRADE D");
else
document.writeln("failed grade");
</script>
</head>
</html>
Switch Case
<html>
<head>
<title>
switch statement
</title>
var choice,n;
n=parseInt(choice);
switch(n) {
break;
break;
break;
break;
default: document.writeln("FAILED");
}</script></head></html>
Control Statements/Loops in JS
For Loop in JS
while Loop in JS
while Loop in JS
Do..while Loop in JS
Do..while Loop in JS
<html>
<head>
<title>
do-while loop
</title>
var i=0;
do
document.writeln("<br>");
i++;
}while(i<=5);
</script>
</head>
</html>
Break and continue in JS
Break and continue in JS
Break and continue in JS
JavaScript Arrays
➢An array is a special variable, which can hold more than one value at a time.
➢JavaScript arrays are used to store multiple values in a single variable.
Creating an Array
var array_name = [item1, item2, ...];
var array_name = new Array(“item1”, ”item2”, ”item3");
var cars = ["Saab", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");
Array indexes start with 0.
➢[0] is the first element. [1] is the second element.
JavaScript Arrays
Access an Array
You can refer to a particular element in an array by referring to the name of the array and
the index number. The index number starts at 0.
var myArray = new Array(3);
myArray[0]=“red”;
myArray[1]=“yellow”;
myArray[2]=“green”;
➢For example, a function can be called when an event occurs, like when the
function functionname()
{
some code to be executed
}
JavaScript Functions and Events
<html>
<body>
<h2>JavaScript Functions</h2>
<p id="demo"></p>
<script>
return p1 * p2;
</script>
</body>
</html>
JavaScript Functions and Events
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
Example on java script for adding numbers
<html>
<head>
<script type="text/javascript">
function add()
{
var a=document.getElementById("t1").value;
var b=document.getElementById("t2").value;
var c=parseInt(a)+parseInt(b);
document.getElementById("res").value=c;
}
</script>
</head>
<body>
<form>
num1:<input type="text" id="t1"/><br/><br/>
num2:<input type="text" id="t2"/><br/><br/>
result:<input type="text" id="res"/><br/><br/>
<input type="button" value="add" onclick="add()"/>
</form>
</body>
</html>
Create objects using functions
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.display=display_inf;
}
P1= new person(“james”, “Bond”,”007”,”brown”);
function display_inf()
{
document.write(“person firstname:”, this.firstname,”<br/>”);
document.write(“person lastname:”, this.lastname,”<br/>”);
}
// call above method display_inf()
P1.display_inf();
Let keyword
• A variable declared with var is defined throughout the program. One of
the issues with using the var keyword was redeclaring a variable inside
a block will also redeclare the variable outside the block.
• var and let are both used for variable declaration in javascript but the
difference between them is that var is function scoped and let is block
scoped.
• let is block-scoped
• let doesn't allow to redeclare Variables
• Redeclaring a variable with var in a different scope or block changes
the value of the outer variable too.
• When a variable declared with var is used in a loop, the value of that
variable changes.
JavaScript Scope
• Scope determines the accessibility (visibility) of variables.
• JavaScript has 3 types of scope:
✓ Block scope
✓ Function scope
✓ Global scope
• Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
• ES6 introduced two important new JavaScript keywords: let and const.
These two keywords provide Block Scope in JavaScript.
• Automatically Global
• If you assign a value to a variable that has not been declared, it will
automatically become a GLOBAL variable.
• Global variables defined with the var keyword belong to the window object
• Global variables defined with the let keyword do not belong to the window
object
Hoisting
• Hoisting is JavaScript's default behavior of moving all declarations to
the top of the current scope (to the top of the current script or the
current function).
• In JavaScript, a variable can be declared after it has been used.
• JavaScript only hoists declarations, not initializations.
<body>
<p id="demo"></p>
<script>
var x = 5; // Initialize x
var y = 7; // Initialize y
</script>
</body>
Differences between var and let keywords
SN var let
1. The var keyword was introduced with The let keyword was added in ES6 (ES 2015)
JavaScript. version of JavaScript.
3. It can be declared globally and can be It can be declared globally but cannot be
accessed globally. accessed globally.
Differences between var and let keywords
SN var let
4. Variable declared with var keyword can be re-declared Variable declared with let keyword can be updated but
and updated in the same scope. not re-declared.
Example: Example:
function varGreeter() function varGreeter()
{ {
var a = 10; let a = 10;
var a = 20; //a is replaced let a = 20; //SyntaxError:
console.log(a); //Identifier 'a' has already been declared
} console.log(a);
varGreeter(); }
varGreeter();
• Strict mode is declared by adding "use strict"; to the beginning of a script or a function.
• Declared at the beginning of a script, it has global scope (all code in the script will execute in strict mode)
• Declared inside a function, it has local scope (only the code inside the function is in strict mode):
• Strict mode changes previously accepted "bad syntax" into real errors.
•
Events
• Javascript detect certain events performed on the browser and provide computation reactions when
event occurred.
• These computations are called event driven programming.
• Event is generate when user clicks on any html element with which javascript should react.
• Event handler is a script that is implicitly executed in response to the appearance of event.
• Examples of html events
• When u click mouse
• Press a key
• When page loaded
• When image loaded
• Input text changed
• When form submitted.
Events
• The change in the state of an object is known as an Event.
• Events are signals fired inside the browser window that notify of changes in the browser or operating
system environment.
• Programmers can create event handler code that will run when an event fires, allowing web pages to
• The process of reacting over the events is called Event Handling. The JS handles the HTML events
Event Handler
• JavaScript objects that fire events have a corresponding "onevent" properties (named by prefixing "on" to the name of
the event). These properties are called to run associated handler code when the event is fired, and may also be called
• The most flexible way to set an event handler on an element is to use the EventTarget.addEventListener method. This
approach allows multiple listeners to be assigned to an element, and for listeners to be removed if needed
JavaScript Functions and Events
➢Mouse events
➢Keyboard events
➢Form events
➢Window/Document events
JS Mouse events
Event Performed Event Handler Description
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
load onload When the browser finishes the loading of the page
resize onresize When the visitor resizes the window of the browser
JavaScript Events and Objects
Event Object
onLoad Body
onUnload Body
onMouseOver Link, Button
onMouseOut Link, Button
onSubmit Form
Button, Checkbox, Submit, Reset,
onClick
Link
JavaScript Click Event
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write(“CBIT");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
JavaScript Mouse Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert(“CBIT");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
JavaScript Focus Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" CBIT";
}
//-->
</script>
</body>
</html>
JavaScript Keydown Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
JavaScript Load Event
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
JavaScript Strings
➢JavaScript strings are for storing and manipulating text.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p id="demo"></p>
<script>
let text = "John Doe"; // String written inside quotes
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
JavaScript Strings
Method Description
➢The Date object provides the date and time information and also provides
various methods.
Creating Date Objects
new Date()
new Date(milliseconds)
new Date(Date string)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
JS Date and Time
const timeNow = new Date();
console.log(timeNow); // shows current date and time
const time1 = new Date(0);
console.log(time1); // Thu Jan 01 1970 05:30:00
const time2 = new Date(100000000000)
console.log(time2); // Sat Mar 03 1973 15:16:40
t
Document Object Model (DOM)
https://software.hixie.ch/utilities/js/live-dom-viewer/
Document Object Model (DOM)
To display Document to the console:
Just type on JavaScript console: document
Then we will get total HTML Page/Document.
To Display DOM Objects on the Console:
console.dir(document)
Observe that Root element of DOM is document.
DOM Attributes:
1) document.URL :This is original URL of the website.
2) document.body :It returns everything inside body.
3) document.head :It returns head of the page.
4) document.links :It returns list of all links of the page.
Document Object Model (DOM)
How to grab HTML Elements from the DOM?
1) document.getElementById()
Returns element with the specified id.
2) document.getElementsByClassName()
Returns list of all elements belongs to the specified class.
3) document.getElementsByTagName()
Returns list of all elements with the specified tag.
4) document.querySelector()
Returns the first object matching CSS style selector.
5) document.querySelectorAll()
Returns all objects Matches the CSS Style Selector.
JavaScript Regular Expressions
➢ In JavaScript, a Regular Expression (RegEx) is an object that describes a
sequence of characters used for defining a search pattern.
/^a...s$/
➢ The pattern is: any five letter string starting with a and ending with s.
https://regex101.com/
Syntax
A regular expression could be defined like this:
var pattern = /pattern/attributes;
pattern:- specifies a regular expression
Attribute:- specify if a search should be global, case-insensitive, etc.
JavaScript Regular Expressions
Create a RegEx
➢ Using a regular expression literal:
cost regularExp = /abc/;
➢ Using the RegExp() constructor function:
const reguarExp = new RegExp('abc');
https://regex101.com/
JavaScript Regular Expressions
Using String Methods
➢ In JavaScript, regular expressions are often used with the two string methods: search() and
replace().
➢ The search() method uses an expression to search for a match, and returns the position of the match.
1. The search method returns the position in the String object at which the pattern matched.
2. If there is no match, search returns –1.
3. The position of the first character in the string is 0.
➢ The replace() method returns a modified string where the pattern is replaced.
JavaScript Regular Expressions
var str = "Rabbits are furry";
if (position >= 0)
else
output:
Executes a search for a match in a string and returns an array of information. It returns null
exec()
on a mismatch.
match() Returns an array containing all the matches. It returns null on a mismatch.
Tests for a match in a string and returns the index of the match. It returns -1 if the search
search()
fails.
Searches for a match in a string and replaces the matched substring with a replacement
replace()
substring.
frog isn’t”:
/\bis\b/
• The pattern does not match the second string because the ‘is’ is followed
<script> </script>
output- is,is
var str="Is this all there is?";
var patt1=/is/gi;
document.write(str.match(patt1));
</script>
Output- Is,is,is
JavaScript Regular Expressions
Do a global, case-insensitive search for "is":
<!DOCTYPE html>
<html>
<body> [abc]
<!DOCTYPE html>
<script>
<html>
var str="Is this all there is?"; <body>
var patt1=/is/gi;
<script>
document.write(str.match(patt1)); var str="Is this all there is?";
</script> var patt1=/[a-h]/g;
document.write(str.match(patt1));
</body> </script>
</html>
</body>
Output- Is,is,is
</html>
output- h,a,h,e,e
JavaScript Regular Expressions
<!DOCTYPE html>
<html>
<body>
<script>
var str="Is this all there is?";
var patt1=/[^a-h]/g;
document.write(str.match(patt1));
</script>
</body>
</html>
Output- I,s, ,t,i,s, ,l,l, ,t,r, ,i,s,?
JavaScript Regular Expressions
Email Validation Example
<html>
<head> <body>
<script> <h3>EMAIL VALIDATION </h3>
function myFunction() { ENTER EMAIL :
var x =
document.getElementById("myText").value;
<input type="text" id="myText">
var y=/^[a-z]{1,20}\d{2}\@[a-z]{2,10}\.[a-
z]{3}$/; <button onClick="myFunction()">Try it</button>
if(x.match(y))
alert(" Valid email "); <p id="demo"> </p>
else </body>
}
</script>
</head>