Unit-2
Unit-2
Unit-2
By
Dr. CH Mahender Reddy
Contents:
• JavaScript: Introduction,
• Functions,
• Arrays,
• DOM,
• Built-in Objects,
• Regular Expression,
• Event handling,
• Validation,
• Dynamic documents
Introduction:
• JavaScript is an object-based scripting language that is lightweight and cross-platform.
• JavaScript is not compiled but translated. The JavaScript Translator (embedded in the browser) is
responsible for translating the JavaScript code.
• Client-side JavaScript does not allow the reading or writing of files. This has been kept for security
reasons.
• JavaScript cannot be used for networking applications because there is no such support available.
• Microsoft FrontPage − Microsoft has developed a popular HTML editor called FrontPage.
FrontPage also provides web developers with several JavaScript tools to assist in the creation of
interactive websites.
• The specification for JavaScript 2.0 can be found on the following site: http://www.ecmascript.org/
• JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> tag.
• You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it
is normally recommended that you should keep it within the <head> tags.
• The <script> tag alerts the browser program to start interpreting all the text
between these tags as a script. A simple syntax of your JavaScript will appear as
follows.
<script ...>
JavaScript code
</script>
• The script tag takes two important attributes −
• Language − This attribute specifies what scripting language you are using. Typically, its value
will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased
out the use of this attribute.
• Type − This attribute is what is now recommended to indicate the scripting language in use and
its value should be set to "text/javascript".
• You can use spaces, tabs, and newlines freely in your program and you are free to format and
indent your programs neatly and consistently which makes the code easy to read and understand.
Semicolons are Optional
• Simple statements in JavaScript are generally followed by a semicolon character, just as they are in
C, C++, and Java.
• JavaScript, however, allows you to omit this semicolon if each of your statements are placed on a
separate line.
• So the identifiers Time and TIME will convey different meanings in JavaScript.
• NOTE − Care should be taken while writing variable and function names in JavaScript.
• All the modern browsers come with built-in support for JavaScript. Frequently, you may need to
enable or disable this support manually.
JavaScript in Internet Explorer:
• Here are simple steps to turn on or turn off JavaScript in your Internet Explorer −
• Follow Tools → Internet Options from the menu.
• Select Security tab from the dialog box.
• Click the Custom Level button.
• Scroll down till you find Scripting option.
• Select Enable radio button under Active scripting.
• Finally click OK and come out
• To disable JavaScript support in your Internet Explorer, you need to select Disable radio button
under Active scripting.
JavaScript in Firefox:
• Here are the steps to turn on or turn off JavaScript in Firefox −
• Open a new tab → type about: config in the address bar.
• Then you will find the warning dialog. Select I’ll be careful, I promise!
• Then you will find the list of configure options in the browser.
• In the search bar, type javascript.enabled.
• There you will find the option to enable or disable javascript by right-clicking on the value of that
option → select toggle.
• If javascript.enabled is true; it converts to false upon clicking toogle. If javascript is disabled; it
gets enabled upon clicking toggle.
JavaScript in Chrome:
• Here are the steps to turn on or turn off JavaScript in Chrome −
• Click the Chrome menu at the top right hand corner of your browser.
• Select Settings.
• Click Show advanced settings at the end of the page.
• Under the Privacy section, click the Content settings button.
• In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all sites to
run JavaScript (recommended)".
JavaScript in Opera:
• Here are the steps to turn on or turn off JavaScript in Opera −
• Follow Tools → Preferences from the menu.
• Select Advanced option from the dialog box.
• Select Content from the listed items.
• Select Enable JavaScript checkbox.
• Finally click OK and come out.
• To disable JavaScript support in your Opera, you should not select the Enable JavaScript
checkbox.
Warning for Non-JavaScript Browsers
If you have to do something important using JavaScript, then you can display a warning
message to the user using <noscript> tags.
You can add a noscript block immediately after the script block as follows −
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>
Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the
message from </noscript> will be displayed on the screen.
JavaScript Where To:
The <script> Tag
In HTML, JavaScript code must be inserted between <script> and </script> tags.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
</body>
</html>
• There is flexibility given to include JavaScript code anywhere in an HTML document. However,
the most preferred ways to include JavaScript in an HTML file are as follows −
• Script in <head>...</head> section.
• Script in <body>...</body> section.
• Script in <body>...</body> and <head>...</head> sections.
• Script in an external file and then include in <head>...</head> section.
JavaScript in <head>...</head> section
• If you want to have a script run on some event, such as when a user clicks somewhere, then you
will place that script in the head as follows −
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
JavaScript in <body>...</body> section
• If you need a script to run as the page loads so that the script generates content on the page, then
the script goes in the <body> portion of the document. In this case, you would not have any
function defined using JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
JavaScript in <body> and <head> Sections:
<html> <body>
<head> <script type="text/javascript">
<script type="text/javascript"> <!--
<!-- document.write("Hello World")
function sayHello() { //-->
alert("Hello World") </script>
} <input type="button" onclick="sayHello()"
//--> value="Say Hello" />
</body>
</script>
</head> </html>
JavaScript in External File:
• External scripts are practical when the same code is used in many different web pages.
• JavaScript files have the file extension .js.
• To use an external script, put the name of the script file in the src (source) attribute of a <script>
tag:
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body> Filename.js
.......
</body> function sayHello() {
alert("Hello World")
</html> }
JavaScript Comment:
• The JavaScript comments are a meaningful way to deliver the message.
• It is used to add information about the code, warnings, or suggestions so that end users can easily
interpret the code.
• The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.
• There are two types of comments in JavaScript.
1. Single-line Comment
It is represented by double forward slashes (//).
2. Multi-line Comment
It is represented by a forward slash with an asterisk then an asterisk with a forward
slash. For example: /* your code here */
JavaScript Variable:
• A JavaScript variable is simply the name of the storage location. There are two types of variables
in JavaScript: local variable and global variable.
• There are some rules while declaring a JavaScript variable (also known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After the first letter we can use digits (0 to 9), for example, value1.
• JavaScript variables are case sensitive, for example x and X are different variables
• Correct JavaScript variables
var x = 10;
var _value="sonoo";
• Incorrect JavaScript variables
var 123=30;
var *aa=320;
JavaScript local variable:
• A JavaScript local variable is declared inside a block or function. It is accessible within
the function or block only. For example:
<script>
function abc(){
var x=10;//local variable
}
</script>
Or,
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
JavaScript global variable:
• A JavaScript global variable is accessible from any function. A variable i.e. declared outside the
function or declared with a window object is known as a global variable. For example:
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
Scope of variables:
var let const
The scope of a var variable is The scope of a let variable is block The scope of a const variable is
functional scope. scope. block scope.
It can be updated and re-declared It can be updated but cannot be re- It cannot be updated or re-declared
into the scope. declared into the scope. into the scope.
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 20%10 = 0
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9
JavaScript Comparison Operators:
• The JavaScript comparison operator compares the two operands. The comparison operators are as follows:
= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
-= Subtract and assign var a=20; a-=10; Now a = 10
*= Multiply and assign var a=10; a*=20; Now a = 200
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0
JavaScript Special Operators:
• The following operators are known as JavaScript special operators.
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.
, Comma Operator allows multiple expressions to be evaluated as single statement.
delete Delete Operator deletes a property from the object.
In In Operator checks if object has the given property
instanceof checks if the object is an instance of given type
new creates an instance (object)
typeof checks the type of object.
void it discards the expression's return value.
yield checks what is returned in a generator by the generator's iterator.
Control Statements:
• JavaScript supports conditional statements which are used to perform different actions based on
different conditions. Here we will explain the if.. else statement.
• Flow Chart of if-else
• The following flow chart shows how the if-else statement works.
• JavaScript supports the following forms of if..else statement −
• if statement
• if...else statement
• if...else if... statement.
JavaScript If statement:
• It evaluates the content only if the expression is true. The signature of the JavaScript if statement is
given below.
if(expression){
//content to be evaluated
}
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
JavaScript If...else Statement:
• It evaluates the content and whether the condition is true or false. The syntax of JavaScript if-else
statement is given below.
if(expression){
//content to be evaluated if the condition is true
}
else{
//content to be evaluated if the condition is false
}
<script>
var a=20;
if(a%2==0){
document.write("a is even number"); }
else{
document.write("a is odd number"); }
</script>
JavaScript If...else if statement:
• It evaluates the content only if the expression is true from several expressions. The signature of the
JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
The while Loop
• The most basic loop in JavaScript is the while loop
The purpose of a while loop is to execute a
statement or code block repeatedly as long as
an expression is true.
• Once the expression becomes false, the loop
terminates.
The while Loop
• Syntax
• The syntax of while loop in JavaScript is as follows −
while (expression)
{
Statement(s) to be executed if expression is true
}
The do...while Loop
• The do...while loop is similar to
the while loop except that the condition
check happens at the end of the loop.
• This means that the loop will always be
executed at least once, even if the
condition is false.
The do...while Loop
• Syntax
• The syntax for do-while loop in JavaScript is as follows −
Do
{
Statement(s) to be executed;
} while (expression);
The for loop
• The 'for' loop is the most compact form of looping. It includes the
following three important parts −
• The loop initialization where we initialize our counter to a starting
value. The initialization statement is executed before the loop begins.
• The test statement which will test if a given condition is true or not. If
the condition is true, then the code given inside the loop will be
executed, otherwise the control will come out of the loop.
The for loop
The syntax of for loop is JavaScript is as follows −
• Using the example above, toCelsius refers to the function object, and toCelsius() refers to the
function result.
• Functions Used as Variable Values
• Functions can be used the same way as you use variables, in all types of formulas, assignments,
and calculations.
JavaScript Function Example:
• Let’s see the simple example of a function in JavaScript that does not have arguments.
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
JavaScript Function Arguments:
• We can call functions by passing arguments. Let’s see the example of a function that has one
argument.
<script>
function getcube(number=5){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Function with Return Value:
• We can call a function that returns a value and use it in our program. Let’s see the example of a
function that returns value.
<script>
function getInfo(){
return "hello world!! How are you?";
}
</script>
<script>
document.write(getInfo());
</script>
JavaScript Function Object:
• In JavaScript, the purpose of a Function constructor is to create a new Function object. It
executes the code globally. However, if we call the constructor directly, a function is created
dynamically but in an unsecured way.
• Syntax
new Function ([arg1[, arg2[, ....argn]],] functionBody)
• Parameter
• arg1, arg2, ...., argn - It represents the argument used by the function.
• functionBody - It represents the function definition.
JavaScript Function Object Examples:
<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>
<script>
var pow=new Function("num1","num2","return Math.pow(num1,num2)");
document.writeln(pow(2,3));
</script>
JavaScript Function Methods:
• Let's see function methods with description.
Method Description
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
JavaScript array constructor (new keyword)
• Here, you need to create an instance of an array by passing arguments in the
constructor
<script>
var emp=new Array("Jai",“lava",“kusa");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
• Changing an Array Element
cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
• Converting an Array to a String
• The JavaScript method toString() converts an array to a string of (comma-separated) array
values.
fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
• Arrays are Objects
• Arrays are a special type of objects. The type of operator in JavaScript returns "object"
for arrays.
• But, JavaScript arrays are best described as arrays.
• Arrays use numbers to access their "elements". In this example, person[0] returns
John:object
• person = {firstName:"John", lastName:"Doe", age:46};
• Accessing the First Array Element
fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[0];
• Accessing the Last Array Element
let fruit = fruits[fruits.length - 1];
• Adding Array Elements
• The easiest way to add a new element to an array is using the push() method:
fruits.push("Lemon");
• A new element can also be added to an array using the length property:
fruits[fruits.length] = "Lemon";
• Associative Arrays
• Many programming languages support arrays with named indexes.
• Arrays with named indexes are called associative arrays (or hashes).
• JavaScript does not support arrays with named indexes.
• In JavaScript, arrays always use numbered indexes.
person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
• How to Recognize an Array
• A common question is: How do I know if a variable is an array?
• The problem is that the JavaScript operator typeof returns "object":
const fruits = ["Banana", "Orange", "Apple"];
let type = typeof fruits; //object
• To solve this problem ECMAScript 5 (JavaScript 2009) defined a new method
Array.isArray():
Array.isArray(fruits); //true
• The instanceof operator returns true if an object is created by a given constructor:
fruits instanceof Array; //true
Array Properties
• Constructor Returns the function that created the Array object's
prototype
• Length Sets or returns the number of elements in an array
• Prototype Allows you to add properties and methods to an Array
object
Array Methods
concat() Joins two or more arrays and returns a copy of the joined arrays
copyWithin() Copies array elements within the array, to and from specified
positions
every() Check if every element in an array passes a test
fill() Fill the elements in an array with a static value
filter() Creates a new array with every element in an array that passes a test
find() Returns the value of the first element in an array that passes a test
findIndex() Returns the index of the first element in an array that passes a test
forEach() Calls a function for each array element
Cont…
indexOf() Search the array for an element and returns its position
isArray() Checks whether an object is an array
join() Joins all elements of an array into a string
lastIndexOf() Search the array for an element, starting at the end, and returns its
position
map() Creates a new array with the result of calling a function for each array
element
pop() Removes the last element of an array and returns that element
push() Adds new elements to the end of an array and returns the new length
• sort() Sorts the elements of an array
• splice() Adds/Removes elements from an array
Cont…
reduce() Reduce the values of an array to a single value (going left-to-right)
reduceRight() Reduce the values of an array to a single value (going right-to-left)
reverse() Reverses the order of the elements in an array
shift() Removes the first element of an array, and returns that element
slice() Selects a part of an array, and returns the new array
some() Checks if any of the elements in an array pass a test
• toString() Converts an array to a string and returns the result
• unshift() Adds new elements to the beginning of an array, and returns the new
length
• valueOf() Returns the primitive value of an array
JavaScript Math Object
• The JavaScript Math object allows you to perform mathematical tasks
on numbers.
• Unlike other objects, the Math object has no constructor.
• The Math object is static.
• All methods and properties can be used without creating a Math
object first.
Math Properties (Constants)
• Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
<html> </script>
<body> </body>
<h2>JavaScript Math Constants</h2> </html>
<p id="demo"></p>
<script> Output:
document.getElementById("demo").innerHTML = JavaScript Math Constants
"<p><b>Math.E:</b> " + Math.E + "</p>" + Math.E: 2.718281828459045
"<p><b>Math.PI:</b> " + Math.PI + "</p>" + Math.PI: 3.141592653589793
"<p><b>Math.SQRT2:</b> " + Math.SQRT2 + "</p>" + Math.SQRT2: 1.4142135623730951
"<p><b>Math.SQRT1_2:</b> " + Math.SQRT1_2 + Math.SQRT1_2: 0.7071067811865476
"</p>" + Math.LN2: 0.6931471805599453
"<p><b>Math.LN2:</b> " + Math.LN2 + "</p>" +
Math.LN10: 2.302585092994046
"<p><b>Math.LN10:</b> " + Math.LN10 + "</p>" + Math.LOG2E: 1.4426950408889634
"<p><b>Math.LOG2E:</b> " + Math.LOG2E + "</p>" Math.Log10E: 0.4342944819032518
+
"<p><b>Math.Log10E:</b> " + Math.LOG10E +
"</p>";
Math Methods
• Number to Integer
• There are 4 common methods to round a number to an integer:
Math.round(x) Returns x rounded to its nearest integer
onmouseout The user moves the mouse away from an HTML element
Example: https://www.geeksforgeeks.org/css-positioning-elements/
Regular Expression
• A regular expression is an object that describes a pattern of characters.
• Regular expressions are used to perform pattern-matching and "search-and-replace"
functions on text.
What Is a Regular Expression?
• A regular expression is a sequence of characters that forms a search pattern.
• When you search for data in a text, you can use this search pattern to describe what you
are searching for.
• A regular expression can be a single character or a more complicated pattern.
• Regular expressions can be used to perform all types of text search and text replace
operations.
• Syntax:
/pattern/modifiers;
Ex:
var patt = /gitam/i
Regular Expression Modifiers
Modifiers can be used to perform case-insensitive more global
searches:
Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all)
m Perform multiline matching
d Perform start and end matching (New in ES2022)
Regular Expression Patterns:
• Brackets are used to find a range of characters:
• Metacharacters are characters with a special meaning
Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
[^abc] Find any character, not inside the brackets
[^0-9] Find any digit not in between the brackets
Metacharacter Description
\. Search single characters, except line terminator or newline.
\w Find the word character i.e. characters from a to z, A to Z, 0 to 9
\d Find a digit
\D Search non-digit characters i.e all the characters except digits
\s Find a whitespace character
\S Find the non-whitespace characters.
\b Find a match at the beginning or at the end of a word
\B Find a match that is not present at the beginning or end of a word.
\0 Find the NULL character.
\n Find the newline character.
\f Find the form feed character
\r Find the carriage return character
\t Find the tab character
\v Find the vertical tab character
\uxxxx Find the Unicode character specified by the hexadecimal number xxxxx
• Quantifiers define quantities:
Quantifier Description
m{X} Find the match of any string that contains a sequence of m, X times
m{X, Y} Find the match of any string that contains a sequence of m, X to Y times
m{X,} Find the match of any string that contains a sequence of m, at least X times
?!m Find the match of any string which is not followed by a specific string m.
Regular Expression Object Methods:
Method Description