Você está na página 1de 22

Essential Javascript -- A Javascript Tutorial

By Patrick Hunlock Javascript is an interpreted language with a C like syntax. While many people brush the language off as nothing more than a browser scripting language it actually supports many advanced concepts such as ob!ect"oriented"programing recursion lambda and closures. #t$s a very approachable language for the beginner that %uickly scales to be as powerful a tool as your skills allow. &his reference will cover the basic language constructs. &his is not a beginner$s guide to programming. &his article focuses on bringing people who already know another programming language up to speed on Javascript methodology. 'dditionally this is not an exhaustive language definition it is a broad overview that will occasionally focus in on some more advanced concepts. #t$s here to get you started other articles will focus on making you an expert.

Getting Started
&o dive into Javascript all you need is a simple text"editor and a browser. #n windows you can use notepad under your accessories and (inux and mac users have a similar editor. )imply create a blank H&*( page as such+
<html> <head> <title>Learning Javascript</title> </head> <body> <p>Hello World! </body> </html>

)ave the file then in your browser type in the file name you !ust created to see the results. Javascript is interpreted so any changes you make to this file will show up instantly in the browser the moment you hit the reload button.

In-Line Javascript
&o define a Javascript block in your web page simply use the following block of H&*(.
<script type='text/javascript'> // o!r script goes here" </script>

,ou can place these script blocks anywhere on the page that you wish there are some rules and conventions however. #f you are generating dynamic content as the page loads you will want the script blocks to appear where you want their output to be. -or instance if # wanted to say .Hello World/. # would want my script block to appear in the 0body1 area of my web page and not in the 0head1 section. Essential Javascript A Javascript Tutorial Page 1 of 22

2nless your scripts are generating output as the page loads good practice says that you should place your scripts at the very bottom of your H&*(. &he reason for this is that each time the browser encounters a 0script1 tag it has to pause compile the script execute the script then continue on generating the page. &his takes time so if you can get away with it make sure the browser hits your scripts at the end of the page instead of the start.

External Javascript
3xternal Javascript is where things get interesting. 'ny time you have a block of code which you will want to use on several different web pages you should place that block in an external Javascript file. &he clock on the upper right"hand corner of this page is a good example. &he clock appears on almost every page on this site and so it is included in my .common.!s. file. 3very web"page on the site will load this file and so the clock is available to all of my web"pages. &here$s nothing fancy about an external Javascript file. 'll it is is a text file where you$ve put all your Javascript. Basically everything that would ordinarily go between the 0script1 tags can go in your external file. 4ote that between was stressed you can not have the 0script1 05script1 tags themselves in your external file or you will get errors. &he biggest advantage to having an external Javascript file is that once the file has been loaded the script will hang around the browser$s cache which means if the Javascript is loaded on one page then it$s almost a sure thing that the next page on the site the user visits will be able to load the file from the browser$s cache instead of having to reload it over the #nternet 6&his is an incredibly fast and speedy process7. #ncluding an external file is basically the same as doing an in"line script the only difference is that you specify a filename and there$s no actual code between 0script1 and 05script1...
<script type='text/javascript' src='common"js'></script>

When the browser encounters this block it will load common.!s evaluate it and execute it. (ike in"line scripts above you can place this block anywhere you need the script to be and like in"line scripts you should place these as close to the bottom of the web"page as you can get away with. &he only difference between in"line Javascript blocks and external Javascript blocks is that an external Javascript block will pause to load the external file. #f you discount that one thing there$s no procedural difference between the two/

Javascript is case sensitive.


#t should also be noted before we begin that Javascript is extremely case sensitive so if you$re trying to code along with any examples make sure lowercase is lowercase and uppercase is uppercase. -or the most part Javascript is also a camel"cased language. &hat is if you$re trying to express more than one word you will eliminate the spaces leave the first letter uncapitali8ed and capitali8e the first letter of each word. &hus .get element by id. becomes .get3lementBy#9.. By contrast H&*( itself is 4:& case sensitive.

Essential Javascript A Javascript Tutorial

Page 2 of 22

Output (writeln)
:ne of the most important things to do when learning a new language is to master basic input and output which is why hello world has become almost a clich; in programming textbooks. -or Javascript you need three hello worlds because there are three ways to communicate with the user each increasingly more useful than the last. &he first method is to use the document.writeln(string) command. &his can be used while the page is being constructed. 'fter the page has finished loading a new document.writeln(string) command will delete the page in most browsers so use this only while the page is loading. Here$s how a simple web"page will look...
<html> <head> </head> <body> <script type='text/javascript'> doc!ment"#riteln$'Hello World!'%& </script> </body> </html>

's the page is loading Javascript will encounter this script and it will output .Hello World/. exactly where the script block appears on the page. &he problem with writeln is that if you use this method after the page has loaded the browser will destroy the page and start constructing a new one. -or the most part document.writeln is useful only when teaching yourself the language. 9ynamic content during page load is better served by the server"side scripting languages. &hat said document.writeln is very useful in pre"processing forms before they$re sent to the server "" you can basically create a new web"page on the fly without the need to contact the server.

Output (alert)
&he second method is to use a browser alert box. While these are incredibly useful for debugging 6and learning the language7 they are a horrible way to communicate with the user. 'lert boxes will stop your scripts from running until the user clicks the :< button and it has all the charm and grace of all those pop"up windows everyone spent so many years trying to get rid of/
<html> <head> </head> <body> <script type='text/javascript'> alert$'Hello World!'%& </script> </body> </html>

Essential Javascript A Javascript Tutorial

Page 3 of 22

Output (getElementById)
&he last method is the most powerful and the most complex 6but don$t worry it$s really easy/7. 3verything on a web page resides in a box. ' paragraph 60P17 is a box. When you mark something as bold you create a little box around that text that will contain bold text. ,ou can give each and every box in H&*( a uni%ue identifier 6an #97 and Javascript can find boxes you have labeled and let you manipulate them. Well enough verbiage check out the code/
<html> <head> </head> <body> <div id=''eedbac('></div> <script type='text/javascript'> doc!ment"get)lement*y+d$''eedbac('%"innerH,-L='Hello World!'& </script> </body> </html>

&he page is a little bigger now but it$s a lot more powerful and scalable than the other two. Here we defined a division 0div1 and named it .feedback.. &hat H&*( has a name now it is uni%ue and that means we can use Javascript to find that block and modify it. We do exactly this in the script below the division/ &he left part of the statement says on this web page 6document7 find a block we$ve named .feedback. 6 getElementById('feedback') 7 and change its H&*( 6innerHTML7 to be 'Hello World '. We can change the contents of $feedback$ at any time even after the page has finished loading 6which document.writeln can$t do7 and without annoying the user with a bunch of pop"up alert boxes 6which alert can$t do/7. #t should be mentioned that innerH&*( is not a published standard. &he standards provide ways to do exactly what we did in our example above. &hat mentioned innerH&*( is supported by every ma!or Browser and in addition innerH&*( works faster and is easier to use and maintain. #t$s therefore not surprising that the vast ma!ority of web pages use innerH&*( over the official standards. While we used .Hello World/. as our first example its important to note that with the exception of 0script1 and 0style1 you can use full"blown H&*(. Which means instead of !ust Hello World we could do something like this+
<html> <head> </head> <body> <div id=''eedbac('></div> <script type='text/javascript'> doc!ment"get)lement*y+d$''eedbac('%"innerH,-L='<.><'ont color=red>Hello World!</'ont>'& </script> </body> </html>

Essential Javascript A Javascript Tutorial

Page 4 of 22

#n this example innerHTML will process your string and basically redraw the web page with the new content. &his is a =3>, powerful and easy to use concept. #t means you can basically take an empty H&*( element 6which our feedback division is7 and suddenly expand it out with as much H&*( content as you$d like.

Input (One

lic! "# $ule "%em &ll)

#nput of course is a little more complicated. -or now we$ll !ust reduce it to a bare click of the mouse. #f everything in H&*( is a box and every box can be given a name then every box can be given an event as well and one of those events we can look for is .on!lick.. (ets revisit our last example...
<html> <head> </head> <body> <div id=''eedbac(' on/lic(='goodbye$%'>0sers #itho!t Javascript see this"</div> <script type='text/javascript'> doc!ment"get)lement*y+d$''eedbac('%"innerH,-L='Hello World!'& '!nction goodbye$% 1 doc!ment"get)lement*y+d$''eedbac('%"innerH,-L='2oodbye World!'& 3 </script> </body> </html>

Here we did two things to the example first we added an .on!lick. event to our feedback division which tells it to execute a function called goodbye() when the user clicks on the division. ' function is nothing more than a named block of code. #n this example goodbye does the exact same thing as our first hello world example it$s !ust named and inserts $?oodbye World/$ instead of $Hello World/$. 'nother new concept in this example is that we provided some text for people without Javascript to see. 's the page loads it will place .2sers without Javascript will see this.. in the division. #f the browser has Javascript and it$s enabled then that text will be immediately overwritten by the first line in the script which looks up the division and inserts .Hello World/. overwriting our initial message. &his happens so fast that the process is invisible to the user they see only the result not the process. &he goodbye() function is not executed until it$s explicitly called and that only happens when the user clicks on the division. While Javascript is nearly universal there are people who surf with it deliberately turned off and the search bots 6googlebot yahoo$s slurp etc7 also don$t process your Javascript so you may want to make allowances for what people and machines are"not seeing.

Essential Javascript A Javascript Tutorial

Page 5 of 22

Input ('ser Input)


Clicks are powerful and easy and you can add an onClick event to pretty much any H&*( element but sometimes you need to be able to ask for input from the user and process it. -or that you$ll need a basic form element and a button+
<inp!t id='!ser+np!t' si4e=56> <b!tton on/lic(='!ser7!bmit$%'>7!bmit</b!tton><*8> <.><div id='res!lt'></div>

Here we create an input field and give it a name of u"erIn#ut. &hen we create a H&*( button with an on!lick event that will call the function u"er$ubmit(). &hese are all standard H&*( form elements but they$re not bound by a 0form1 tag since we$re not going to be submitting this information to a server. #nstead when the user clicks the submit button the on!lick event will call the u"er$ubmit() function+
<script type='text/javascript'> '!nction !ser7!bmit$% 1 var 0+=doc!ment"get)lement*y+d$'!ser+np!t'%"val!e& doc!ment"get)lement*y+d$'res!lt'%"innerH,-L=' o! typed9 ':0+& 3 </script>

Here we create a variable called %I which looks up the input field u"erIn#ut. &his lookup is exactly the same as when we looked up our feedback division in the previous example. )ince the input field has data we ask for its &alue and place that value in our %I variable. &he next line looks up the re"ult division and puts our output there. #n this case the output will be .,ou &yped@ . followed by whatever the user had typed into the input field. We don$t actually need to have a submit button. #f you$d like to process the user input as the user types then simply attach an on'eyu# event to the input field as such+
<inp!t id='!ser+np!t' on;ey0p=<!ser7!bmit$%< si4e=56><*8> <.><div id='res!lt'></div>

&here$s no need to modify the u"er$ubmit() function. 4ow whenever a user presses a key while the u"erIn#ut box has the focus for each keypress u"er$ubmit() will be called the value of the input box retrieved and the re"ult division updated.

ab
Essential Javascript A Javascript Tutorial Page 6 of 22

Javascript is an Event (riven Language


's you can tell from the input examples Javascript is an event driven language which means your scripts react to events you set up. ,our code isn$t running all the time it simply waits until an event starts something up/ ?oing into all the Javascript events is beyond the scope of this document but here$s a short"list of common events to get you started. Event on'bort onBefore2nload onBlur onChange onClick on9blClick on3rror on-ocus on<ey9own on<eyPress on<ey2p on(oad on*ouse9own on*ouse*ove on*ouse:ut on*ouse:ver on*ouse2p on>eset on>esi8e on)elect on)ubmit on2nload Description 'n image failed to load. &he user is navigating away from a page. ' form field lost the focus 62ser moved to another field7 &he contents of a field has changed. 2ser clicked on this item. 2ser double"clicked on this item. 'n error occurred while loading an image. 2ser !ust moved into this form element. ' key was pressed. ' key was pressed :> released. ' key was released. &his ob!ect 6iframe image script7 finished loading. ' mouse button was pressed. &he mouse moved. ' mouse moved off of this element. &he mouse moved over this element. &he mouse button was released. ' form reset button was pressed. &he window or frame was resi8ed. &ext has been selected. ' form$s )ubmit button has been pressed. &he user is navigating away from a page.

&hese events can be attached to most any H&*( tag or form element. :f them all on!lick will probably be what you end up using most often.

Essential Javascript A Javascript Tutorial

Page 7 of 22

#mments
Javascript supports two types of comments. 9ouble"slashes 6557 tell !avascript to ignore everything to the end of the line. ,ou will see them used most often to describe what is happening on a particular line.
var x==& // )verything 'rom the // to end o' line is ignored$>% var thingamajig=?@A"B=& // @ times the price o' a #hatsit"

Block %uotes begin a comment block with a slash"asterisk 65A7 and Javascript will ignore everything from the start of the comment block until it encounters an asterisk"slash 6A57. Block %uotes are useful for temporally disabling large areas of code or describing the purpose of a function or detailing the purpose and providing credits for the script itself.
'!nction #hirlymajig$jabber#oc(y% 1 /> Here #e ta(e the jabber#oc(y and insert it in the gireCgimbleD ta(ing great care to observe the ips!m lor!m! Eor borCrathCo!tgrabe! We really sho!ld patent this! >/ 3 ret!rn $jabber#oc(y>@%&

,ou should note that while comments are useful for maintaining the code they are a liability itself in Javascript since they will be transmitted along with the code to each and every page load which can create substantial bandwidth penalties and increase the load time of your page for users. &his doesn$t mean you shouldn$t comment your code !ust that once your code is .finished. you should make a backup copy with the comments then strip out all the comments in the file which is actually sent to the user. ,ou can automate this process with a minimi8ing application which you can find at http@55www.crockford.com5!avascript5!smin.html and an on"line !avascript version at http@55fmarcia.info5!smin5test.html . &he result of minimi8ing your Javascript is a tiny compact file which is a fraction of the si8e of the original which will save you bandwidth and provide speedier page"load time for your visitors. However the result is also a very unmaintainable source"code mess which is why you should keep a separate unminimi8ed 6and heavily commented7 version of the original file. 6A7 :f special consideration you should note that the browser itself is '(W',) looking for a 05script1 tag to mark the end of your Javascript and if it finds that tag intact in"one"piece be it in a string or a comment it is going to stop processing Javascript at that point and restart" processing H&*(.
var x==& /> ,he bro#ser #ill brea( the Javascript #hen it sees this </script> tag" )verything 'rom tag 'or#ard is no# being processed as H,-L! ,his is a bad thing! ,o avoid this yo! need to avoid !sing this tag any#here in yo!r JavascriptD and i' yo! m!st have itD yo! sho!ld brea( the string o!t li(e this""" >/ doc!ment"#riteln$'</scr':'ipt>'%&

Essential Javascript A Javascript Tutorial

Page 8 of 22

)aria*les
Javascript is not a strongly typed language which means you rarely have to concern yourself with the type of data a variable is storing only what the variable is storing and in Javascript variables can store anything even functions.
var var var var var var var var var var var var var var var var this+sF7tring = ',his is a string'& alsoF7tring = '@='& isFG!mber = @=& is)H!al = $alsoF7tring==isFG!mber%& // ,his is tr!eD they are both @=" is)H!al = $alsoF7tring===isFG!mber%& // Ealse one is a n!mberD the other a string" concat=alsoF7tring : isFG!mber& // concat is no# @=@= addition=isFG!mber : isFG!mber& // addition is no# =6 alsoFG!mber=A"6=& // is eH!al to A"6= $!s!ally%" 'loat)rror=6"65:6"6?& // is eH!al to 6"65IIIIIIIIIIIIIII an)xponent=?"@Ae:A& // is eH!al to ?@A6 hexadecimal = 6x''& // is eH!al to @==" octal = 6AJJ& // is eH!al to @==" is,r!e = tr!e& // ,his is a booleanD it can be tr!e or 'alse" isEalse= 'alse& // ,his is a booleanD it can be tr!e or 'alse isFrray = K6D 'one'D @D AD 'B'D =L& // ,his is an array" 'o!r = isFrrayKBL& // assign a single array element to a variable" // in this case 'o!r = 'B' var isMbject = 1 'color'9 'bl!e'D // ,his is a Javascript object 'dog'9 'bar('D 'array'9 K6D?D@DADBD=LD 'my'!nc'9 '!nction $% 1 alert$'do something!'%& 3 3 var dog = isMbject"dog& // dog no# stores the string 'bar('& isMbject"my'!nc$%& // creates an alert box #ith the val!e <do something!< var someE!nction = '!nction$% 1 ret!rn <+ am a '!nction!<& 3 var alsoFE!nction = someE!nction& //Go $% so alsoFE!nction becomes a '!nction var res!lt = alsoFE!nction$%& // alsoFE!nction is exec!ted here beca!se $% // exec!tes the '!nction so res!lt stores the // ret!rn val!e o' the '!nction #hich is // <+ am a '!nction!<

' variable may not be a Javascript reserved word or begin with a number or any symbol other than B or C. #n #nternet explorer you should also avoid variable names with the same name as html elements you have named. -or instance+
var someNiv = doc!ment"get)lement*y+N$'someNiv'%&

+will cause problems in #nternet 3xplorer because the variable name and the division name are identical. #n recent years a convention has formed around the use of the B symbol as various libraries like Prototype and JDuery use it to look up a named H&*( element. -or most purposes if you see B6$something$7 in Javascript you should read that as being document.getElementById('"omet(ing'). &his is not standard Javascript in order for )('"omet(ing') to work you need to be using a Javascript framework which will define B as doing something 6(ike JDuery Prototype etc7. &he use of a leading underscore 6C7 is generally useful to indicate a global variable or a variable that has been set outside the current scope.

Essential Javascript A Javascript Tutorial

Page 9 of 22

' final consideration on variables is that functions themselves can be defined like and act like variables. :nce a function has been defined it can be passed to other functions as an argument 6' process knows as lambda7 or assigned to other variables !ust like a string array or any other Javascript ob!ect. ?enerally if you use a function without trailing parenthesis 67 the function is treated like a variable and can be passed and assigned. &railing parenthesis #4=:<3 the function executing it and passing back the return value 6if any7. Please note that this is a very broad summary overview of Javascript$s data types. -or more information please see the other articles in this series 6listed at the top of the page7 which go into exhaustive detail on each Javascript type.

)aria*le Sc#pe
=ariables in Javascript have -24C&#:4 scope. &hat is all variables are global unless they are explicitly defined inside a function and even then child"functions have access to their parent$s variables. #f a function defines a new variable W#&H:2& using the &ar keyword that variable will be global in scope.
var global = 'this is global'& '!nction scopeE!nction$% 1 also2lobal = ',his is also global!'& var not2lobal = ',his is private to scopeE!nction!'& '!nction s!bE!nction$% 1 alert$not2lobal%& // We can still access not2lobal in this child '!nction" still2lobal = 'Go var (ey#ord so this is global!'& var is.rivate = ',his is private to s!bE!nction!'& // // // // // ,his is an error since #e haven't exec!ted s!b'!nction exec!te s!b'!nction ,his #ill o!tp!t 'Go var (ey#ord so this is global!' ,his generate an error since is.rivate is private to s!b'!nction$%"

alert$still2lobal%& s!bE!nction$%& alert$still2lobal%& alert$is.rivate%& alert$global%& 3 alert$global%& alert$also2lobal%& scopeE!nction$%& alert$also2lobal%& alert$not2lobal%&

// o!tp!ts9 'this is global' // o!tp!ts9 'this is global' // generates an error since #e haven't r!n scopeE!nction yet" // o!tp!ts9 ',his is also global!'& // generates an error"

&he concept that a variable will continue to exist and can be referenced after the function that created it has ceased executing is known as C(:)2>3. #n the above example "till*lobal and al"o*lobal can be considered closures because they persist after the function that creates them has ceased to operate. ,ou can do some pretty fancy stuff with it later on but it$s not terribly hard to understand once you associate it with creating a global scoped variable inside a function.

Essential Javascript A Javascript Tutorial

Page 1 of 22

Special +eyw#rds
Javascript has a few pre"defined variables with special meaning. +a+ "" 4ot a 4umber 6?enerated when an arithmetic operation returns an invalid result7. +a+ is a weird construct. -or one it is 43=3> e%ual to itself so you can$t simply check to see if ,-'dog' .. '+a+'. ,ou must use the construct i"+a+(,-dog) to determine if the operation failed. #n boolean operations +a+ evaluates to false however E also evaluates to false so use i"+a+. )ince +a+ is never e%ual to itself you can use this simple trick as well@ if 6result /F result7 G alert6$4ot a 4umber/$7H I Infinity is a keyword which is returned when an arithmetic operation overflows Javascript$s precision which is in the order of JEE digits. ,ou can find the exact minimum and maximum range for your Javascript implementation using +umber.M/012/L%E and +umber.MI+12/L%E. null is a reserved word that means .empty.. When used in boolean operation it evaluates to false. Javascript supports true and fal"e as boolean values. #f a variable hasn$t been declared or assigned yet 6an argument to a function which never received a value an ob!ect property that hasn$t been assigned a value7 then that variable will be given a special undefined value. #n boolean operations undefined evaluates as fal"e. Here$s an example+
'!nction doFlert$say,his% 1 i' $say,his===!nde'ined% 1 say,his='de'a!lt val!e'& 3 alert$say,his%& 3 // // // // /hec( to see i' say,his #as passed" +t #asn't so give it a de'a!lt val!e )nd chec( ,oss !p the alert"

ab
Essential Javascript A Javascript Tutorial Page 11 of 22

&rit%metic Operat#rs
&here$s nothing particularly exotic about the way Javascript does arithmetic. Operator K " A 5 L KK "" Description 'ddition 6also string concatention7 )ubtration 6also unary minus7 *ultiplication 9ivision >emainder of division 6or modulus7 pre or post increment pre or post decrement

KK and "" are C style operators their position around the variable they are operating on is important. #f the operator appears B3-:>3 the variable they will be evaluated immediately if they appear '-&3> the variable they will be evaluated only after the entire line has been resolved. -or instance+
var x = =& var y = x::& var x = =& var y = ::x& // y==D x=5 // y=5D x=5

#n the first example y is assigned the value of x 6M7 and then x is incremented by one because the KK operator appears '-&3> x. #n the second example x is incremented by one first because KK appears B3-:>3 the x so y is given the value N. How this works between C and PhP and Javascript can be somewhat different. &here was a most excellent discussion about this on reddit if you$d like to delve into those differences. 'dditional shorthand operators exist when working on the same variable. -or instance+
x = x : =& x := =& // is the same as"""

ab
Essential Javascript A Javascript Tutorial Page 12 of 22

L#gical and

#mparis#n Operat#rs

Javascript supports e%uality checking 6FF7 and identity checking 6FFF7. 3%uality checks for e%uality regardless of type. &herefore OM and $OM$ will evaluate as true. #dentity checking checks not only for e%uality but type e%uality as well so OM and $OM$ will evaluate as false because while both are OM one is a string and the other a number. 4ote that a single e%ual sign is an assignment statement/ xFM will assign M to x while xFFM will see if x is e%ual to M and xFFFM will check to see if x is identical to M. #n addition to FF and FFF you can check for not e%ual 6/F7 and not identical 6/FF7. Operator F FF FFF /F /FF / QQ RR 0 0F 1 1F Description 'ssignment xFMH 55 assigns M to x 3%uality is xFFMP #dentity is x M and a number as wellP 4ot e%ual is x une%ual to MP 4ot identical is x une%ual to the 4umber MP 4ot if not6false7 is true. :> is 6xFFM7 :> 6yFFM7 'nd is 6xFFM7 '49 6yFFM7 (ess than. is x less than MP (ess than or e%ual. is x less than or e%ual to MP ?reater than. is x greater than MP ?reater than or %ual. is x greater than or e%ual to MP

ab
Essential Javascript A Javascript Tutorial Page 13 of 22

#nditi#nals, I&he if statement lets you execute a block of code if some test is passed.
var x==& i' $x===% 1 alert$'x is eH!al to =!'%& 3

,ou can also use an el"e clause to execute code if the test fails.
var x==& i' $x===% 1 alert$'x is eH!al to =!'%& 3 else 1 alert$'x is not eH!al to =!'%& 3

'n el"eif statement also exists which allows for better formating of long conditional tests.
var x==& i' $x==?% 1 alert$'x is eH!al 3 else i' $x==@% 1 alert$'x is eH!al 3 else i' $x===% 1 alert$'x is eH!al 3 else 1 alert$'x isn't ?D 3

to ?!'%& to @!'%& to =!'%& @ or =!'%&

#nditi#nals, S.I" /
#f you$re going to be doing a large number of tests it makes sense to use a switch statement instead of nested ifs. )witches in !avascript are %uite powerful allowing evaluations on both the switch and the case.
var x==& s#itch $x% 1 case ?9 alert$'x is eH!al to case @9 alert$'x is eH!al to case =9 alert$'x is eH!al to de'a!lt9 alert$<x isn't ?D @ 3

?!'& brea(& @!'& brea(& =!'& brea(& or =!<%&

4ote that if you omit the break statement that '(( of the code to the end of the switch statement will be executed. )o if x is actually e%ual to M and there is no break statement an alert for .x is e%ual to M. will appear as well as an alert for .x isn$t S O or M/..

Essential Javascript A Javascript Tutorial

Page 14 of 22

)ometimes it makes more sense to do the evaluation in the case statement itself. #n this case you$d use true false or an expression which evaluates to true or false in the switch statement.
var x==& s#itch $tr!e% 1 case $x==?%9 alert$'x is eH!al to ?!'& brea(& case $x==@%9 alert$'x is eH!al to @!'& brea(& case $x===%9 alert$'x is eH!al to =!'& brea(& de'a!lt9 alert$<x isn't ?D @ or =!<%& 3

#nditi#nals, S%#rt%and &ssignment


Javascript supports more advanced constructs. :ften you will see code like the following+
'!nction doFddition$'irstOarD secondOar% 1 var 'irst = 'irstOar PP =& var second= secondOar PP ?6& ret!rn 'irst:second& 3 doFddition$?@%&

Here Javascript uses a logical :> 6QQ7 to determine if the passed variables actually have a value. #n the example we call do/ddition with a value of SO but we neglect to pass a second argument. When we create the fir"t variable fir"t2ar is a non"falsey value 6#3 it$s actually defined7 so Javascript assigns first=ar to first. "econd2ar was never passed a value so it is undefined which evaluates to fal"e so here the variable "econd will be assigned a default value of SE. ,ou should note that 8ero evaluates as false so if you pass 8ero as either fir"t2ar or "econd2ar the default values will be assigned and 4:& 8ero. #n our example above it is impossible for fir"t or "econd to be assigned a 8ero. #n psuedo code...
var someOariable = $assign i' this is tr!thy% PP $assign this i' 'irst test eval!ates 'alse%

#nditi#nals, "ernary Operat#rs


&ernary operators are a shorthand if5else block who$s syntax can be a bit confusing when you$re dealing with :PC 6:ther People$s Code7. &he syntax boils down to this.
var !serGame = '*ob'& var hello = $!serGame=='*ob'% Q 'Hello *ob!' 9 'Hello Got *ob!'&

#n this example the statement to be evaluated is (u"er+ame..'Bob'). &he %uestion marks ends the statement and begins the conditionals. #f %"er+ame is indeed Bob then the first block 'Hello Bob ' will be returned and assigned to our (ello variable. #f u"er+ame isn$t Bob then the second block 6$Hello 4ot Bob/$7 is returned and assigned to our (ello variable. #n psudeo code+
var someOariable = $condition to test% Q $condition tr!e% 9 $condition 'alse%&

Essential Javascript A Javascript Tutorial

Page 15 of 22

&he %uestion mark 6P7 and colon 6@7 tend to get lost in complex expressions as you can see in this example taken from wikipedia 6but which will also work in Javascript if the various variables are assigned...7
'or $i = 6& i < -FRS.F,,)8G7& i::% cSpatternsKiL"7ho#Windo#$mSdata"'MnKiL Q 7WS7HMW 9 7WSH+N)%&

)o while %uick and efficient they do tend to reduce the maintainability5readability of the code.

L##ps, -O$
&he for loop follows basic C syntax consisting of an initiali8ation an evaluation and an increment.
'or $var i=6& $i<=%& i::% 1 doc!ment"#riteln$'+ is eH!al to ':i:'<br>'%& 3 // o!tp!ts9 // + is eH!al to 6 // + is eH!al to ? // + is eH!al to @ // + is eH!al to A // + is eH!al to B

&his is actually an extreme simplification of what a for statement can do. :n the other end of the spectrum consider this shuffle prototype which will randomly shuffle the contents of an array. Here everything is defined and executed within the context of the for statement itself needing no additional block to handle the code.
Frray"prototype"sh!''le = '!nction $%1 'or$var rndD tmpD i=this"length& i& rnd=parse+nt$-ath"random$%>i%D tmp=thisKCC iLD thisKiL=thisKrndLD thisKrndL=tmp%& 3&

ab
Essential Javascript A Javascript Tutorial Page 16 of 22

L##ps, -O$0I1
Javascript has a variant of the for loop when dealing with Javascript ob!ects. Consider the following ob!ect+
var myMbject = 1 'animal' 9 'gro#ls' 9 'hasEleas'9 'loyal' 9 'dog'D tr!eD tr!eD tr!e 3

We can loop through these values with the following construct.


var myMbject = 1 'animal' 9 'gro#ls' 9 'hasEleas'9 'loyal' 9 'dog'D tr!eD tr!eD tr!e 3

'or $var property in myMbject% 1 doc!ment"#riteln$property : ' contains ' : myMbjectKpropertyL:'<br>'%& 3 // M!tp!ts9 // animal contains dog // gro#ls contains tr!e // hasEleas contains tr!e // loyal contains tr!e

What this essentially does is assign the property name to the variable #ro#erty. We can then access my3b4ect through an associative array style syntax. -or instance the first itteration of the loop assigns animal to #ro#erty and my3b4ect56animal67 will return dog. &here is a big caveat here in that properties and methods added by prototyping will also show up in these types of loops. &herefore it$s best to always check to make sure you are dealing with data and not a function as such+
'or $var property in myMbject% 1 i' $typeo'$myMbjectKpropertyL% != ''!nction'% 1 doc!ment"#riteln$property : ' contains ' : myMbjectKpropertyL:'<br>'%& 3 3

&he typeof check to screen out functions will ensure that your for5in loops will extract only data and not methods that may be added by popular !avascript libraries like Prototype.

ab
Essential Javascript A Javascript Tutorial Page 17 of 22

L##ps, ./ILE
w(ile loops in Javascript also follow basic C syntax and are easy to understand and use. &he w(ile loop will continue to execute until its test condition evaluates to false or the loop encounters a break statement.
var x = ?& #hile $x<=% 1 x = x :?& 3 var x = ?& #hile $tr!e% 1 x = x : ?& i' $x>==% 1 brea(& 3 3

)ometimes it makes more sense to evaluate the test condition at the end of the loop instead of the beginning. )o for this Javascript supports a do-w(ile structure.
var x=?& do 1 x = x : ?& 3 #hile $x < =%&

Bringing It &ll "#get%er


)o now you know how to do basic input and output how to do conditional branching and how to do loops. &hat$s pretty much everything you need to know about any programming language to get started/ )o lets wrap everything we$ve done so far into one simple web application. -irst we$ll define our web page.
<html> <head> <title>-y Eirst Javascript</title> </head> <body> Hello World! </body> </html>

4ow to this we will add an input line a drop down box and a submit button. 4otice we give an #9 to the form elements and have the submit button call a function when it$s clicked. ' function which we will write later. We$ve also added some descriptive text.

Essential Javascript A Javascript Tutorial

Page 18 of 22

<html> <head> <title>-y Eirst Javascript</title> </head> <body> Hello World! <p>7ay #hatQ <inp!t id=<say,his< si4e=B6> <.>Ho# many timesQ <select id='ho#-any'> <option val!e=?>?</option> <option val!e== selected>=</option> <option val!e=?6>?6</option> <option val!e=@6>@6</option> </select> <p><b!tton on/lic(='doLoop$%'>No +t!</b!tton> </body> </html>

4ow we need to add a division where the output will occur. We$ll add this right below the form elements specifically the .9o #t/. button.
<html> <head> <title>-y Eirst Javascript</title> </head> <body> Hello World! <p>7ay #hatQ <inp!t id=<say,his< si4e=B6> <.>Ho# many timesQ <select id='ho#-any'> <option val!e=?>?</option> <option val!e== selected>=</option> <option val!e=?6>?6</option> <option val!e=@6>@6</option> </select> <p><b!tton on/lic(='doLoop$%'>No +t!</b!tton> <p><div id=<res!lts<></div> </body> </html>

&he script for this will be simple enough. When the button is clicked the doLoo#() function will be called. do(oop67 will lookup the value of the "ayT(i" input field then repeat that (owMany times. Here$s the script itself separate from the H&*(+
'!nction doLoop$% 1 var sayWhat = doc!ment"get)lement*y+d$'say,his'%"val!e& var maxLoop = doc!ment"get)lement*y+d$'ho#-any'%"val!e& var str = ''& // #here #e'll store o!r o!tp!t temporarily" 'or $var i=?& $i<=maxLoop%& i::% 1 str=str:i:'9':sayWhat:'<br>'& 3 doc!ment"get)lement*y+d$<res!lts<%"innerH,-L=str& 3

Essential Javascript A Javascript Tutorial

Page 19 of 22

'nd the entire application all together.


<html> <head> <title>-y Eirst Javascript</title> </head> <body> Hello World! <p>7ay #hatQ <inp!t id=<say,his< si4e=B6> <.>Ho# many timesQ <select id='ho#-any'> <option val!e=?>?</option> <option val!e== selected>=</option> <option val!e=?6>?6</option> <option val!e=@6>@6</option> </select> <p><b!tton on/lic(='doLoop$%'>No +t!</b!tton> <p><div id=<res!lts<></div> <script type='text/html'> '!nction doLoop$% 1 var sayWhat = doc!ment"get)lement*y+d$'say,his'%"val!e& var maxLoop = doc!ment"get)lement*y+d$'ho#-any'%"val!e& var str = ''& // #here #e'll store o!r o!tp!t temporarily" 'or $var i=?& $i<=maxLoop%& i::% 1 str=str:i:'9':sayWhat:'<br>'& 3 doc!ment"get)lement*y+d$<res!lts<%"innerH,-L=str& 3 </script> </body> </html>

(/"2L, (ynamic /"2L


&he above example is what$s technically considered 9ynamic H&*( 6or 9H&*(7 because the contents of the page dynamically change based on user interaction after the page has finished loading. ?oing into great detail on 9H&*( is beyond the scope of this article but there is one small trivial !ump that can really change how you see H&*( and Javascript. &his page has pulled an H&*( element with the use of document.get3lementBy#d. :nce we$ve had this assigned to a variable we$ve been able to manipulate the contents of that element with innerH&*( and in the case of forms find the value of the element with the value property. &here is also a style property which lets you access and change the C)) styles for that element. &here is a nice C)) reference at #loveJack9aniels 6 http@55www.ilove!ackdaniels.com5cheat" sheets5css"cheat"sheet5 7. *ost all of the properties you can access are listed on the left and right margin of the cheat sheet 6the interior5brown areas aren$t applicable7. &he only real trick is that where you see a dash in the C)) name for Javascript you need to remove the dash and capitali8e the next letter. )o the C)) style background8color becomes background!olor in Javascript.

Essential Javascript A Javascript Tutorial

Page 2 of 22

Here$s an example which will change the background color of a division when you click on it$s contents.
<div id=<example< on/lic(=<colori4e$%<>/lic( on this text to change the bac(gro!nd color</div> <script type='text/javascript'> '!nction colori4e$% 1 var element = doc!ment"get)lement*y+d$<example<%& element"style"bac(gro!nd/olor='TU66'& 3 </script>

Here we create a division with a name of e9am#le which will call a function called colori:e() when that division is clicked. colori:e() will lookup the e9am#le division and assign it to the Javascript variable element. 4ext we assign a color of TUEE 6burgundy7 to the element$s "tyle.background!olor property. &his actually made the text hard to read so in the next example we$ll add another line to change the color of the text to white.
<div id=<example< on/lic(=<colori4e$%<>/lic( on this text to change the bac(gro!nd color</div> <script type='text/javascript'> '!nction colori4e$% 1 var element = doc!ment"get)lement*y+d$<example<%& element"style"bac(gro!nd/olor='TU66'& element"style"color='#hite'& 3 </script>

'nd lets go ahead and center the text as well.


<div id=<example< on/lic(=<colori4e$%<>/lic( on this text to change the bac(gro!nd color</div> <script type='text/javascript'> '!nction colori4e$% 1 var element = doc!ment"get)lement*y+d$<example<%& element"style"bac(gro!nd/olor='TU66'& element"style"color='#hite'& element"style"textFlign='center'& 3 </script>

&he manipulation of an H&*( element$s C)) styles is incredibly powerful/ ,ou can hide or display elements with the style.display property 6"tyle.di"#lay.noneFinvisible "tyle.di"#lay.blockFvisible7 ,ou can let the elements float over the page with "tyle.#o"ition 6absolute5relative5fixed7 you can change their position on the page by setting "tyle.left and "tyle.to#. &he possibilities are literally endless.

Essential Javascript A Javascript Tutorial

Page 21 of 22

#nclusi#n
's stated at the beginning of this article this document is intended to bring a programmer up to speed in Javascript and is not an exhaustive review of the language. &his article is a part of a larger series of reference articles 6listed at the top of the page7. 's you master the fundamentals introduced on this page it$s recommended that you visit the other reference articles to master the details of the language. Javascript is a surprisingly deep and well considered language 6with a few notable and notorious exceptions7. #t is simple enough for beginners to programming to understand and scales to become as advanced as you need it to be. While it may be frustrating to work around the various idiosyncrasies of all the browser models and versions Javascript itself is a !oy to work in and when developing web"applications the least and most unobtrusive of all the problems you will have to surmount.

&dditi#nal $es#urces
While there are many good Javascript books available. &he general consensus is that the best introduction and reference to Javascript is Javascript@ &he 9efinitive ?uide by 9avid -lanagan. &his book is endorsed by the 2senet group comp.lang.!avascript as well as by 9ouglas Crockford and other notable people of influence within the Javascript community.

ab
)ersi#n
This document is current as of Firefox 2.03, IE 7.0, JSCRIPT .!, EC"#$2!2 Edition 3, Ja%ascri&t '.7

License
Co&(ri)ht * 2007 +( Patric, -un.oc, / htt&011222.hun.oc,.com. The source codes 3+ut not the artic.e itse.f4 in this document are re.eased into the &u+.ic domain and ma( +e used 2ithout com&ensation or attri+ution.

Essential Javascript A Javascript Tutorial

Page 22 of 22

Você também pode gostar