Unit Iii Java Script: Variables, Operators, Functions, Control Structures, Events, Objects Introduction To Java Script

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

UNIT III

Java Script: Variables, operators, functions, Control structures, Events, objects

Introduction to Java Script:

• JavaScript is a object based scripting language.


• It is designed to enhance web pages that are constructed with HTML
documents.
• Netscape navigator developed the JavaScript.
• Microsoft version of JavaScript is Jscript.
• JavaScript is the most popular scripting language on the internet, and works in
all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and
Safari.
• JavaScript was designed to add interactivity to HTML pages
• JavaScript is usually embedded directly into HTML pages.
• JavaScript is an interpreted language (means that scripts execute without
preliminary compilation)
• Everyone can use JavaScript without purchasing a license.

 Similarities between Java Script & Java:


• Both have same kind of operators.
• Java script uses similar control structures of java.
• Both are used as languages for use on internet.
• Up to concept of method and object , both are same.

 Differences between Java Script & Java:

Java Java script

1.Java is a programming 1.Java script is a scripting


language. language.

2.Java is an object oriented 2.Java script is a object based


language. language.

3.Code is first compiled & then 3.Only code is interpreted.


interpreted.

4.Java is strongly typed


language and type checking can 4. In JS variables need not to be
be done at compile time. declared before their use.

5.Objects in java are static. 5.In JS, objects are dynamic.


Data members and methods are
fixed at compile time.

 Advantages of Java script:

• JavaScript gives HTML designers a programming tool - HTML authors


are normally not programmers, but JavaScript is a scripting language with
a very simple syntax! Almost anyone can put small "snippets" of code into
their HTML pages.
• Javascript can be used as an alternative to java applets.Applets need to
be downloaded even though they are embedded in Html, jS need not to be
downloaded.
• Javascript can get embedded in XHtml.
• JavaScript can react to events - A JavaScript can be effectively used for
interaction with users.Javascript supports all the form elements such as
button,text etc..Simple applications such as Calculators,Calenderscan be
developed using javascript.
• JavaScript can manipulate HTML elements - Using Document Object
Model (DOM), JavaScript can read and change the content of an HTML
element.Hence static web page becomes dynamic.
• JavaScript can be used to validate data - A JavaScript can be used to
validate form input before submitting it to the server.
• JavaScript can be used to detect the visitor's browser - A JavaScript
can be used to detect the visitor's browser, and - depending on the browser
- load another page specifically designed for that browser.
• JavaScript can be used to create cookies - A JavaScript can be used to
store and retrieve information on the visitor's computer.

 How To Develop Java Script:

1. The HTML <script> tag is used to insert a JavaScript into an HTML


document.
The script can be inserted either in <head> section or <body> section or in
both.
Syntax:

<script type=”text/javascript”>
…………………..
</script>

2. Identifiers:

Identifiers are the names given to variables. These variables hold the
data value.
Some of the rules for handling identifiers in java script:
• Identifiers must start with either letter or underscore or dollar sign.
• There is no limit on the length of identifiers,
• The letters of Identifiers are case sensitive.
• Programmer defined variable names must not have upper case letters.

3. Reserved Words:

Reserved words are special words associated with some


meaning.

Some of the words are

break continue delete for if else do while case switch


try catch throw default var return new this function finally

4. Comments:

• Comments will not be executed by JavaScript. Comments can be


added to explain the JavaScript, or to make the code more readable

 The // Single line comment


 The /* */ multi line comment.

5. Semicolon:

While writing java script , the web programmer must give semicolon at
the end of statements.
 Using an Internal JavaScript:

Java script can be placed in head or body section.


Sample program:
<html>
<head>
<title>Internal javascripts</title>
</head>
<body>
<p>Java Scripts</p>
< script type=”text/javascript” >
document.write(“Welcome to JavaScript Language”);
</script>
< /body>
</html>
 Using an External JavaScript:
• JavaScript can also be placed in external files.
• External JavaScript files often contain code to be used on several
different web pages.
• External JavaScript files have the file extension .js
• External script cannot contain the <script></script> tags!
• To use an external script, point to the .js file in the "src" attribute of the
<script> tag.

Advantages of External javascript:

• Script can be hidden from the browser.


• The layout and presentation of the web document can be separated out
from the user interaction through the java script.

Dis advantages of External JavaScript:

• If small piece of JS code has to be embedded In XHTML, then making a


separate file is meaningless.
• If JS is embedded in several places then it is complicated to make
separate file.
Sample program:

External.html
<html>
<head>
<title>External javascripts</title>
</head>
<body>
<p>Java Scripts</p>
< script type=”text/javascript” src=”myscript.js”> </script>
< /body>
</html
myscript.js
document.write(“Welcome to JavaScript Language”);

Variables:

• Variables are "containers" for storing information.


• JavaScript variables are used to hold values or expressions
• A variable can have a short name, like x, or a more descriptive
name, like carname.

Rules for JavaScript variable names:

• Variable names are case sensitive (y and Y are two different variables)
• Variable names must begin with a letter, the $ character, or the underscore
character.
• Try to use descriptive names for variables. This makes the code easier to
understand.

Note: Because JavaScript is case-sensitive, variable names are case-sensitive.

• Java script defines two types of entities primitives and objects.


• The primitives are for storing the values where as objects are for storing the
reference to actual value.

Primitive types: The following are the primitive types in java script.

1. Number
2. String
3. Boolean
4. Undefined
5. Null

Numeric:

 These are called as numbers. Because they can store the number
values.
 These numbers include integer, floating and double values.
 Ex: 10, 5.789

String:

 String literals are sequence of characters.

Note:

 When assigning a text value to a variable, put quotes around the value.
 When assigning a numeric value to a variable, do not put quotes
around the value, if you put quotes around a numeric value, it will be
treated as text.

Boolean:

 The Boolean values are true and false.


 These values can be compared with the variables or can be used in
assignment statement.

Undefined:

 If a variable is explicitly defined and not assigned to any value to it


then it is an undefined.
 If we try to display the undefined value then on the browser, the word
‘undefined’ will be displayed.

Null:

 The null values can be assigned by using the reserved word null .
 The null means no value.
 If we try to access the null value then a runtime error will occurs.
 Declaring (Creating ) JavaScript Variables:

• Creating a variable in JavaScript is most often referred to as "declaring" a


variable.
• JavaScript variables can be declared with the var keyword.
• The value of this variable can be anything. it can be a string or a
number…
• Ex: var x; var empname;

 Assigning values to the variables:

• To assign a value to the variable, use the equal (=) sign.

Var x; x=20; Var str; str=”welcome”;

Ex:

<html>
<head>
<title>Variable declaration</title>
</head>
<body>
<h2>Variable declaration</h2>
<script type="text/javascript">
var a=10,b=15,c;
c=a+b;
document.write("After addition ,the result is:");
document.write(c);
</script>
</body>
</html>

 Scope of the variables:

1. Local variables:

 A variable declared within a JavaScript function becomes LOCAL and


can only be accessed within that function. (The variable has local
scope).Also called as function scope.
 A variable with function scope is called as local variable.
 We can have local variables with the same name in different functions,
because local variables are only recognized by the function in which
they are declared.
 Local variables are deleted as soon as the function is completed.

2. Global variables:

 Variables declared outside a function, become GLOBAL, and all


scripts and functions on the web page can access it. Also called as script
level scope.
 The variable with script scope is called as global variable.
 Global variables are deleted when you close the page.

3. Auto declaration:

 If a variable is used without the var declaration statement, it will be


automatically declared with global scope, become a global variable.

4. Collision:

 If a variable is defined in a function has the same name as a variable


defined outside the function, then the variable outside the function can
not be accessible within this function.

Operators:

o Arithmetic operators
o Assignment operators
o Comparison operators
o Logical operators
o String operators

Arithmetic operators:

Operator Description Example(y=5) Result of


x
+ Addition y+2 7
- Subtraction y-2 3
* Multiplication y*2 10
/ Division y/2 2.5
% Modulus (division y%2 1
remainder)
++ Increment(increases the y++ 6
variable by 1)
-- Decrement(decreases the y-- 4
variable by 1)

Assignment operators:

• Assignment operators are used to assign values to JavaScript variables.

Given that x=10 and y=5, the table below explains the assignment
operators:
Operator Example Same Result
As

= x=y x=5

+= x+=y x=x+y x=15

-= x-=y x=x-y x=5

*= x*=y x=x*y x=50

/= x/=y x=x/y x=2

%= x%=y x=x%y x=0

Comparison operators:

Comparison operators are used in logical statements to determine


equality or difference between variables or values.

Given that x=5, the table below explains the comparison operators:
Operator Description Comparing Returns

== is equal to x==8 false

x==5 true

=== is exactly equal to (value and x==="5" false


type)
x===5 true

!= is not equal x!=8 true

!== is not equal (neither value or x!=="5" true


type)
x!==5 false

> is greater than x>8 false

< is less than x<8 true

>= is greater than or equal to x>=8 false

<= is less than or equal to x<=8 true

Logical operators:

Logical operators are used to determine the logic between variables or values.

Given that x=6 and y=3, the table below explains the logical operators:

Operator Name Example


&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true
String operators:

The + operator can also be used to concatenate (add) string variables or


text values together.

EX: <html>
<head>
<title>String Operators</title>
</head>
<body>
<h2>String Operators</h2>
<script type="text/javascript">
var str1="Welcome";
var str2="MLWEC";
document.write ("<h3>"+str1+"To"+str2+"</h3>");
</script>
</body>
</html>
Conditional Operator:

JavaScript also contains a conditional operator that assigns a value to a


variable based on some condition.

Syntax:
Variable name=(condition)?value1:value2

Java script functions:

• A function is a block of code that executes only when we tell it to execute.


• It can be when an event occurs, like when a user clicks a button, or from a
call within your script, or from a call within another function.
• Separate functions can be created for each task.
• Functions can be placed both in the <head> and in the <body> section of a
document, just make sure that the function exists, when the call is made.

How to Define a Function:

• Define name for it.


• Indicate any values that might be required as arguments.
• Add Statements
Syntax:

Function functionname()
{
some code
}

Example:

<html>
<head>
<script type="text/javascript">
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
</body>
</html>
 Calling a Function with Arguments:

• When calling a function, we can pass along some values to it, these
values are called arguments or parameters.
• These arguments can be used inside the function.
• We can send as many arguments separated by commas (,).

Syntax: myFunction(argument1,argument2)
function myFunction(var1,var2)
{
some code
}
Example:
<html>
<body>
<p>Click the button to call a function with arguments</p>

<button onclick="myFunction('Nalini','Asst.prof')">Click me</button>

<script type="text/javascript">
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script> </body> </html>

 Returning value from the Function:

• Function that result a value must use the return statement.


• This statement specifies the value that will be returned to where the
function was called.
• When using the return statement, the function will stop executing, and
return the specified value.
• Ex:
function myFunction()
{
var x=5;
return x;
}
Control Structures:

• Control structure is essential part of any programming language which is


required to control the logic of the program.
• Conditional statements are used to perform different actions based on
different conditions.
• In Java Script, we have the following control structures:

 if statement - use this statement to execute some code only if a


specified condition is true
 if...else statement - use this statement to execute some code if the
condition is true and another code if the condition is false
 if...else if....else statement - use this statement to select one of
many blocks of code to be executed
 switch statement - use this statement to select one of many blocks
of code to be executed.

 if-Statement:

Use the if statement to execute some code only if a specified


condition is true.

Syntax:
if (condition)
{
code to be executed if condition is true
}

Example:

<html>
<head> <title>if statement</title> </head>
<body>
<h2>if statement</h2>
<script type="text/javascript">
date=new Date();
time=date.getHours();
if(time<12)
document.write("<h3>"+"Gudmorning"+"</h3>");
</script>
</body>
</html>

 if-else Statement:

Use the if....else statement to execute some code if a


condition is true and another code if the condition is not true.
Syntax:
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example:
<html>
<head>
<title>if statement</title>
</head>
<body>
<h2>if statement</h2>
<script type="text/javascript">
date=new Date();
time=date.getHours();
if (time<20)
{
document.write("<h3>"+"Gudmorning"+"</h3>");
}
else
{
document. write("<h3>"+"Gudevening"+"</h3>");
}
</body>
</html>

 if-else Statement
Use the if....else if...else statement to select one of
several blocks of code to be executed.
Syntax:
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2 is
true
}
 switch Statement:

• The switch statement is used to perform different action based on


different conditions.
• The the switch statement to select one of many blocks of code
to be executed.

Syntax:

switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}

Example:

<html>

<body>
<p>Click the button to display what day it is today.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type="text/javascript">
function myFunction()
{
var x;
var d=new Date().getDay();
switch (d)
{
case 0: x="Today it's Sunday"; break;
case 1: x="Today it's Monday"; break;
case 2: x="Today it's Tuesday"; break;
case 3: x="Today it's Wednesday"; break;
case 4: x="Today it's Thursday"; break;
case 5: x="Today it's Friday"; break;
case 6: x="Today it's Saturday"; break;
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
Looping:

In JavaScript, there are two different kinds of loops:

 for - loops through a block of code a specified number of times


 while - loops through a block of code while a specified condition
is true
 A do while –loop runs once before the condition is checked. If the
condition is true, it will continue to run until the condition is true.

Objects:

Methods are the actions that can be performed on objects.

There are several objects in java script programming language.

Object name Purpose of the object


document To get complete control on document along with the
displaying contents.
window To get dialog control and provision for accepting data
from user
Math Used for mathematical functions & standard constants in
mathematics
String String manipulation can be done & generate HTML
markup methods
Date For date manipulations ,mainly to get current date and
time
Number To get number constants
Boolean Wrapper class for Boolean type
Math object:

• Methods in Math object are used for manipulation of numbers and to perform
any common mathematical calculations.
• It contains many rounding methods like floor value, ceil value, round value
and many trigonometric functions like sin, cos and tan functions and other
functions like max, min etc…

Methods in Math Object:

Method Name Purpose Usage


Math.abs(x) Returns the absolute value Math.abs(-30)=30
Math.abs(40)=40
Math.abs(0)=0
Math.ceil(x) Gives nearest integer ,which Math.ceil(5.8)=6
is not less than x. Math.ceil(5.0001)=6
Math.ceil(-5.8)=-5
Math.floor(x) Gives nearest integer ,which Math.floor(5.8)=5
is not greater than x. Math.floor(5.0001)=5
Math.floor(-5.8)=-6
Math.round(x) Rounds x closer to nearest Math.round(5.8)=6
integer Math.round(5.001)=5
Math.max(x,y) Gives maximum value from Math.max(3,5)=5
x,y
Math.min(x,y) Gives minimum value from Math.min(3,5)=3
x,y
Math.log(x) Gives logarithm or base of x Math.log(2)
Math.exp(x) Gives exponential of a given Math.exp(3)
number
Math.pow(x,y) Gives value of x power y Math.pow(2,3)=8
Math.sin(x) Returns the sin value of x. Math.sin(0)=0
Math.cos(x) Returns the cosine value of Math.cos(0)=1
x.
Math.tan(x) Returns the tangent value of Math.tan(45)=1
x.
Math.sqrt(x) Gives square root of x Math.sqrt(4)=2
Math.random(x) Generates a random number Math.random()
between 0 & 1
Example:

<html>

<head>
<title>math functions</title>
</head>
<body>
<center>
<script type="text/javascript">
document.writeln(Math.abs(40));
document.writeln(Math.ceil(40.8));
document.writeln(Math.floor(40.8));
document.writeln(Math.round(40.0004));
document.writeln(Math.max(3,4));
document.writeln(Math.min(78,40));
document.writeln(Math.sqrt(400));
document.writeln(Math.log(4));
document.writeln(Math.exp(4));
</script>
</center>
</body>
</html>

String Object:

• The web content is to be displayed on the web page in string form.


• Java script provides many string functions to process these string objects.
• A string is a collection of objects;these may include any kind of special
characters, digits, normal characters.
• The String object is used to manipulate a stored piece of text.
• String manipulation can be done & generate HTML markup methods

Methods of String Object:

Function name Description


Anystring.toLowerCase() To convert to lowercase
toUpperCase To convert to upper case
charAt(pos) Returns a character at a given position
substr(m,n) Extract n characters from m-th
position
split(delim) Splits the character accrording to
delimeter
concat(str) Concatenates two strings
substring(m,n) Extract characters from m to n but not
including n-th character
S1.big() To display in big text
blink() To display in blink text
bold() To display in bold text
italics() To display in italics text
Small() To display in small text
Strike() To display in strike text

Example:

<html>
<head>
<title>String functions</title>
</head>
<body>
<center>
<script type="text/javascript">
var s1=”hai”, s2=”hello”;
document.writeln(“First string is:”+s1);
document.writeln(“Second string is:”+s2);
document.writeln(“length of fst stringis:”+s1.length());
document.writeln(s1.toUpperCase());
document.writeln(s2.toLowerCase());
document.writeln(“cocatnatingstrings:”+s1.concat(s2));
</script>
</center> </body> </html>
Date Object:

• The Date object is used to work with dates and times.


• Date objects are created with the Date() constructor.
Get Methods:

Meaning
Method
getDate() Returns 1 to 31,day of month
getDay() Returns 0 to 6 ,Sunday to Saturday
getMonth() Returns 0 to 11
getFullYear() Returns four digit year number
getHours() Returns 0 to 23
getMinutes() Returns 0 to 59
getSeconds() Returns 0 to 59
getTime() Rweturns number of millisec from
jan 1970

Set Methods:

Meaning
Method
setDate(v) To Set Date, day, month, full year
setDay(v)
setMonth(v)
setFullYear(y,m,d)
setHours() To Set
setMinutes() hours,minutes,seconds,milliseconds,time
setSeconds()
setTime()
setMilliseconds()

UTC: Universal Time Coordinate

UTC GET Methods:


getUTCDate(), getUTCDay(), getUTCMonth(), getUTCFullYear(),
getUTCHours(), getUTCMinutes(), getUTCSeconds(), getUTCTime()

UTC GET Methods:

setUTCDate(), setUTCDay(), setUTCMonth(), setUTCFullYear(y,m,d) ,


setUTCHours(), setUTCMinutes(), setUTCSeconds(), setUTCTime(),
setUTCMilliseconds()
To Get today’s Time:

<html>
<body>
<script type="text/javascript">
var d=new Date();
document.write(d);
</script>
</body> </html>

To Display a clock on webpage :

<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout(function(){startTime()},500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div> </body> </html>
Boolean Object:

• The Boolean object is used to convert a non-Boolean value to a Boolean


value (true or false).

Sample Program:

<html>
<body>
<script type="text/javascript">
var d=new Boolean(false);
document.write(“<b>”+”The Boolean value is:”);
document.write(temp.toString());
</script>
</body>
</html>

Number Object:

Property Meaning
MAX_VALUE Largest possible number get
displayed
MIN_VALUE Smallest possible number
NaN When not a number,NaN
displyed

Events:

 Events are actions that can be detected by JavaScript.


 Every element on a web page has certain events which can trigger a
JavaScript. For example, we can use the onclick event of a button element to
indicate that a function will run when a user clicks on the button.
 Advantages of Events:

• We can create user interactive forms.


• Validate forms when the elements lost their focus
• We can handle errors
• Process the forms with help of submit button
• Scripts can respond to user interactions
• Change the page accordingly……dynamically
• It makes web pages more interactively and user-friendly.

 Examples of events:

• Clicking a button (or any other HTML element)


• A page is finished loading
• An image is finished loading
• Moving the mouse-cursor over an element
• Entering an input field
• Submitting a form
• A keystroke

Events Attribute Meaning Associated Tags


blur onblur Losing focus <button> , <input>
.<a>, <textarea>
change onchange On occurance of <input> ,
change <textarea>,<select>
click onclick When user clicks <input> .<a>
mouse button
dbclick ondbclick When user double <input> .<a>,
clicks mouse <button>
button
focus onfocus When user <a>, <input> ,
acquires the input <textarea>,<select>
focus
keyup onkeyup When user releases Form elements
the key from
keyboard
keydown on keydown When user presses Form elements
key down
keypress Onkeypress When user presses Form elements
key
mousedown onmousedown When user clicks Form elements
left mouse button
mouseup onmouseup When user releases Form elements
left mouse button
mousemove onmousemove When user moves Form elements
mouse
mouseout onmouseout User moves mouse Form elements
away from some
element
mouseover onmouseover User moves mouse Form elements
away over some
element
load onload After getting <body>
document loaded
reset onreset When reset button <form>
clicked
submit onsubmit Submit button <form>
clicked
select onselect On selection <input>,
<textarea>
unload onunload User exits the <body>
document

Example:

<html>
<head>
<title>onload events</title>
<script type="text/javascript">
function sample()
{
alert("welcome");
}
</script>
</head>
<body onload="sample()">
</body> </html>

You might also like