0% found this document useful (0 votes)
3 views

3.JAVA SCRIPT

JavaScript is a lightweight, object-oriented programming language primarily used for scripting web pages, enabling dynamic interactivity. It supports both client-side and server-side scripting, with advantages such as speed and simplicity, but has limitations like lack of file access and multithreading. The document covers JavaScript features, syntax, data types, variables, operators, and control structures including conditional statements.

Uploaded by

sharma xerox
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

3.JAVA SCRIPT

JavaScript is a lightweight, object-oriented programming language primarily used for scripting web pages, enabling dynamic interactivity. It supports both client-side and server-side scripting, with advantages such as speed and simplicity, but has limitations like lack of file access and multithreading. The document covers JavaScript features, syntax, data types, variables, operators, and control structures including conditional statements.

Uploaded by

sharma xerox
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

UNIT-III

JAVA SCRIPT
Introduction:
JavaScript (js) is a light-weight object-oriented programming language which is
used by several websites for scripting the webpages.
It is an interpreted, full-fledged programming language that enables dynamic
interactivity on websites when applied to an HTML document. It was introduced in the
year 1995 for adding programs to the webpages.
Features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it
is a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather
than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
8. It provides good control to the users over the web browsers.

JavaScript Syntax:
Java Script can be implemented using JavaScript statements that are placed within the
<script>…</script>
Syntax:
<script language= “javascript” type= “text/javascript”>
JavaScript code
</script>
Language: This attribute specifies what scripting language you are using. Typically, its
value will be “javascript”.
Type:The type attribute specifies the type of the script. The type attribute identifies
the content between the <script> and </script> tags.

Comments:
 Javascript supports both C-style and C++ style comments.
 Any text between a // and the end of a line is treated as a single line comment.
 Any text between the characters /* and */ is treated as a multiline comment.
 Javascript also recognizes the HTML comment opening sequence <!-- and closing
sequence -->.
Client Side Java Scripting:
Client-side scripting simply means running scripts, such as JavaScript, on the
client device, usually within a browser. All kinds of scripts can run on the client side if
they are written in JavaScript, because JavaScript is universally supported.
Advantages:
Speed: Client-side JavaScript is very fast because it can be run immediately within the
client-side browser.
Simplicity: JavaScript is relatively simple to learn and implement.
Popularity: JavaScript is used everywhere on the web.
Interoperability: JavaScript plays nicely with other languages and can be used in a
huge variety of applications.
Server Load: Being client-side reduces the demand on the website server.
Rich Interfaces: Gives the ability to create rich interfaces.
Limitations:
 Client-side JavaScript does not allow the reading or writing of files. It has been kept
for the security reason.
 JavaScript could not used for networking applications because there is no such
support available.
 JavaScript doesn't have any multithreading or multiprocessor capabilities.

Server Side Java Scripting:


Server-side scripts run on the server instead of the client, often in order to
deliver dynamic content to webpages in response to user actions. Server-side scripts
don't have to be written in JavaScript, since the server may support a variety of
languages.
S. No Client-side JS Server-side JS
1 Does not need interaction with Requires interaction with the server
the server

2 Runs on the user’s computer Runs on the web server

3 Reduces load on the server’s Allows the server to provide


proccessing unit dynamic websites tailored to the
user. Increases the processing load
on server.
4 Languages used: HTML, CSS, Languages used: JSP, PHP, ASP.net,
JavaScript Python
Core features
The JavaScript programming language, developed by Netscape. And it is not a
part of Java platform.
JavaScript does not create applets or standalone applications. In its most form,
JavaScript resides inside HTML documents.
Differences between Java and JavaScript:
Sl.No. Java JavaScript
1 Java is an OOP Programming Language JavaScript is an OOP scripting
Language
2 Java creates applications that run in a JavaScript code is run on browser only.
virtual machine or browser.
3 Java code needs to be compiled. JavaScript code are all in text.
4 Java is heavy weight programming JavaScript is light weight programming
Language Language.

JavaScript Error javascript.JSException: Unknown name


When loading the webpage an error is displayed:
JavaScript Error javascript.JSException: Unknown name
Possible causes:
1. JavaScript is not enabled in the browser.
2. The browser does not support JavaScript technology.
3. The web page has a JavaScript programming error.
Adding JavaScript to HTML Pages:
There are following three ways in which users can add JavaScript to HTML
pages.
1. Embedding code
2. External file
1. Embedding code:To add the JavaScript code into the HTML pages, we can use
the <script>.....</script> tag of the HTML that wrap around JavaScript code inside the
HTML program. Users can also define JavaScript code in the <body> section or <head>
section.

Embedded_Js.html OUTPUT
(using head section)
<!DOCTYPE html >
<html>
<head>
<title> page title</title>
<script>
document.write("Welcome to GPRDPGC");
</script>
</head>
<body>
<p>Inthis example we saw how to add
JavaScript in the head section </p>
</body>
</html>
Embedded_Js.html OUTPUT
(using body section)
<!DOCTYPE html >
<html>
<head>
<title> page title</title>
</head>
<body>
<script>
document.write("Welcome to GPRDPGC");
</script>
<p>Inthis example we saw how to add
JavaScript in the head section </p>
</body>
</html>

2. External file: We can also create a separate file to hold the code of
JavaScript with the (.js) extension and later incorporate/include it into our
HTML document using the src attribute of the <script> tag. It becomes
very helpful if we want to use the same code in multiple HTML documents.
It also saves us from the task of writing the same code over and over again
and makes it easier to maintain web pages.
hello.js External.html
function display() { <html>
alert("Hello World!"); <head>
} <meta charset="utf-8">
<title>Including a External JavaScript File</title>
</head>
<body>
<form>
<input type="button" value="Result" onclick="display()"/>
</form>
<script src="hello.js">
</script>
</body>
</html>

OUTPUT
Data types and variables
Javascript Data Types:
JavaScript provides different data types to hold different types of values. There are
two types of data types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
 JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine.
 You need to use var keyword here to specify the data type. It can hold any type of
values such as numbers, strings etc.
For example:

JavaScript primitive data types:


There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description


String represents sequence of characters e.g. "hello"
Number represents numeric values e.g. 100
Boolean represents boolean value either false or true
Undefined represents undefined value
Null represents null i.e. no value at all

JavaScript non-primitive data types:


The non-primitive data types are as follows:
Data Type Description
Object represents instance through which we can access members
Array represents group of similar values
RegExp represents regular expression

JavaScript variables:
A JavaScript variable is simply a name of 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 first letter, we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

Correct Javascript Variables In Correct Javascript Variables


var x = 10; var 123=30;
var _value="sonoo"; var *aa=320;
JavaScript local variable:
A JavaScript local variable is declared inside the block or function. It is
accessible within the function or block only.
For Example:

(or)

JavaScript global variable:


A JavaScript global variable is accessible from any function. A variable i.e.
declared outside the function is called global variable.
For example:
Operators
Operator:
An operator is a symbol that performs some operation on single or multiple
operands (data value) and produces a result.
There are following types of operators in JavaScript.
1. Arithmetic Operators 2. Comparison (Relational) Operators
3. Bitwise Operators 4.Logical Operators
5. Assignment Operators 6. Conditional Operators
7. Special Operators
1)Arithmetic Operators:
Arithmetic operators are used to perform arithmetic operations on the
operands. The following operators are known as JavaScript arithmetic operators.

Operator Description Example


+ 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
2) Comparison (Relational) Operators:
The JavaScript comparison operator compares the two operands. The
comparison operators are as follows:
Operator Description Example
== Is equal to 10==20 = false
=== Identical (equal and of same type) 10==20 = false
!= Not equal to 10!=20 = true
!== Not Identical 20!==20 = false
> Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
< Less than 20<10 = false
<= Less than or equal to 20<=10 = false
3)Bitwise Operators:
The bitwise operators perform bitwise operations on operands. The bitwise
operators are as follows:
Operator Description Example
& Bitwise AND (10==20 & 20==33) = false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) = false
~ Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift with Zero (10>>>2) = 2
4. Logical Operators: In Comparison operators we can check only one condition
at a time. But by using logical operators we can check multiple conditions at a
time.
The following operators are known as JavaScript logical operators.
Operator Description Example
&& Logical AND (10==20 && 20==33) = false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true

5. Assignment Operators:
The following operators are known as JavaScript assignment operators.
Operator Description Example
= 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

6. Conditional Operators:
 Conditional operator is also called ternary operator.
 Conditional operator first it will the check the condition, if the condition is
true then expression-1 value will return otherwise expression-2 will return.
 In conditional operator especially we can use (?) and (:) operators.
Syntax:

7. Special Operators:

The following operators are known as JavaScript special operators.

Operator Description

, Comma Operator allows multiple expressions to be evaluated as single


statement.
new creates an instance (object)

typeof checks the type of object.

Expressions & Statements


Conditional statements are used to decide the flow of execution based on
different conditions. If a condition is true, you can perform one action and if the
condition is false, you can perform another action.

Java scriptsupports the following Conditional statements-


 if statement
 if-else statement
 if-else if statement
 Switch statement
If statement: if statement is the most simple decision making statement. It is used
to decide whether a certain statement or block of statements will be executed or not i.e
if a certain condition is true then a block of statement is executed otherwise not.
Syntax Flow Cart

Example Output
<html> value of a is greater than 10
<body>
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
</body>
</html>

if-else statement:The if statement alone tells us that if a condition is true it will


execute a block of statements and if the condition is false it won’t. But what if we want
to do something else if the condition is false. Here comes the else statement. We can
use the else statement with if statement to execute a block of code when the condition
is false.
Syntax Flow Cart
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

Example Output
<html> a is even number
<body>
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
</body>
</html>

if-else if statement: JavaScript else if statement is used along with


the if statement to define multiple different conditions. When we have to implement
multiple conditions in our script then we can use theif, else if and else statements in
our code.

Syntax Flow Cart


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
}

Example Output
<script type = "text/javaScript"> i is 20
// JavaScript program to illustrate nested-if
statement
vari = 20;
if (i == 10)
document.write("i is 10");
else if (i == 15)
document.write("i is 15");
else if (i == 20)
document.write("i is 20");
else
document.write("i is not present");
< /script>
Switch statement:The JavaScript switch statement is used to execute one code
from multiple expressions. It is just like else if statement. But it is convenient
than if..else..if because it can be used with numbers, characters etc.

Syntax Flow Cart


switch(variable/expression) {
case value1:
// body of case 1
break;

case value2:
// body of case 2
break;

case valueN:
// body of case N
break;

default:
// body of default
}

Example Output
<script> B Grade
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>

JavaScript Looping Statements


The JavaScript loops are used to iterate the piece of code using while, do while
and for loops.
There are four types of loops in JavaScript.
1. while loop
2. do-while loop
3. for loop

1. while loop: The JavaScript while loop iterates the elements for the infinite number of
times. It should be used if number of iteration is not known. The syntax of while loop is
given below.
Syntax flowchart
//initialization
while (condition)
{
code to be executed
increment/decrement
}

Example Output
<!DOCTYPE html> 1
<html>
<body>
2
<script> 3
vari=1; 4
while (i<=5) 5
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>

2. do-while loop: The JavaScript do while loop iterates the elements for the
infinite number of times like while loop. But, code is executed at least once
whether condition is true or false.The syntax of do while loop is given below.
Syntax Flowchart
do{
code to be executed
}while (condition);

Example Output
<!DOCTYPE html> 1
<html> 2
<body>
<script>
3
vari=1; 4
do{ 5
document.write(i + "<br/>");
i++;
}while (i<=5);
</script>
</body>
</html>

3. for loop: The JavaScript for loop iterates the elements for the fixed number of
times. It should be used if number of iteration is known. The syntax of for loop is
given below.
Syntax Flowchart
for (initialization; condition; increment)
{
code to be executed
}

Functions
JavaScript functions are used to perform operations. We can call JavaScript function
many times to reuse the code.
There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need to write many lines
of code each time to perform a common task.
Function Definition:
Before we use the function, we need to define it. The most common way to
define a function in Java script is by using the “function” keyword.
Syntax Example
<script> <script>
function function_name(parameters-list) functionsayHello()
{ {
//statements alert(“Hello”);
} }
</script> </script>

Calling Function: If you want execute the function, you need to call that function. For
that you use the function name with parenthesis brackets given below.
Example:sayHello();
Function Parameters:
Till now, we have seen functions without parameters. But there is facility to pass
parameters while calling a function. We can use the parameters inside the function. A
function can take multiple parameters separated by comma.
Example:
<script>
//function definition
sayHello(name, age)
{
Document.write(name + “ is ” + age + “ years old”);
}
//calling the function
sayHello(“Sai”, 25);
</script>
The return statement:
A Java script function can have an optional return statement. This is required if
you want to return a value from function. This statement should be the last statement
in a function.
Example:
<script>
functiongetWish()
{
return “Welcome to India”;
}
document.write(getWish());
</script>

Objects
Object Introduction:
 An object is a real world entity such as pen, car, chair etc.,
 Java script is also an object oriented programming (OOP) Language.
 A javaScript object is an entity having state and behavior (properties and
method).
 JavaScript is template based not class based. Here, we don't create class to get
the object. But, we direct create objects.
There are three ways to create an object in java script. They are:
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1. By object literal:
Syntax:object={property1:value1,property2:value2.....propertyN:valueN}
Example:
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

Output:102 Shyam Kumar 40000

2. By creating instance of Object directly (using new keyword):


Syntax:var objectname=new Object();
Here, new keyword is used to create object.
Example:
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

Output:101 Ravi 50000


3. By using an object constructor (using new keyword):
 Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.
 Thethis keyword refers to the current object.
Example:
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>

Output:103 VimalJaiswal 30000

Built in objects:
Java script has several built in (or) native objects. These objects are accessible
anywhere in the program.
List of Java script built in objects:
 Number Object
 Boolean Object
 String Object
 Array Object
 Date Object
 Math Object
 RegExp Object

Arrays
An Array object lets you store multiple values in a single variable. It stores a fixed-size
sequence collection of elements of same type.

Syntax:
var fruits = new Array(“apple”, “banana”, “mango”);

 The Array parameter is a list of strings or integers.


 When you specify a single numeric parameter with the Array constructor, you
specify the initial length of the array.

You can also create array by simply assigning values as follows:-


Example:
var fruits = [“apple”, “banana”, “mango”];

 You will use index numbers to access and to set the values inside an array as
follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element
Example:

Example Output
<script> Arun
var i; Varun
var emp = new Array(); John
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

Date and math related objects


Java script Date Object:
The JavaScript date object can be used to get year, month and day. You can
display a timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides
methods to get and set day, month, year, hour, minute and seconds.

Constructor:
You can use 4 variant of Date constructor to create date object.
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)

Date Methods:

Methods Description
getDate() It returns the integer value between 1 and 31 that represents the day
for the specified date on the basis of local time.
getDay() It returns the integer value between 0 and 6 that represents the day of
the week on the basis of local time.
getFullYear() It returns the integer value that represents the year on the basis of local
time.
getHours() It returns the integer value between 0 and 23 that represents the hours
on the basis of local time.
getMilliseconds() It returns the integer value between 0 and 999 that represents the
milliseconds on the basis of local time.
getMinutes() It returns the integer value between 0 and 59 that represents the
minutes on the basis of local time.
getMonth() It returns the integer value between 0 and 11 that represents the month
on the basis of local time.
getSeconds() It returns the integer value between 0 and 60 that represents the
seconds on the basis of local time.
setDate() It sets the day value for the specified date on the basis of local time.
setDay() It sets the particular day of the week on the basis of local time.
setFullYears() It sets the year value for the specified date on the basis of local time.
setHours() It sets the hour value for the specified date on the basis of local time.
setMilliseconds() It sets the millisecond value for the specified date on the basis of local
time.
setMinutes() It sets the minute value for the specified date on the basis of local time.
setMonth() It sets the month value for the specified date on the basis of local time.
setSeconds() It sets the second value for the specified date on the basis of local time.

Example Output
<!DOCTYPE html> Today's day: 24
<html>
<body>
<script>
var date=new Date();
document.writeln("Today's day: "+date.getDate());
</script>
</body>
</html>

Java script Math Object:


The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.

Math Properties:
JavaScript provides 8 mathematical constants that can be accessed as Math properties:
Example:
1. Math.E // returns Euler's number
2. Math.PI // returns PI
3. Math.SQRT2 // returns the square root of 2
4. Math.SQRT1_2 // returns the square root of ½
5. Math.LN2 // returns the natural logarithm of 2
6. Math.LN10 // returns the natural logarithm of 10
7. Math.LOG2E // returns base 2 logarithm of E
8. Math.LOG10E // returns base 10 logarithm of E

Math Methods:
Methods Description
abs() It returns the absolute value of the given number.
ceil() It returns a smallest integer value, greater than or equal to the given number.
cos() It returns the cosine of the given number.
exp() It returns the exponential form of the given number.
floor() It returns largest integer value, lower than or equal to the given number.
log() It returns natural logarithm of a number.
max() It returns maximum value of the given numbers.
min() It returns minimum value of the given numbers.
pow() It returns value of base to the power of exponent.
random() It returns random number between 0 (inclusive) and 1 (exclusive).
round() It returns closest integer value of the given number.

Document Object Model (DOM)


"The W3C Document Object Model (DOM) is a platform and language-neutral interface
that allows programs and scripts to dynamically access and update the content,
structure, and style of a document."

 The DOM is a W3C (World Wide Web Consortium) standard.


 The DOM defines a standard for accessing documents:

The W3C DOM standard is separated into 3 different parts:


 Core DOM - standard model for all document types
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents

HTML DOM:
The HTML DOM is a standard object model and programming interface for
HTML. It defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.

The HTML DOM (Document Object Model)


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:


The HTML DOM Tree of Objects

With the object model, JavaScript gets all the power it needs to create dynamic HTML:
 JavaScript can change all the HTML elements in the page
 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

EVENT HANDLING
JavaScript's interaction with HTML is handled through events that occur when
the user or the browser manipulates a page.

When the page loads, it is called an event. When the user clicks a button, that
click too is an event. Other examples include events like pressing any key, closing a
window, resizing a window, etc.

Developers can use these events to execute JavaScript coded responses, which
cause buttons to close windows, messages to be displayed to users, data to be
validated, and virtually any other type of response imaginable.

Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.

You might also like