Sei sulla pagina 1di 28

Advance Java

Java Script Basics


LEVEL PRACTITIONER

About the Author


Created By: Credential Information: Version and Date: Renjith(t-renjith)/ Shanmu (105110) Trainer / Sr Architect 1.0, January 21st 2012

Cognizant Certified Official Curriculum

Icons Used
Hands on Exercise

Questions

Tools

Coding Standards

Test Your nderstandi ng

Case Study

Demonstration

Best Practices & Industry Standards

!or"s#o$

Objectives
After completing this chapter you will be able to understand,
What is java script? How to develop Client Side programming using java script? Basic building bloc s of !ava script"

The need of client side scripting?

A client side script is a small program which is executed by the browsers. Examples : Javascript , VBscript Need of client side script? For validating the user data before it reaches the server. Example: Login name and password fields are mandatory in a login page. Validation can be done by java script. Perform some dynamic functionality based on user navigations. Example: ser hovers above a image! dynamically changes the image. "isable the salary text field if user selects unemployed radio button. &

How client side script works?


A user from #ndia is trying to login a mail application residing in $. Assume that the user forgets to enter the login name and clic%s submit.
Java cript in Bro!ser validates the data.

User submits the login page.

User '(ndia)

erver thro!s an error "login name #andator$%

erver 'U*)
erver validates the login page

No &lient side scripting : #f each transaction &arrow depicted' ta%es ( seconds the total transaction ta%es ) seconds. &lient side script implemented: server calls will not happen if the user data is wrong. Assuming script validation ta%es * second for the validating the login name the transaction could be completed in * second &reducing the response time by )+,'.

'

What is Java

cript?

JavaScript is a client side scripting language which can be used to perform client side operations. -ava scripts are executed by the browser engine. Example: Validations in fields $how tool tips Perform some operations on mouse clic%. .hange a font color on mouse over.

Advantages of Java

cript

-ava $cript is used for performing the basic sanity chec%s on the user re/uest before it is submitted to the server! thus improving the transactions response time. 0his also reduces the load on the server as some logic is executed by the client browser. 0his also reduces the networ% traffic by ensuring that no invalid user re/uests are transmitted over the networ%.

Uses Of Java
.lient side validation

cript?

Examples: .hec% for mandatory fields! numeric validation in salary field.

"ynamic application of styles Examples: .hange the font color of a text dynamically. -ava$cript can react to events li%e onclick , onblur, onfocus etc Examples: Perform a validation on .lic%. 1n focus of a text box clear the values.

How to include !avaScript in H#$% files


+ption , : .an be written inside the page body. 2body3 2script type45text6javascript5 3 66-ava$cript code 26script3 26body3 +ption -: .an be written inside the page header 2head3 2script type45text6javascript5 3 66-ava$cript code 26script3 26head3 +ption .: .an be written as an external java script file and imported to the page

2script type45text6javascript5 src45xxx.js5326script3

+,

Java cript !o"s and !ont"s


7riting scripts in page body is not considered a good practice because it ma%es the page complex to maintain ! results in duplicate scripts across pages and reduces reusability. #t is always recommended to write the script as an external file so that the code can be reused and this also improves performance as the browser caches the scripts ma%ing the page loading faster.

++

Java cript #anguage $onstructs


-ava script is built using the following elements Value! Variables! and Literals 8xpressions and 1perators 9egular 8xpressions $tatements Functions

+2

How to develop a java script function ?


-ava $cript are developed using the 0 cript1 02 cript1 tag. Functions are li%e java methods which executes a specific logic. / simple function to print the date: 2script type45text6javascript53 function print"ate&': document.write&52p35 ; "ate&' ; 526p35'< = 26script3

+3

%alues & %ariables


-ava $cript variables does not have explicit data types. Example: Variables need not be declared as integer! a string or a real. All -ava$cript variables are declared using the %eyword var. Example: var x4> 66 defines a variable x with value >. -ava$cript recogni?es the data type based on the value ovar pi 4 (.*@ A pi is considered a number by the java script engine. o var flag 4 true A flag is considered a boolean variable. o var countryBame 4 C#ndiaD A 0his will be considered as a string.

+%

%alues & %ariables '$ont(


A -ava$cript identifier or name must start with a letter or underscore &5EC' subse/uent characters can also be digits &+F)' Variables cope: o Local variable are declared inside a function o Global variable are declared outside a function Applying var to declare a global variable is optional but var is mandatory for local variables.

+&

#iterals
Literals are fixed values that appear in a -ava $cript program. 3e! Java cript literals, Integer Literals: #ntegers can be expressed in decimal! hexadecimal! and octal. var value4(H< Object Literals : An object literal is a list of ?ero or more pairs of property names and associated values of an object! enclosed in curly braces &:='. var animal4:cat!dog= String Literals : A string literal is ?ero or more characters enclosed in double or single /uotation mar%s. var number4C(HD Float Literals : 9epresents floating point values. var pi4(.*@ +'

$onditional

tate)ents* If++else

6efinition: sed to execute some code if the condition is true and another code if the condition is false. $ntax
if 'condition)4 22code to be executed if condition is true 5 else 4 22code to be executed if condition is not true 5 if 'a1b)4 document.!rite'"a is greater than b%)7 5 else 4 document.!rite'"b is greater than a%)7 5

Example

&'

$onditional

tate)ents* If++else if ++else

$ntax
if 'condition)4 22code to be executed if condition is true 5 else if 'condition2) { 22code to be executed 5 else 4 22code to be executed 5

Example
var time8,97 if 'time0,,)4 document.!rite'":ood #orning%)7 5 else if 'time< !) { document.!rite'":ood Noon%)7 5 else 4 document.!rite'":ood Evening%)7 5

&(

.onditional $tatementsI $witch


6efinition : sed to select a particular bloc% of statements based on the user choice. $imilar to if..8lse..#f $tatement. Example $ntax
s!itch'n) 4 case ,: 22execute code bloc; , brea; 7 case -: 22execute code bloc; brea; 7 default: 22code to be executed if n is different from case , and 5 5 Var n8-7 s!itch'n) 4 case ,: document.!rite'"one%)7 brea; 7 case -: document.!rite'"<!o%)7 brea; 7 default: document.!rite'"invalid choice%)7

.onditional $tatementsI For Loop


6efinition :
var initval7 for'initval8startvalue7initval08endalue7initval8initval=incrval) 4 22code to be executed in loop 5

sed for iterating through a bloc% for the specified number of times.

var i7 for'i8,7i08,>7initval8initval=,) 4 document.!rite'i)7 5

.onditional $tatementsI while and do while Loop


?hile @oop: 0he while loop iterates through a bloc% of code till a specified condition is true.
!hile 'initval08endvalue) 4 ""code to be e#ecuted in loop 5 var i8,7 !hile 'i08,>) 4 document.!rite'i)7 5

6o..?hile : 0he do...while loop is a variant of the while loop. 0his loop will execute the bloc% of code atleast 1B.8! and then it will repeat the loop as long as the specified condition is true.
do 4 ""code to be e#ecuted in loop 5 !hile 'var08endvalue)7 var i8,7 do 4 document.!rite'i)7 5 !hile 'i08,>)7

,-pressions
-ava$cript e#pressions are similar to expressions in any other programming language. <hree t$pes of expressions: ,. -. .. A. /rithmeticI evaluates to a number. $#ample : var sum 4 a ; b< tring: evaluates to a character string. $#ample : var name 45FredC< @ogical: evaluates to true or false. $#ample : var flag 4 a>b; &onditional Expression: A conditional expression can have one of the two values based on a condition. $ntax: var value4&condition' J val* I valH #f condition is true! the expression has the value of val*! 1therwise it has the value of valH. Example: status 4 &age 34 *K' J 5adult5 I 5minorD Assigns the value 5adult5 to the variable status if age is eighteen or greater. 1therwise! it assigns the value 5minor5 to status.

22

Operators
-ava$cript operators are similar to the operators in any other programming language. -ava$cript supports the following types of operators *. Arithmetic A $#ample: ;! L H. Mitwise A $#ample: N! O (. .omparison A $#ample: 3! 2 and P4 @. Assignment F $#ample: 4 Q. Logical F $#ample: OO! RR

23

Ti)e To .eflect

Associates to /uic%ly summari?e the following before ending the session 7hat ma%es java script useful for form validationJ Sow to declare a variable in java scriptJ 7hat is the tag used to declare java script codeJ 7hat is the construct used for executing a statement repeatedlyJ

2%

#end a Hand / Java

cript !e)o

+bBective: 0his is a demo to show how to write a java script method inside a S0TL page. Croblem: Print the first HQ odd numbers using -ava$cript. &omponents to be developed I myPage.html

2&

#end a Hand /)01age+ht)l


.reate an html page myPage.html which produces the output as shown below

2'

#end a Hand /)01age+ht)l '$ode(

"ocument.write&' method for writing to the page

2(

Advance Java

You have successfully completed JavaScript Basics

Potrebbero piacerti anche