Sunteți pe pagina 1din 36

JAVASCRIPT INTRODUCTION

JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers, !s, laptops, tablets, smart phones, and more.

JavaScript is a Scripting Language


" scripting language is a lightweight programming language. JavaScript is programming code that can be inserted into HTML pages. JavaScript inserted into HTML pages, can be e#ecuted b$ all modern web browsers. JavaScript is eas$ to learn.

%hat &ou %ill Learn


'elow is a taste of what $ou will learn in this tutorial.

JavaScript( %riting Into HTML )utput *#ample


document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph</p>");

You can only use document.write in the HT ! output. "# you use it a$er the document has loaded% the whole document will &e o'erwri(en.

JavaScript( +eacting to *vents *#ample


<&u(on type)"&u(on" onclic*)"alert(+,elcome-+)">.lic* e-</&u(on>

The alert,- function is not much used in JavaScript, but it is often .uite hand$ for tr$ing out code. The onclic/ event is onl$ one of the man$ HTML events $ou will learn about in this tutorial.

JavaScript( !hanging HTML !ontent


0sing JavaScript to manipulate the content of HTML elements is a ver$ powerful functionalit$.

*#ample
/)document.get0lement1y"d("demo") //2ind the element /.innerHT !)"Hello 3a'a4cript"; //.hange the content

&ou will often see document.get*lement'$I1,2 some id 2-. This is defined in the HTML 1)M. The 1)M ,1ocument )b3ect Model- is the official %4! standard for accessing HTML elements.

JavaScript( !hanging HTML St$les


!hanging the st$le of an HTML element, is a variant of changing an HTML attribute.

*#ample
/)document.get0lement1y"d("demo") //2ind the element /.style.color)"567777"; //.hange the style

JavaScript( 5alidate Input


JavaScript is commonl$ used to validate input.

*#ample
i# is8a8(/) 9alert("8ot 8umeric"):;

1id &ou 6now7


3a'a4cript and 3a'a are two completely di6erent languages% in &oth concept and design. 3a'a (in'ented &y 4un) is a more comple/ programming language in the same category as .. 0. ;<=>= is the o?cial name o# the 3a'a4cript standard. 3a'a4cript was in'ented &y 1rendan 0ich. "t appeared in 8etscape (a no longer e/is@ng &rowser) in 1AAB% and has &een adopted &y 0. ; (a standard associa@on) since 1AAC

Scripts in HTML must be inserted between 8script9 and 8:script9 tags. Scripts can be put in the 8bod$9 and in the 8head9 section of an HTML page.

The 8script9 Tag


To insert a JavaScript into an HTML page, use the 8script9 tag. The 8script9 and 8:script9 tells where the JavaScript starts and ends. The lines between the 8script9 and 8:script9 contain the JavaScript(
<script> alert(" y 2irst 3a'a4cript"); </script>

&ou don't have to understand the code above. Just ta/e it for a fact, that the browser will interpret and e#ecute the JavaScript code between the 8script9 and 8:script9 tags.
Dld e/amples may ha'e type)"te/t/Ea'ascript" in the <script> tag. This is no longer reFuired. 3a'a4cript is the de#ault scrip@ng language in all modern &rowsers and in

HT !B.

JavaScript in 8bod$9
In this e#ample, JavaScript writes into the HTML 8bod$9 while the page loads(

*#ample
<-GD.TYH0 html> <html> <&ody> . . <script> document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph</p>"); </script> . . </&ody> </html>

JavaScript ;unctions and *vents


The JavaScript statements in the e#ample above, are e#ecuted while the page loads. More often, we want to e#ecute code when an event occurs, li/e when the user clic/s a button. If we put JavaScript code inside a function, we can call that function when an event occurs. &ou will learn much more about JavaScript functions and events in later chapters.

JavaScript in 8head9 or 8bod$9


&ou can place an unlimited number of scripts in an HTML document. Scripts can be in the 8bod$9 or in the 8head9 section of HTML, and:or in both. It is a common practice to put functions in the 8head9 section, or at the bottom of the page. This wa$ the$ are all in one place and do not interfere with page content.

" JavaScript ;unction in 8head9


In this e#ample, a JavaScript function is placed in the 8head9 section of an HTML page. The function is called when a button is clic/ed(

*#ample
<-GD.TYH0 html> <html>

8head9 8script9 function m$;unction,< document.get*lement'$Id,2demo2-.innerHTML=2M$ ;irst JavaScript ;unction2> ? 8:script9 8:head9 8bod$9 8h@9M$ %eb age8:h@9 8p id=2demo29" aragraph8:p9 8button t$pe=2button2 onclic/=2m$;unction,-29Tr$ it8:button9 8:bod$9 8:html9

" JavaScript ;unction in 8bod$9


In this e#ample, a JavaScript function is placed in the 8bod$9 section of an HTML page. The function is called when a button is clic/ed(

*#ample
<-GD.TYH0 html> <html> <&ody>

8h@9M$ %eb age8:h@9

8p id=2demo29" aragraph8:p9 8button t$pe=2button2 onclic/=2m$;unction,-29Tr$ it8:button9 8script9 function m$;unction,< document.get*lement'$Id,2demo2-.innerHTML=2M$ ;irst JavaScript ;unction2> ? 8:script9 8:bod$9 8:html9

*#ternal JavaScripts
Scripts can also be placed in e#ternal files. *#ternal files often contain code to be used b$ several different web pages. *#ternal JavaScript files have the file e#tension .3s. To use an e#ternal script, point to the .3s file in the 2src2 attribute of the 8script9 tag(

*#ample
<-GD.TYH0 html> <html> <&ody> <script src)"my4cript.Es"></script> </&ody> </html>

&ou can place the script in the 8head9 or 8bod$9 as $ou li/e. The script will behave as if it was located e#actl$ where $ou put the 8script9 tag in the document.
0/ternal scripts cannot contain <script> tags.

JavaScript Variables
JavaScript variables are 2containers2 for storing information(

*#ample
'ar /)B; 'ar y)>; 'ar I)/Jy;

Much Li/e "lgebra


#=A $=B C=#D$ In algebra we use letters ,li/e #- to hold values ,li/e A-. ;rom the e#pression C=#D$ above, we can calculate the value of C to be @@. In JavaScript these letters are called variables.

JavaScript 5ariables
"s with algebra, JavaScript variables can be used to hold values ,#=A- or e#pressions ,C=#D$-. 5ariable can have short names ,li/e # and $- or more descriptive names ,age, sum, totalvolume-.

Karia&le names must &egin with a le(er Karia&le names can also &egin with L and M (&ut we will not use it) Karia&le names are case sensi@'e (y and Y are di6erent 'aria&les) 1oth 3a'a4cript statements and 3a'a4cript 'aria&les are case<sensi@'e.

JavaScript 1ata T$pes


JavaScript variables can also hold other t$pes of data, li/e te#t values ,name=2John 1oe2-. In JavaScript a te#t li/e 2John 1oe2 is called a string. There are man$ t$pes of JavaScript variables, but for now, 3ust thin/ of numbers and strings.

%hen $ou assign a te#t value to a variable, put double or single .uotes around the value. %hen $ou assign a numeric value to a variable, do not put .uotes around the value. If $ou put .uotes around a numeric value, it will be treated as te#t.

*#ample
'ar pi)N.1O; 'ar name)"3ohn Goe"; 'ar answer)+Yes " am-+;

1eclaring ,!reating- JavaScript 5ariables


!reating a variable in JavaScript is most often referred to as 2declaring2 a variable. &ou declare JavaScript variables with the var /e$word(
'ar carname;

"fter the declaration, the variable is empt$ ,it has no value-. To assign a value to the variable, use the e.ual sign(
carname)"Kol'o";

However, $ou can also assign a value to the variable when $ou declare it(
'ar carname)"Kol'o";

In the e#ample below we create a variable called carname, assigns the value 25olvo2 to it, and put the value inside the HTML paragraph with id=2demo2(

*#ample
<p id)"demo"></p> 'ar carname)"Kol'o"; document.get0lement1y"d("demo").innerHT !)carname;

"t+s a good programming prac@ce to declare all the 'aria&les you will need% in one place% at the &eginning o# your code.

)ne Statement, Man$ 5ariables


&ou can declare man$ variables in one statement. Just start the statement with var and separate the variables b$ comma(
'ar name)"Goe"% age)N7% Eo&)"carpenter";

&our declaration can also span multiple lines(


'ar name)"Goe"% age)N7% Eo&)"carpenter";

5alue = undefined
In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, li/e user input. 5ariable declared without a value will have the value undefined. The variable carname will have the value undefined after the e#ecution of the following statement(
'ar carname;

+eE1eclaring JavaScript 5ariables


If $ou reEdeclare a JavaScript variable, it will not lose its value(. The value of the variable carname will still have the value 25olvo2 after the e#ecution of the following two statements(
'ar carname)"Kol'o"; 'ar carname;

JavaScript "rithmetic
"s with algebra, $ou can do arithmetic with JavaScript variables, using operators li/e = and D(

*#ample
y)B; /)yJ=;

JavaScript Statements
JavaScript is a se.uence of statements to be e#ecuted b$ the browser.

JavaScript Statements
JavaScript statements are 2commands2 to the browser. The purpose of the statements is to tell the browser what to do. This JavaScript statement tells the browser to write 2Hello 1oll$2 inside an HTML element with id=2demo2(
document.get0lement1y"d("demo").innerHT !)"Hello Golly";

Semicolon >
Semicolon separates JavaScript statements. Formall$ $ou add a semicolon at the end of each e#ecutable statement. 0sing semicolons also ma/es it possible to write man$ statements on one line.
You might see e/amples without semicolons. 0nding statements with semicolon is op@onal in 3a'a4cript.

JavaScript !ode
JavaScript code ,or 3ust JavaScript- is a se.uence of JavaScript statements.

10

*ach statement is e#ecuted b$ the browser in the se.uence the$ are written. This e#ample will manipulate two HTML elements(

*#ample
document.get0lement1y"d("demo").innerHT !)"Hello Golly"; document.get0lement1y"d("myG"K").innerHT !)"How are youP";

JavaScript !ode 'loc/s


JavaScript statements can be grouped together in bloc/s. 'loc/s start with a left curl$ brac/et, and end with a right curl$ brac/et. The purpose of a bloc/ is to ma/e the se.uence of statements e#ecute together. " good e#ample of statements grouped together in bloc/s, are JavaScript functions. This e#ample will run a function that will manipulate two HTML elements(

*#ample
#unc@on my2unc@on() 9 document.get0lement1y"d("demo").innerHT !)"Hello Golly"; document.get0lement1y"d("myG"K").innerHT !)"How are youP"; :

JavaScript is !ase Sensitive


JavaScript is case sensitive. %atch $our capitaliCation closel$ when $ou write JavaScript statements( " function get*lement'$Id is not the same as get*lementb$I1. " variable named m$5ariable is not the same as M$5ariable.

%hite Space
JavaScript ignores e#tra spaces. &ou can add white space to $our script to ma/e it more readable. The following lines are e.uivalent(

11

'ar name)"Hege"; 'ar name ) "Hege";

'rea/ up a !ode Line


&ou can brea/ up a code line within a te#t string with a bac/slash. The e#ample below will be displa$ed properl$(
document.write("Hello Q ,orld-");

However, $ou cannot brea/ up a code line li/e this(


document.write Q ("Hello ,orld-");

1id &ou 6now7


3a'a4cript is a scrip@ng language. 4crip@ng code is e/ecuted line &y line while the &rowser reads it. ,ith tradi@onal programming% all the code has to &e compiled &e#ore it can &e

JavaScript If...Else Statements


!onditional statements are used to perform different actions based on different conditions.

!onditional Statements
5er$ often when $ou write code, $ou want to perform different actions for different decisions. &ou can use conditional statements in $our code to do this. In JavaScript we have the following conditional statements(

if statement < use this statement to e/ecute some code only i# a speciRed condi@on is true if...else statement < use this statement to e/ecute some code i# the condi@on is true and another code i# the condi@on is #alse

12

if...else if....else statement < use this statement to select one o# many &loc*s o# code to &e e/ecuted switch statement < use this statement to select one o# many &loc*s o# code to &e e/ecuted

If Statement
0se the if statement to e#ecute some code onl$ if a specified condition is true. Syntax
i# (condition) 9 code to be executed if condition is true :

Fote that if is written in lowercase letters. 0sing uppercase letters ,I;- will generate a JavaScript errorG

*#ample
Ma/e a 2Hood da$2 greeting if the time if less than IJ(JJ(
i# (@me<=7) 9 /)"Sood day"; :

The result of # will be(


Sood day

Fotice that there is no ..else.. in this s$nta#. &ou tell the browser to e#ecute some code onl$ if the specified condition is true.

If...else Statement
0se the if....else statement to e#ecute some code if a condition is true and another code if the condition is not true. Syntax
i# (condition) 9 code to be executed if condition is true :

13

else 9 code to be executed if condition is not true :

*#ample
If the time is less than IJ(JJ, $ou will get a 2Hood da$2 greeting, otherwise $ou will get a 2Hood evening2 greeting
i# (@me<=7) 9 /)"Sood day"; : else 9 /)"Sood e'ening"; :

The result of # will be(


Sood day

If...else if...else Statement


0se the if....else if...else statement to select one of several bloc/s of code to be e#ecuted. Syntax
i# (condition1) 9 code to be executed if condition1 is true : else i# (condition2) 9 code to be executed if condition2 is true : else 9 code to be executed if neither condition1 nor condition2 is true :

*#ample
If the time is less than @J(JJ, $ou will get a 2Hood morning2 greeting, if not, but the

14

time is less than IJ(JJ, $ou will get a 2Hood da$2 greeting, otherwise $ou will get a 2Hood evening2 greeting(
i# (@me<17) 9 /)"Sood morning"; : else i# (@me<=7) 9 /)"Sood day"; : else 9 /)"Sood e'ening"; :

The result of # will be(


Sood day

JavaScript !p"p #!xes


JavaScript has three /ind of popup bo#es( "lert bo#, !onfirm bo#, and rompt bo#.

"lert 'o#
"n alert bo# is often used if $ou want to ma/e sure information comes through to the user. %hen an alert bo# pops up, the user will have to clic/ 2)62 to proceed. Syntax
window.alert("sometext");

The window.alert method can be written without the window prefi#.

*#ample
<-GD.TYH0 html> <html> <head> <script> #unc@on my2unc@on() 9 alert("" am an alert &o/-"); :

15

</script> </head> <&ody> <input type)"&u(on" onclic*)"my2unc@on()" 'alue)"4how alert &o/"> </&ody> </html>

!onfirm 'o#
" confirm bo# is often used if $ou want the user to verif$ or accept something. %hen a confirm bo# pops up, the user will have to clic/ either 2)62 or 2!ancel2 to proceed. If the user clic/s 2)62, the bo# returns true. If the user clic/s 2!ancel2, the bo# returns false. Syntax
window.conRrm("sometext");

The window.confirm,- method can be written without the window prefi#.

*#ample
'ar r)conRrm("Hress a &u(on"); i# (r))true) 9 /)"You pressed DT-"; : else 9 /)"You pressed .ancel-"; :

rompt 'o#
" prompt bo# is often used if $ou want the user to input a value before entering a page. %hen a prompt bo# pops up, the user will have to clic/ either 2)62 or 2!ancel2 to proceed after entering an input value. If the user clic/s 2)62 the bo# returns the input value. If the user clic/s 2!ancel2 the bo# returns null.

16

Syntax
window.prompt("sometext"%"defaultvalue");

The window.prompt,- method can be written without the window prefi#.

*#ample
'ar name)prompt("Hlease enter your name"%"Harry Ho(er"); i# (name-)null UU name-)"") 9 /)"Hello " J name J "- How are you todayP"; :

Line 'rea/s
To displa$ line brea/s inside a popup bo#, use a bac/Eslash followed b$ the character n.

*#ample
alert("HelloQnHow are youP");

JavaScript Functions
" function is a bloc/ of code that will be e#ecuted when 2someone2 calls it(

*#ample
<-GD.TYH0 html> <html> <head> <script> #unc@on my2unc@on() 9 alert("Hello ,orld-"); : </script> </head> <&ody> <&u(on onclic*)"my2unc@on()">Try it</&u(on> </&ody> </html>

17

JavaScript ;unction S$nta#


" function is written as a code bloc/ ,inside curl$ < ? braces-, preceded b$ the function /e$word(
#unc@on functionname() 9 some code to be executed :

The code inside the function will be e#ecuted when 2someone2 calls the function. The function can be called directl$ when an event occurs ,li/e when a user clic/s a button-, and it can be called from 2an$where2 b$ JavaScript code.
3a'a4cript is case sensi@'e. The #unc@on *eyword must &e wri(en in lowercase le(ers% and the #unc@on must &e called with the same capitals as used in the #unc@on name.

!alling a ;unction with "rguments


%hen $ou call a function, $ou can pass along some values to it, these values are called arguments or parameters. These arguments can be used inside the function. &ou can send as man$ arguments as $ou li/e, separated b$ commas ,,my2unc@on(argument1,argument2)

1eclare the argument, as variables, when $ou declare the function(


#unc@on my2unc@on(var1%var2) 9 some code :

The variables and the arguments must be in the e#pected order. The first variable is given the value of the first passed argument etc.

*#ample
<&u(on onclic*)"my2unc@on(+Harry Ho(er+%+,iIard+)">Try it</&u(on> <script> #unc@on my2unc@on(name%Eo&)

18

9 alert(",elcome " J name J "% the " J Eo&); : </script>

The function above will alert 2%elcome Harr$ otter, the %iCard2 when the button is clic/ed. The function is fle#ible, $ou can call the function using different arguments, and different welcome messages will be given(

*#ample
<&u(on onclic*)"my2unc@on(+Harry Ho(er+%+,iIard+)">Try it</&u(on> <&u(on onclic*)"my2unc@on(+1o&+%+1uilder+)">Try it</&u(on>

The e#ample above will alert 2%elcome Harr$ otter, the %iCard2 or 2%elcome 'ob, the 'uilder2 depending on which button is clic/ed.

;unctions %ith a +eturn 5alue


Sometimes $ou want $our function to return a value bac/ to where the call was made. This is possible b$ using the return statement. %hen using the return statement, the function will stop e#ecuting, and return the specified value. Syntax
#unc@on my2unc@on() 9 'ar /)B; return /; :

The function above will return the value A. Fote( It is not the entire JavaScript that will stop e#ecuting, onl$ the function. JavaScript will continue e#ecuting code, where the functionEcall was made from. The functionEcall will be replaced with the returnvalue(
'ar myKar)my2unc@on();

The variable m$5ar holds the value A, which is what the function 2m$;unction,-2

19

returns. &ou can also use the returnvalue without storing it as a variable(
document.get0lement1y"d("demo").innerHT !)my2unc@on();

The innerHTML of the 2demo2 element will be A, which is what the function 2m$;unction,-2 returns. &ou can ma/e a returnvalue based on arguments passed into the function(

*#ample
!alculate the product of two numbers, and return the result(
#unc@on my2unc@on(a%&) 9 return aV&; : document.get0lement1y"d("demo").innerHT !)my2unc@on(O%N);

The innerHTML of the 2demo2 element will be(


1=

The return statement is also used when $ou simpl$ want to e#it a function. The return value is optional(
#unc@on my2unc@on(a%&) 9 i# (a>&) 9 return; : /)aJ& :

The function above will e#it the function if a9b, and will not calculate the sum of a and b.

Local JavaScript 5ariables


" variable declared ,using var- within a JavaScript function becomes L)!"L and can onl$ be accessed from within that function. ,the variable has local scope-. &ou can have local variables with the same name in different functions, because local

20

variables are onl$ recogniCed b$ the function in which the$ are declared. Local variables are deleted as soon as the function is completed.

Hlobal JavaScript 5ariables


5ariables declared outside a function, become HL)'"L, and all scripts and functions on the web page can access it.

The Lifetime of JavaScript 5ariables


The lifetime JavaScript variables starts when the$ are declared. Local variables are deleted when the function is completed. Hlobal variables are deleted when $ou close the page.

"ssigning 5alues to 0ndeclared JavaScript 5ariables


If $ou assign a value to variable that has not $et been declared, the variable will automaticall$ be declared as a HL)'"L variable. This statement(
carname)"Kol'o";

will declare the variable carname as a global variable , even if it is e#ecuted inside a function.

JavaScript $%&' ()& Events


HTML 1)M allows JavaScript to react to HTML events.

*#ample
Mouse Over Me
21

Click Me

+eacting to *vents
" JavaScript can be e#ecuted when an event occurs, li/e when a user clic/s on an HTML element. To e#ecute code when a user clic/s on an element, add JavaScript code to an HTML event attribute(
onclic*)JavaScript

*#amples of HTML events(


,hen a user clic*s the mouse ,hen a we& page has loaded ,hen an image has &een loaded ,hen the mouse mo'es o'er an element ,hen an input Reld is changed ,hen an HT ! #orm is su&mi(ed ,hen a user stro*es a *ey

In this e#ample, the content of the 8h@9 element is changed when a user clic/s on it(

*#ample
<-GD.TYH0 html> <html> <&ody> <h1 onclic*)"this.innerHT !)+Doops-+">.lic* on this te/t-</h1> </&ody> </html>

In this e#ample, a function is called from the event handler(

*#ample
<-GD.TYH0 html> <html> <head> <script> #unc@on changete/t(id)

22

9 id.innerHT !)"Doops-"; : </script> </head> <&ody> <h1 onclic*)"changete/t(this)">.lic* on this te/t-</h1> </&ody> </html>

HTML *vent "ttributes


To assign events to HTML elements $ou can use event attributes.

*#ample
"ssign an onclic/ event to a button element(
<&u(on onclic*)"displayGate()">Try it</&u(on>

In the e#ample above, a function named displa$1ate will be e#ecuted when the button is clic/ed.

"ssign *vents 0sing the HTML 1)M


The HTML 1)M allows $ou to assign events to HTML elements using JavaScript(

*#ample
"ssign an onclic/ event to a button element(
<script> document.get0lement1y"d("my1tn").onclic*)#unc@on()9displayGate():; </script>

In the e#ample above, a function named displa$1ate is assigned to an HTML element with the id=m$'utn2. The function will be e#ecuted when the button is clic/ed.

The onload and onunload *vents


The onload and onunload events are triggered when the user enters or leaves the page. The onload event can be used to chec/ the visitor's browser t$pe and browser version,

23

and load the proper version of the web page based on the information. The onload and onunload events can be used to deal with coo/ies.

*#ample
<&ody onload)"chec*.oo*ies()">

The onchange *vent


The onchange event are often used in combination with validation of input fields. 'elow is an e#ample of how to use the onchange. The upper!ase,- function will be called when a user changes the content of an input field.

*#ample
<input type)"te/t" id)"#name" onchange)"upper.ase()">

The onmouseover and onmouseout *vents


The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML element.

*#ample
" simple onmouseoverEonmouseout e#ample(

Mouse Over Me

The onmousedown, onmouseup and onclic/ *vents


The onmousedown, onmouseup, and onclic/ events are all parts of a mouseEclic/. ;irst when a mouseEbutton is clic/ed, the onmousedown event is triggered, then, when the mouseEbutton is released, the onmouseup event is triggered, finall$, when the mouseE clic/ is completed, the onclic/ event is triggered.

24

*#ample
" simple onmousedownEonmouseup e#ample(

Click Me

JavaScript *rray )+,ect


The "rra$ ob3ect is used to store multiple values in a single variable.

Tr$ it &ourself E *#amples


!reate an arra$, and assign values to it(

*#ample
'ar mycars ) new ;rray(); mycarsW7X ) "4aa&"; mycarsW1X ) "Kol'o"; mycarsW=X ) "1 ,";

%hat is an "rra$7
"n arra$ is a special variable, which can hold more than one value at a time. If $ou have a list of items ,a list of car names, for e#ample-, storing the cars in single variables could loo/ li/e this(
'ar car1)"4aa&"; 'ar car=)"Kol'o"; 'ar carN)"1 ,";

However, what if $ou want to loop through the cars and find a specific one7 "nd what if $ou had not 4 cars, but 4JJ7

25

The solution is an arra$G "n arra$ can hold man$ values under a single name, and $ou can access the values b$ referring to an inde# number.

!reate an "rra$
"n arra$ can be created in three wa$s. The following code creates an "rra$ ob3ect called m$!ars( @( +egular(
'ar my.ars)new ;rray(); my.arsW7X)"4aa&"; my.arsW1X)"Kol'o"; my.arsW=X)"1 ,";

I( !ondensed(
'ar my.ars)new ;rray("4aa&"%"Kol'o"%"1 ,");

4( Literal(
'ar my.ars)W"4aa&"%"Kol'o"%"1 ,"X;

"ccess an "rra$
&ou refer to an element in an arra$ b$ referring to the inde# number. This statement access the value of the first element in m$!ars(
'ar name)my.arsW7X;

This statement modifies the first element in m$!ars(


my.arsW7X)"Dpel";

W7X is the Rrst element in an array. W1X is the second . . . . . (inde/es start with 7)

26

&ou !an Have 1ifferent )b3ects in )ne "rra$


"ll JavaScript variables are ob3ects. "rra$ elements are ob3ects. ;unctions are ob3ects. 'ecause of this, $ou can have variables of different t$pes in the same "rra$. &ou can have ob3ects in an "rra$. &ou can have functions in an "rra$. &ou can have arra$s in an "rra$(
my;rrayW7X)Gate.now; my;rrayW1X)my2unc@on; my;rrayW=X)my.ars;

"rra$ Methods and roperties


The "rra$ ob3ect has predefined properties and methods(
'ar /)my.ars.length // the num&er o# elements in my.ars 'ar y)my.ars.inde/D#("Kol'o") // the inde/ posi@on o# "Kol'o"

!reate Few Methods


rotot$pe is a global constructor in JavaScript. It can construct new properties and methods for an$ JavaScript )b3ects.

*#ample( Ma/e a new "rra$ method.


;rray.prototype.ucase)#unc@on() 9 #or (i)7;i<this.length;iJJ) 9thisWiX)thisWiX.toYpper.ase();: :

JavaScript Strin- )+,ect


27

The String ob3ect is used for storing and manipulating te#t.

JavaScript Strings
" string simpl$ stores a series of characters li/e 2John 1oe2. " string can be an$ te#t inside .uotes. &ou can use simple or double .uotes(

*#ample
'ar carname)"Kol'o Z.>7"; 'ar carname)+Kol'o Z.>7+;

&ou can access each character in a string with its position ,inde#-(

*#ample
'ar character)carnameWCX;

String inde#es are CeroEbased, which means the first character is KJL, the second is K@L, and so on. &ou can use .uotes inside a string, as long as the$ don't match the .uotes surrounding the string(

*#ample
'ar answer)""t+s alright"; 'ar answer)"He is called +3ohnny+"; 'ar answer)+He is called "3ohnny"+;

)r $ou can put .uotes inside a string b$ using the M escape character(

*#ample
'ar answer)+"tQ+s alright+; 'ar answer)"He is called Q"3ohnnyQ"";

String Length
The length of a string ,a string ob3ect- is found in the built in propert$ length(

28

*#ample
'ar t/t)"Hello ,orld-"; document.write(t/t.length); 'ar t/t)";1.G02SH"3T! 8DH[\4TYK,ZY]"; document.write(t/t.length);

;inding a String in a String


The inde#)f,- method returns the position ,as a number- of the first found occurrence of a specified te#t inside a string(

*#ample
'ar str)"Hello world% welcome to the uni'erse."; 'ar n)str.inde/D#("welcome");

The method returns E@ if the specified te#t is not found. The lastInde#)f,- method starts searching at the end of the string instead of at the beginning.

Matching !ontent
The match,- method can be used to search for a matching content in a string(

*#ample
'ar str)"Hello world-"; document.write(str.match("world") J "<&r>"); document.write(str.match(",orld") J "<&r>"); document.write(str.match("world-"));

+eplacing !ontent
The replace,- method replaces a specified value with another value in a string.

*#ample
str)"Hlease 'isit icroso$-"

29

'ar n)str.replace(" icroso$"%",N4chools");

0pper !ase and Lower !ase


" string is converted to upper:lower case with the methods to0pper!ase,- : toLower!ase,-(

*#ample
'ar t/t)"Hello ,orld-"; // 4tring 'ar t/t1)t/t.toYpper.ase(); // t/t1 is t/t con'erted to upper 'ar t/t=)t/t.to!ower.ase(); // t/t= is t/t con'erted to lower

!onvert a String to an "rra$


" string is converted to an arra$ with the built in method string.split,-(

*#ample
t/t)"a%&%c%d%e" // 4tring t/t.split("%"); // 4plit on commas t/t.split(" "); // 4plit on spaces t/t.split("^"); // 4plit on pipe

Special !haracters
The bac/slash ,M- can be used to insert apostrophes, new lines, .uotes, and other special characters into a string. Loo/ at the following JavaScript code(
'ar t/t)",e are the so<called "Ki*ings" #rom the north."; document.write(t/t);

In JavaScript, a string is started and stopped with either single or double .uotes. This means that the string above will be chopped to( %e are the soEcalled To solve this problem, $ou must place a bac/slash ,M- before each double .uote in 25i/ing2. This turns each double .uote into a string literal(
'ar t/t)",e are the so<called Q"Ki*ingsQ" #rom the north."; document.write(t/t);

JavaScript will now output the proper te#t string( %e are the soEcalled 25i/ings2 from the north.

30

The table below lists other special characters that can be added to a te#t string with the bac/slash sign(
Code Outputs Q+ Q" QQ Qn Qr Qt Q& Q# single Fuote dou&le Fuote &ac*slash new line carriage return ta& &ac*space #orm #eed

String roperties and Methods


roperties(

length prototype constructor

Methods(

char;t() char.ode;t() concat() #rom.har.ode() inde/D#() last"nde/D#() match() replace() search() slice() split() su&str()

31

su&string() to!ower.ase() toYpper.ase() 'alueD#()

JavaScript Date Object


The 1ate ob3ect is used to wor/ with dates and times. +eturn toda$'s date and time How to use the 1ate,- method to get toda$'s date. get;ull&ear,0se get;ull&ear,- to get the $ear. getTime,getTime,- returns the number of milliseconds since J@.J@.@NOJ. set;ull&ear,How to use set;ull&ear,- to set a specific date. to0T!String,How to use to0T!String,- to convert toda$'s date ,according to 0T!- to a string. get1a$,0se get1a$,- and an arra$ to write a wee/da$, and not 3ust a number. 1ispla$ a cloc/ How to displa$ a cloc/ on $our web page.

!reate a 1ate )b3ect


The 1ate ob3ect is used to wor/ with dates and times. 1ate ob3ects are created with the 1ate,- constructor. There are four wa$s of initiating a date(
new Gate() // current date and @me new Gate(milliseconds) //milliseconds since 1AC7/71/71 new Gate(date4tring) new Gate(year% month% day% hours% minutes% seconds% milliseconds)

32

Most parameters above are optional. Fot specif$ing, causes J to be passed in. )nce a 1ate ob3ect is created, a number of methods allow $ou to operate on it. Most methods allow $ou to get and set the $ear, month, da$, hour, minute, second, and milliseconds of the ob3ect, using either local time or 0T! ,universal, or HMT- time. "ll dates are calculated in milliseconds from J@ Januar$, @NOJ JJ(JJ(JJ 0niversal Time ,0T!- with a da$ containing PB,QJJ,JJJ milliseconds. Some e#amples of initiating a date(
'ar today ) new Gate() 'ar d1 ) new Gate("Dcto&er 1N% 1ACB 11_1N_77") 'ar d= ) new Gate(CA%B%=O) 'ar dN ) new Gate(CA%B%=O%11%NN%7)

Set 1ates
%e can easil$ manipulate the date b$ using the methods available for the 1ate ob3ect. In the e#ample below we set a 1ate ob3ect to a specific date ,@Qth Januar$ IJ@J-(
'ar myGate)new Gate(); myGate.set2ullYear(=717%7%1O);

"nd in the following e#ample we set a 1ate ob3ect to be A da$s into the future(
'ar myGate)new Gate(); myGate.setGate(myGate.getGate()JB);

Fote( If adding five da$s to a date shifts the month or $ear, the changes are handled automaticall$ b$ the 1ate ob3ect itselfG

!ompare Two 1ates


The 1ate ob3ect is also used to compare two dates. The following e#ample compares toda$'s date with the @Qth Januar$ I@JJ(
'ar /)new Gate(); /.set2ullYear(=177%7%1O); 'ar today ) new Gate(); i# (/>today)

33

9 alert("Today is &e#ore 1Oth 3anuary =177"); : else 9 alert("Today is a$er 1Oth 3anuary =177"); :

%hat is +eg*#p7
+eg*#p, is short for regular e#pression. " regular e#pression is an ob3ect that describes a pattern of characters. %hen $ou search in a te#t, $ou can use a pattern to describe what $ou are searching for. " simple pattern can be one single character. " more complicated pattern can consist of more characters, and can be used for parsing, format chec/ing, substitution and more. +egular e#pressions are used to perform powerful patternEmatching and 2searchEandE replace2 functions on te#t.

S$nta#
'ar pa()new \eg0/p(pa(ern%modiRers); or more simply_ 'ar pa()/pa(ern/modiRers;

pa(ern speciRes the pa(ern o# an e/pression modiRers speci#y i# a search should &e glo&al% case<sensi@'e% etc.

+eg*#p Modifiers
Modifiers are used to perform caseEinsensitive and global searches. The i modifier is used to perform caseEinsensitive matching. The g modifier is used to perform a global match ,find all matches rather than stopping after the first match-.

34

*#ample @
1o a caseEinsensitive search for 2w4schools2 in a string(
'ar str)"Kisit \estar(echnologies "; 'ar pa(1)/ \estar(echnologies /i;

The mar/ed te#t below shows where the e#pression gets a match(
Kisit \estar(echnologies

*#ample I
1o a global search for 2is2(
'ar str)""s this all there isP"; 'ar pa(1)/is/g;

The mar/ed te#t below shows where the e#pression gets a match(
"s this all there isP

*#ample 4
1o a global, caseEinsensitive search for 2is2(
'ar str)""s this all there isP"; 'ar pa(1)/is/gi;

The mar/ed te#t below shows where the e#pression gets a match(
"s this all there isP

test,The test,- method searches a string for a specified value, and returns true or false, depending on the result. The following e#ample searches a string for the character 2e2(

*#ample
35

'ar pa(1)new \eg0/p("e"); document.write(pa(1.test("The &est things in li#e are #ree"));

Since there is an 2e2 in the string, the output of the code above will be(
true

e#ec,The e#ec,- method searches a string for a specified value, and returns the te#t of the found value. If no match is found, it returns null. The following e#ample searches a string for the character 2e2(

*#ample @
'ar pa(1)new \eg0/p("e"); document.write(pa(1.e/ec("The &est things in li#e are #ree"));

Since there is an 2e2 in the string, the output of the code above will be(
e

36

S-ar putea să vă placă și