M3 ppt1 IntroductionToJavaScript
M3 ppt1 IntroductionToJavaScript
2
HTML is used to create client-side interfaces, but cannot handle client-side activities
to respond to the user.HTML does not provide event-handling facilities. Scripting
provides static HTML pages the ability to make decisions and to perform operations.
The client side processing includes validation, animation and interactive features with
input devices.
A script is a sequence of instructions or commands.
The browser interprets the script while parsing the HTML tags. The
script could do very simple things like validations or some really complex things like
changing the content of the HTML page. One of the most obvious examples could be
- if a user leaves some mandatory fields blank, it does not make sense for the form to
be submitted to the server. This could be trapped at the client itself.
Netscape Communications Corporation developed JavaScript.
Similar to JavaScript , Microsoft introduced JScript and VBScript.
Based on JavaScript and JScript, ECMAScript was introduced.
JavaScript can be supported by all the popular browsers, like IE, Mozilla Firefox.Script
which is executing on a client (browser) known as client side script.Script which is
executing on a Server known as server side script.
Most of the scripts can be used as both client side and server side.
3
Client Side scripting means the script executes on the client side, i.e., the browser
interprets the script embedded in HTML and executes it. This means some of the
application's functionality executes in the browser on the user's workstation. Using
client-side Script yields two main benefits:
First, some application processing tasks are moved off the Web server, allowing
the application, as a whole, to run faster and support more users.
Second, client-side events can provide immediate feedback to the user without
constantly posting data to the server and waiting for a reply. The result is a more
responsive application.
The Client Side Scripting has its own disadvantages too.
Since the browser interprets the script, the scripting language should be selected
with care. Some browsers understand a specific scripting language while others do
not. Hence, your HTML page with client side scripting might work well on one
browser but not on another. For example, if we use VB Script for client side
scripting, it is fully supported by Internet explorer, but not on Netscape
Navigator.
4
JavaScript was born at Netscape as "LiveScript" - a scripting language that could be
used both on the client and server side. It was then renamed "JavaScript" with the
release of Netscape Navigator 2.0. Subsequent releases of the browser have resulted
in more advanced versions of JavaScript.
5
An interpreted language
JavaScript code does not require compilation. The syntax is completely interpreted by the
browser just as it interprets HTML tags.
Embedded within HTML
JavaScript does not require special editor for programs to be written, edited or compiled. It
can be written in any text editor like notepad, textpad or editplus along with the HTML
tag.
Minimal Syntax- Easy to learn
Just by learning few commands and simple syntax rules a complete JavaScript application can
be developed.
Supports quick development
Since JavaScript does not require time-consuming compilation.
Performance
JavaScript can be written such that the HTML file are fairly compact and quite small. This
minimizes storage requirements on the web server and download time for the client.
Designed for programming user events
Supports Object/Event based programming.
Platform Independence/ Architecture Neutral
JavaScript is a programming language that is completely independent of the hardware.
It is understood by any JavaScript enabled browser.
JavaScript program developed on a Unix machine will work perfectly well on a windows
machine.
6
The lexical structure of the programming language defines the set of rules that
specify how the structure of programs will look like.
•Action-oriented model: the events are trigged based on controls on the web page
such as button, check box etc. the information is validated by the JavaScript
•Language is case sensitive . Identifiers and Keywords must always be typed with a
consistent capitalization of letters.
•Optional semicolon : Just as in C,C++ or Java simple statements in JavaScript are
followed by a semicolon(;). This servers as a statement separator, you are allowed to
omit this semicolon if your statements are placed on separate line.
•Comments : it is similar to Java
Single line comment uses //
Multiline comment uses /* and */ is treated as a comment.
7
The <SCRIPT> tag is what allows JavaScript to be included in the HTML page. It looks
something like this –
<SCRIPT Type=“Text/JavaScript”>
(Program goes here)
</SCRIPT>
•LANUAGE attribute indicates the scripting language used for writing the snippet of
the scripting code.
•If you see the LANGUAGE attribute, there is a version number attached to it - this is
recommended to ensure that there are no unpleasant surprises with browsers not
taken into account. The browser will interpret the script with whatever version it has
and this might lead to unexpected results! This could be either a syntax error or a
totally different output.
•The SCRIPT tag can be either in the HEAD tag or the BODY tag. The former is better
in order to separate it from the actual HTML tags. Based on requirement, it can be
written either at the HEAD or BODY section.
•You can use more than one <script> tag in your document.
8
JavaScript can be executed as when the page is loaded by the browser. This can
also be deferred. The code can be executed when the user has trigged some
event.
Immediate mode implies that the code gets executed as the page loads.
This can be done by keeping the SCRIPT tags in the BODY or by trapping the
onload event (events will be dealt with in later chapters).
9
Deferred mode indicates that the script is executed based on some user action
e.g. the clicking of the mouse or the pressing of a button. It is preferred that all
the code that needs to be executed in this fashion be kept in the HEAD tag.
Consider
<html><head>
<script language="JavaScript">
<!--
// Comments : calling function when user clicks
function msg()
{
alert("Hi");
}
//-->
</script>
</head><body><h3>Deferred Script Demo</h3>
<form name="f1"><input type="button" value=" ok " onClick="msg()"> </form>
</body></html>
<!-- , // --> is used to “comment out” or hide the text of the script. Because the
browsers which dose not support JavaScript
will display the JavaScript code as it is if you are not using HTML comments.
Remember that HTML interpreter will interpret HTML and JavaScript interpreter
interpret JavaScript.
10
All JavaScript variables are declared using the keyword var. For example,
var i_Age = 27
var y,z = “20"
var s_Name = "lucky"
i_Num =“5” // variable can be declared just by assigning a value
Notice that there is no variable type that can be declared. The type is automatically
decided by the usage.
One of the main differences between JavaScript and most other languages is that it
does not have explicit data types. There is no way to specify that a particular
variable represents an integer, a string, or a floating-point (real) number. Any
JavaScript variable can be any of these-in fact, the same variable can be interpreted
differently in different contexts.
One rule about variable names: a valid JavaScript variable name must begin
with a letter or with the underscore character (_). Case is important, so that norl,
NoRl, NORL, and _NORL are all valid JavaScript variable names that refer to different
variables.
NOTE :It is advisable that variables be named appropriately with the type of variable
as prefix e.g. i_Interest, s_UserName etc. One thing to remember is that JavaScript is
case-sensitive.
11
Implicit data types and values are as follows:
• A number, such as -5, 0, or 3.3333
• logical values are either true or false
• A string- "Click Here" or "JavaScript"
• null- special value in JavaScript
• A "non-atomic" JavaScript element. It is like function,objects
The value of each variable may differ from one context to another. It is depending
upon the place where the variable is used.
e.g: Consider i_Age=27 z=10 and s_Name=“lucky” are variables
i_Age + z // will result in 37
s_Name+ i_Age // will result in “lucky27”
Here a string is added to a number that results in a string “lucky27” .
• JavaScript will be treating all variables in an expression/statement with the type of first
variable in the expression/statement.This is known as Type casting or Type conversion.
What is the value of an expression such as
A= B + C where C is uninitialized
A will be zero if C is not initialized. So it is a good practice to initialize all the variables to the
default or null values.
12
The standard equality operators (== and !=) compare two operands without
regard to their type.
The strict equality operators (=== and !==) perform equality comparisons on
operands of the same type. Use strict equality operators if the operands must
be of a specific type as well as value or if the exact type of the operands is
important.
The “+” operator can use for concatenation (String addition) of two strings.
13
Conditional Operator (? :)
conditional operator takes three operands. The first operand is condition
checking and the second expression will be executed if the condition returns
true otherwise the third expression will be executed. It is like simple if else
statement.
Example:
document.write(“the greatest value is" + ((a< b ? a:b);
typeof operator
returns the type of operand. It can be string, number ,object or keyword. The
syntax of using typeof is given below
Example:
typeof(age) returns number
typeof 33 returns number
16
17
Example for if...else statement
<script language="JavaScript">
num=11;
document.write("<h3> To find "+num+" is even or odd</h3>");
if(num%2==0){
document.write("<h3>"+num+" is even</h3>");}
else{
document.write("</h3>"+num+" is odd</h3>");}
</script>
The switch statement evaluates the expression and it will be mapped with the case
statements. If none of the catch block matches then it execute the default block. Even if
the default is not found it will execute the next statement after the switch statement.
Break is used to break the cases. If it is not present then statements following the case will
be executed.
18
<script language="JavaScript">
/* Using for Loop */
for(ivar=1;ivar<=50;ivar=ivar+5)
{
document.write("<hr color=red size=3
width="+ivar+"%>");
}
for(ivar=50;ivar>=1;ivar=i-var5)
{
document.write("<hr color=red size=3
width="+ivar+"%>");
}
document.write("<form name='f1'><select name='s1'>");
year=2000;
/* Using While Loop */
while(year<2050)
{
document.write("<option
value="+year+">"+year+"</option>");
year++;
}
document.write("</select></form>");
</script>
19
break: Aborts execution of the loop, drops out of loop to the next statement
following the loop.
Ex:
var ivar = 0
while (ivar < 10)
{
if (ivar==3)
{
document.write("the counter has reached " + ivar);
break;
}
ivar++;
}
Will terminate the loop when the value of i is 3.
continue : Aborts the current iteration and transfers control to the condition
checking in the loop . Loop will continue if it is true.
22
There are two purposes for functions.
1. It is a reusable code which is used to perform the same operation without copying
the code again and again(organizational tool).
2. It is link to event and the web page. eg radio button, Mouse clicks, button presses,
etc.
Functions may also be called with values, known as parameters, which may be used
inside the body of the function.
It can return some values using return statement. Otherwise it is like a void function.
23
JavaScript provides several built-in functions that can be used to perform explicit type
conversion. Some of them are listed below
eval( )
e.g.: var ivalue = eval(“ 10*5+5”)
ivalue will be assigned the value 55 after the execution of this statement.
e.g.: var inum=parseInt(“ 1abc”) // parsing the string which is starting with number-
returns 1
var inum= parseInt(“abc”) // returns NaN
e.g: var fnum=parseFloat(“3.14abc”) // parsing the string which is starting with float
number- returns 3.14
var fnum= parseFloat(“abc”) // returns NaN
isNaN( ) - the result is true if the parameter is number otherwise false.
24
27
28