3.JAVA SCRIPT
3.JAVA SCRIPT
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.
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 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.
(or)
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:
Operator Description
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>
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>
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.
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>
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>
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”);
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>
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>
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.
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.
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.