javascript: javascript awesomeness book (awesomeness … learning, video professor, d… · but if...

75

Upload: others

Post on 07-Jun-2020

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 2: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 3: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

JavascriptAwesomenessLearntowriteJavascripttheawesomeway

GiladE.TsurMayer

Copyright©2016byGiladE.TsurMayer

Page 4: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 5: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Tableofcontent

Introduction

Chapter1:WhyLearnJavascriptAnyway?

Chapter2:WhatisJavascript?

Chapter3:DoIneedtoknowanythingbeforeIlearnJavascript?

Chapter4:Howtosetupyourpage

Chapter5:Simplealert,writetodocument

Chapter6:Comments

Chapter7:Variables

Chapter8:Variabletypes

Chapter9:Usingdifferenttypesofvar

Chapter10:Mathoperators

Chapter11:Functions

Chapter12:FunctionsParameters

Chapter13:MultipleParameters

Chapter14:ReturnStatement

Chapter15:Callingfunctionfromanotherfunction

Chapter16Ifstatement

Chapter17:Else&Elseif

Chapter18:Switch

Chapter19:Forloop

Chapter20:Array

Chapter21:ArrayTricks

Chapter22:JavascriptonSteroids

Chapter23:Nowwhat?

Page 6: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 7: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

StopEverything!IHaveaPresentForYou!

OMG!OMG!!!OMG!!!Aren’tyouexcited?…whodoesn’tlovepresents???

ThisbookgetsyoutoknowJavascript,butpersonallyIprefervideosoverbooks–Imean,it’seasierifsomeonedoesalltheworkofreadingforyou,right?Youcanwatchabunchofvideosandbeanexpertinnotime.

So,Itookthisbook,andblendeditallintoabite-sizedvideocourse.ifyouwillwatchit,youwillknoweverybasicbuildingblockofJavascriptinnotime!Neat,huh?

Andbecauseyouhavepurchasedthisbook,Iwillgiveyou50%offthisvideocourse.Awesome,right?

Grabthevideoshere:http://basicjavascript.gilad.me/discount50/

Page 8: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 9: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Introduction

HeyGuys!

WelcometotheJavascriptAwesomenessCourse,whereyouwilllearntowritethebasicsofJavascript,theawesomeway!

MynameisGilad,andIwillleadyouthroughthisamazingcourse!

Ibeganmycareerasawebdeveloper,butsoontransitionedtoentrepreneurship,whereIfoundedmyveryownstartupcompany.

Currently,IworkatthecompanyIfoundedfromscratch,doingwhatIlovemost-teachingyouguys!

IdesignedthiscourseforanyoneseekingtolearnbasicofJavascriptandbeginacareerasarockstarwebdeveloper,aswellasanybodywhojustlovestoexpandtheirknowledge.

Bytheendofthecourse,youwillhavearocksolidknowledgeofallJavascriptbuildingblockssuchas:

●JavascriptVariables

●JavascriptFunctions

●JavascriptIfStatement

●JavascriptFormValidation

●Andmanymanymore…

IwillteachyouthelatestversionofJavascriptbythestandardsoftheW3CAssociation.Thesestandardsareusedbyallthemajorcompaniesintheworld.

Iwillnotonlycoverallthesetopics,butIwillalsogiveyouanopportunitytopracticethembygivingyouapopquizeverynowandthen.

TheidealstudentforthiscourseisanybodywhowantstoexpandtheirknowledgeofJavascriptorgetalegupinthewebdeveloperworld.

Totakethiscourse,youwillhavetoknowthebasicsofHTMLandCSS,andalsocomeopen-mindedtomysillyjokes!

Youarefreetotakealookatthecoursedescription,andIlookforwardtomeetingyouinside.

Page 10: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 11: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter1WhyLearnJavascriptAnyway?

Didyoueversitinyourcomfycouchatyourhouseandwondered;

WhyJavascript?

Whatcanitdoforme?

Whyallthebuzzaboutit?

And,whatisanelephantdoinginmylivingroom?

Ifithappenstoyou,petyourbrandnewelephantrightaway.Andalso,joinmeinbeingmoreknowledgeableaboutJavascript.

Rightofthebat,Javasriptisreallycool!Youcanaddlogictoyourwebsite,makeitmoreinteractive,andalsomanipulateyourHTMLandCSSduetothatlogic!

Butifyouthought“cool”istheonlyfeatureofJavascript,thenyouarewrong,becauseJavascriptisalsorelativelyeasy,andit’sthebaseofthemostpopularframeworksoutthere,suchasangular.js,react.js,backbone.js,knockout,andevengoodoldJQuery!Whereveryoustep,onthewebdevelopmentworld,you’llseethefootprintsofJavascript.

Ifyoudesiretobeawebdeveloper,thenyoujustHAVEtobefamiliarwithjavascript.Andthat’swhyyouarehere,right?

SoI’mgladyouarehere.Let’sgetstarted.

Page 12: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 13: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter2WhatisJavascript?

Here’saperson,calledBob.

Bobhaseyes,ears,nose,mouth…

Hehasabody,andalsosomeclothes…

Butuntilithasabrainthatfunctionseverythingtogether,it’sonlyabunchoforgansconnectedtoeachother.

JustlikeourweirdbutbelovedBob,youcansurelyknowHTML,andstructurehugewebsite.

Youcanalsodecorateandstyleyourwebsite,withyouramazinglyCSSskills.

But,ifyoulackinyourJavascriptskills,yourwebpageswilllookdullandold.

Javascriptistheprogramminglanguageoftheweb.Itisourfunctioningbrainthatkeepseverythingintouch.

Ifyouwantyourwebsitetobemoreinteractive,soyouruserscouldclickononeelementandbeamazedwhenitactuallydoessomething,besureyouhaveyourJavascriptskillswellputtogether.

Sosittight,andletusbegin.

Page 14: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 15: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter3DoIneedtoknowanythingbeforeIlearnJavascript?

Althoughit’sajavascriptcourse,youwillneedtoknowatleastalittlebitofHTMLandCSStounderstandthecoursecontent.

IwilluseseveralexamplesthatusesHTMLandCSS,soifyoudon’tknowanyofthose,pleasegobackandstrengthenthoseskills.

IdohaveHTMLcourseandCSScourseforthosewhoneedsit,andbecauseI’msoawesomelygenerouswithyouguys,Iwillgiveyoua50%couponforanyofmyothercourses.

Youcangrabyourcouponhere:http://basicjavascript.gilad.me/discount50/

Onemorething;forallmyexamplesinthiscourseIwilluseNotepad++,whichisacompletelyfreetexteditor.

(youcangrabithere,forfree!:http://notepad-plus-plus.org/download)

However,ifyouhappentobeallergictomysuggestions,youcanalwaystryothersoftwareaswell.

Iwon’tjudgeyou,Ipromise!

*whispering*Iwill!…*whispering*

Page 16: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 17: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter4Howtosetupyourpage

AlrightAlrightAlright!!!YouarealreadysoldaboutlearningJavascript,youaresupposedtobesetwithyourNotepad++,andyouwanttostartcodingJavascript,right?

Beforeyoudo,youneedtosetupyourpage:

Inordertodoso,allyouneedtodo,istowriteinsideofyourheadtag,atagnamedscript.Likethat:

<!DOCTYPE>

<html>

<head>

<scripttype=“text/javascript”>

#…JAVASCRIPTCODE…#

</script>

</head>

<body>

</body>

</html>

Insideofthescripttag,wewillhaveanattributecalledtype/javascipt,thattellsthebrowserwearehavingajavascripttypedscript.

Insideofthattag,youwillwriteyourJavascriptcode!

Page 18: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 19: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter5Simplealert,writetodocument

OMGOMGOMG!!!I’msoexcited!!!…justlikeababytryingtowalkitsfirststeps,youareabouttowriteyourveryfirstjavascriptcode.

Andit’sgoingtocontain…*DrumsRoll*…

Printingafluffyredgoat!

Whyprintingafluffyredgoat,youask?

Becausethereisnothingmoresuspiciousthanwalkingdownthestreetandseeapersonprintinggoatsjustforthesakeofprintinggoats.Thatisred…and…alsofluffy.

Andthat’sthekindofthingswewanttobeassociatewith,thesedays.Leatherjacketsandafluffyredgoat.So…howarewegonnaprintourfluffyredgoatintoourscreen?

Allyouneedtodoistoprintdocument,followbyadot,andthentypethewordwrite.

Rightafterthat,youwillhavetoopenparentheses“(“andcloseparentheses“)”.insideoftheseparentheses,wewillhavequotationmarks.

Andinthequotationmarks,wewillwritedown“I’mprintingafluffyredgoat…”.Because…that’swhatwedo.

Andintheend,justlikeanylanguage,ifwewanttoendasentence,youwillwriteadot,right?

Butinjavascript,wearewritingasemicolon“;”.

document.write(“I’mprintingfluffyredgoat…”);

Wewillsaveourfile,andrefreshourpageand.Ohmy!

Wejustprintedourveryownfluffyredgoat!

Ah!Hack!That’stoogoodtobeasingularevent!

Let’sprintmoreofthese!

document.write(“I’mprintingfluffyredgoat…”);

document.write(“I’mprintingfluffyredgoat…”);

document.write(“I’mprintingfluffyredgoat…”);

document.write(“I’mprintingfluffyredgoat…”);

Yay……Wearehavinglotsoffluffygoats….!

Page 20: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

OKOK!!!…Nowwewanttowarneverybody,beforeweareprintingourgoats,towatchout!Fluffyredgoatsareontheloose!Preferablywithannoyingpopuponthescreen!

Sowewillwritedownalert,andthenwewillopenparentheses,andinsideourparentheses,wewillhavedoublequotationmarksaswell,andthenwewillwrite“watchout!Redfluffygoatsareontheirway!”

Andwewillcloseourstatementwithasemicolon,asusual.

alert(“watchout!RedFluffygoatsareontheirway!”);

Nowsaveyourdocumentandrefreshthepage,and…oh!Iamveryimpressedbyyoursort-of-a-road-signthingy,warningeverybodyaboutwhatcouldbe…theendoftime!

Bytheway,didyouseethatweplaceouralertbeforethedocument.write,andrefreshedthepage,thealertshowedfirst,butyoudidn’tseetheanyofthetextonyourdocumentjustyet.

That’sbecausejavascriptisoperateasaqueue.Firstinthefirststatement,thenthesecondone…Andsoon!

Nowyouknowallaboutwritingandprintinginyourdocument,andallaboutannoyingpopups!Aswellasallaboutfluffyredgoats.

InthenextchapterI’llshowyouhowtowritecomments.

Page 21: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 22: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter6Comments

Ssshhh!!!Ihavetotellyouasecret.

Yesterday,Iwenttoafortuneteller!

Isatonthechair,andthensheapproachesmeandsaid;

“awww…Mydearlybelovedalmighty,awesomelyhumbleGilad…Ihavetotellyousomethingaboutyourstudents…”

Andyouknowme,Icareabigdealaboutmyyoungpadawans,soIasked…“what?”

Soshetoldme;”Inthenearfuture,theywillbeworkingonaproject…aswebdevelopers!”

AndIwasshocked!Isaid“WHAT???AreyouSURE?Mystudents???”

Soshesaid:“Wa…Wait,Ididn’tgettothepointyet!”.AndIwaslike“oh…Yeah…well…Carryon“

“…Inthenearfuture,theywillbeworkingonaproject…Aswebdevelopers!!!…Andtheywillbeworkingwithotherwebdevelopersaswell!!!…“

“Otherwebdevelopers???Other???Areyousure???”

“Indeed.”

SoIranquicklytomyofficeandpreparedyouthislecture.

Ifyouareabouttoworkwithotherwebdevelopers,youwillhavetocommunicatewiththemproperly,andthereisnobetteroptiontodoso,butwithcomments!

Commentsareforyourownsolepurpose,andforyourcolleaguesaswell.

Yousee,Commentsarenotbeingrenderedonthepage,soyoucanwritewhateveryouwant,like“heyJeff,don’tmentionaboutyesterday,Iwasreallyhungry.And….yourcomputerwastheonlythingthattasteslikechicken!P.S,thislineofcodeisgettingeverythingfromthedatabase.”.

Sonowyouknowwhydoyouneedcomments,buthowcanwedothat?

Simplywriteinsideofyourscripttagtwoforwardslash,andstarttyping!

Likethat:

//HeyJeff!…Sorryaboutyourtastychickencomputer

Saveit,Refreshit,and….It’sachristmasmiracle!Justlikewe’veexpected:nothingrenders!

NowonlymeandmycolleagueJeffwouldknowaboutourlittleincident.

ButwhataboutifIwanttoleaveJeffmulti-linecommentaboutwhatIatefordinner…thelist

Page 23: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

ofthingsI’mallergicto…andwhyIalwayslaughlikeacrazypersonwhenitrains?

Sointhatcasewewouldhaveoneforwardslash,followedbystar.Wewritewhateverwewanttowrite,andthencloseitwithstar,and…anotherforwardslash.

/*HeyJeff,Thanksforthepresentforchristmas,howeverIfeellikeWearenotinthatphaseofourrelationshiptosendingeachotherParkingtickets.

P.S.:Thiscodeisnotworking.

P.S.S:weareoutofmilk.Sogetone.thanks!*/

Hopefully,youwouldnotworkwithJeff,becauseheisahandful…

Butifyouwouldorwouldn’t,atleastnowyouknowhowtowriteJavascriptcomments.

Page 24: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 25: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter7Variables

Doyourememberbackinschoolwhenyourteachersaidsomethingalongthelinesof…

X=98

Andthenshesaidsomethinglike:

“DannyjusteatXapples”,

Youallknew…Youallknewshe'stalkingaboutDanny,thatjustswallowed98apples,right?

That’sexactlyhowvariablesworksonJavascript.

JavascriptVariablesarelikelittleplaceholders,theystoreyourdata,andthenifyouwanttousethatdatalater,youjustcallthevariablename,anduseit!

Sobeforeyouwilluseyourvariable,youneedtodeclareanameforit.

Sotodeclarevariable,thelazyjavascriptpeoplejustshorthandthewordvariableintojust“var”…soyoushouldalwayswrite“var”first,andthen,youcancomeupwitheverynameforyourvariable,anynameyoucanthinkof…I’llwritemynameforexample,“gilad”

Then,youshouldwriteanequalsign,andthenwhatyouwanttoassignyourvariableto.

Let’ssaywewanttoprintthenumber9.

Andwewillcloseitwithasemicolonlikealways.

vargilad=9;

Rightnowyoualreadyknowhowtoprintstufftoyourpage,rememberourfluffyredgoat?

document.write(“I’mprintingfluffyredgoat…”);

Soerasethetextinside,andjustwriteyourvariable’sname(noquotationmarkneeded!).

document.write(gilad);

Saveit,andrefreshit.

Hollygoats!We’vegota9onourscreen!

Let’sexplainwhatjusthappened:

Yourbrowserthinkingforhimself,“ohalright,awesomely-cool-web-developer!Youwantmetosetavariable,andthenyoucallthevariable‘gilad’.Soi’llsetaplaceinmyroomjustforyou…AndIwillcallthatplace‘gilad’fromnowon…“

Page 26: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Thenwewrotetheequalsign…sothatmeansyousetittowhateverontherightsideoftheequalsign.

Whichis9.

Sothecomputersays“ok,I’llnowstore9,inmyplacecalled‘gilad’.AndIpromiseyou,Iwilluseitwhateveryouwilltellmetouseit…“

Thenwhenwecalledthe‘gilad’variableinsideour ‘document.write’ ,thecomputertookthevalue,andprintitinsideofthedocument.

Oh,butonemorething…DoyourememberItoldyouaboutthenameofvariable,andthatyoucannameitwhateveryoulike…Well…youcan.

Butyouhave2rulesyouhavetokeep,ok?

Rulenumberone:

Don’teverwriteanythingfunkylikethat: #5^$%^^$. Yourbrowserwillgobananas,

andwouldn’tknowwhatyoumeanbythatname!Youcanonlycallyourvariablesbyletters,

numbers,andunderscores.

Rulenumbertwo:

Javascriptiscasesensitivelanguage,sodon’tcallyourvariable jeffery ,alllettercase,and

thenafterwardscallit JeFferY likeacrazyperson.Forthebrowser,It’slikeyouwillcall

Somegirl“Hillary!”andthenswitchto“HeyBrittney!SupBrit…Imean…Doris!…Doris!!!

Jenni…Bath!…Elizab…Doris!!!Doris…”

Yeah…sodon’tdothat…Otherthanthat.You’resafe!

Page 27: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 28: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter8Variabletypes

Doyourememberwhenyouwereababy,youhadthisweirdgameofshapes,andyouweresupposedtosortthoseshapesandputeveryshapeintoitsplace?

Justlikethatgame,Javascripthasdifferenttypesofvariables.Andtheycannotfiteverywhere…

Letmeexplainittoyoubyfirstwritingitdowninourtexteditor:

Iwillwrite var ,name,equalsto9:

varname=9;

document.write(name);

That’swhatwe’vedoneinthelastlecture,right?

Wehaveavariablenamedname,andit’sequaltothenumber9.

But,mynameisnotnine,right?(Iswearit’sdoesn’t!)

Let’strytoerasethenumbernine,andplacemynameinstead.

varname=gilad;

document.write(name);

Saveit,refreshit,andlet’sseewhatwehavehere…

ah!Nothingshows!Whathappened?

Thedifferencebetween9andagilad,isthat“gilad”isatext(orasJavascriptliketocallit:a“string”).And9isjustanumber.

Thethingis,javascriptcouldeasilythinkthatgiladmaybejustanothervariable,andbecauseitcouldbeavariable,it'stryingtolookforitintheentirepage,andwhenitcouldn’tfindit,itjustsays…“OhWell,alright…Ididmybest,Icannotfinditanywhere…SoI’lljustdonothingandrelax…”(givingupearly,huh?)

TosayexplicitlytoJavascriptthatwehaveastringhere,weneedtowrapourtextinsideofquotationmark.

Let’sdothat:

varname=“gilad”;

document.write(name);

Page 29: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Saveit,refreshit,and…yeahbaby!We’vestillgotit!

Sonowweknowthatwehavetwodifferenttypesofvariables.

Numbers,andstrings.

Andthedifferencebetweenthemisthatlittlequotationmark.

Wehaveafewmoretypesofvariablesinjavascript,andwewillcovertheminlaterlectures.

Page 30: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 31: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter9Usingdifferenttypesofvar

DidyouknowthatJavascriptcanmakeyourhomework?

IfIknewthat,IwouldstudyJavascriptatage5!

Here’sanexample:

document.write(3+3);

Thatcouldcomehandyinfirstgrade,don’tyouthink?

Hmm…let’strysomething…

I’lldeclaretwo vars ,thefirstoneIwillname num1 andsetitto4,andthensecondone,Iwillname num2 ,andsetittothenumber2.

Nowinthe document.write ,Iwillreplacethe3+3into num1+num2 ,andrunit.

varnum1=4;

varnum2=2;

document.write(num1+num2);

Alright…we’vegot6.Awesome!We’velearnedsomethingnew!Wecanactuallyaddvariablestogether!Imaginethepossibilities!

ButIwonderwhatwouldhappenedifIwouldchange…say… 4, into“ 4 ”,youknow,asastring…

Alright,let’sputourmadscientistgogglesandtryitout:

varnum1=“4”;

varnum2=2;

document.write(num1+num2);

Oh,that’sweird…42?

Imean,Iknowtheanswertolife,theuniverseandeverythingis42,but…Ididn’taskthat…

Let’sseewhathappened:

First,wetyped num1 ,equalsto4.Butsincewehaveourquotationmarkaround4,itwouldbeconsideredas“string”andnotasnumber.Soourbrowsermerelyprinted4onthescreen.Andthen,weadded2.Butsinceour4isonlyastring,ourbrowserdidn’tthoughtit’samath

Page 32: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

problem,andjustaddedittothescreen,asis…

Sowecouldeasilyreplace4to“Iloveyou“

Andifwewillrefreshthepage,wecanseethatyourbrowserlovesyou2.

Browser!!!Sillyyou….

Page 33: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 34: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter10Mathoperators

Inmath,wehave4basicoperationsthatyoucanmake.

Addition,subtraction,multiplication,anddivision.

Inthelastlecture,We’vealreadyseenthatwecanaddnumbersinjavascript.

varnum1=4;

varnum2=2;

document.write(num1+num2);

Butapartfrombasicaddition,we’vegotanothermathoperationinJavascript.

Let’stakeatakealookattherestofthem.

Wehavegotsubtraction:

varnum1=4;

varnum2=2;

document.write(num1-num2);

Yousimplymaketheminussign.

Ifyouwanttomultiplynumbers,don’twritethexletterorsomethinglikethat,simplywritestarinstead:

varnum1=4;

varnum2=2;

document.write(num1*num2);

That’sMultiplication.

Wecandividenumbersaswell.

Allyouneedtodo,istotypeaforwardslash.

varnum1=4;

varnum2=2;

document.write(num1/num2);

Page 35: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Sothat’sdivision.

NowI’vegotabonusforya!

Let’ssayyouwanttoincrementanumberbyone.

So…ofcourse…youcantypesomethinglikethat…:

varnum1=4;

document.write(num1+1);

But!Ifyouarealazypersonlikemyself,youcanshorthandanddothat:!

varnum1=4;

document.write(num1++);

Orsomethinglikethatifwewantanumbertobedecreased:

varnum1=4;

document.write(num1--);

Theplusplus(++)sign(andalsotheminusminus),willincrementor…decrement?(Canwesaydecrement?!)yournumberbyone.It’sshortanddandy,andwewillalsoseethatalotinourfuture,whenwewillencountermorecomplexstuffonJavascript!

Page 36: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 37: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter11Functions

Here’saTruestory:

WhenIfirstcameoutfrommyparents’house,Ihada…well…a…littletiny…Really…mini-ti…tiny-problem.

Well,yousee?Ihatecleaning,andwhenIfirstcameoutfrommyparents’house,nobodywascleaningafterme(ahh!!!Thehorror!).Soafteradayortwo,Ihadtonsofdishesinmysink,mycleanclothsblendperfectlywithmydirtyclothesonmybed,myfloorwascompletelyamess,andmytwocatsdidn’treallyhelp(meow!).

SothefirstthingI’vedone,istogetmeonethoserobotswhocleanthefloorafteryou.

Aperfectsolutionforthelazymaninourera.

AndIwasveryglad!Itwasarepetitivetask,thatIcouldhavedonemyselfformanytimes,thatsomesortof…robot:isdoingitforme!

SoifwegotoourworldofJavascript,youmayalreadythinkthatthereisapossibilitytocodetheSAMEcodeoverandoveragain…

Andifyouarelazylikeme…well…youwillneedtofigureouthowtomakeyourselfanewrobot!

Tothisrobot,theJavascript-peoplecalled“Function”s.

Insteadofwritingthesamecodeoverandoveragain,yourFunctionwillbasicallystoreasegmentofyourcode,andwhenyouwouldliketoexecuteit,youcancallit,andthefunctionwillrun.

LikeIalwayssay,Let’sseesomeexample,andyouwillunderstanditbetter:

Let’ssaywewanttohaveafunctionthatwillcongratulateuseverytimeweenterourwebsite.

So,inordertowriteafunction,allyouneedtowriteis….

“function”!

Sogoahead,andwritefunction,andthenyournameofthefunction,andjustlikeyourvariables,youcannameitwhatevernameyouwant,butit’sagoodpracticetogowithameaningfulofwhatyourfunctionneedstodo.Soifwewanttocongratulateyourusers,let’scallit“Congrats”.

Andthenafterthename,weneedtoopenparenthesis,andcloseparenthesis(bytheway,thoseparenthesis’areactuallyhaveameaning,butfornow,justleaveitwithoutanythinginside).

Thenopencurlybracketandclosecurlybrackets.Andinsidethecurlybracketswewilltypeourcodethatwewanttobeexecutewhenwecallthefunction.

Page 38: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

functionCongrats(){

//….javascript“congrats”code…

}

Wewantourcodetocongratulateourusers,solet’swritesomethingonalert…Let’ssee…

“Welcometothe‘hamster-mobile’website.Whereyoucanfindacheapvehicletoyourbelovedhamster…“

Well,Ithinkweknowwhatournextstart-upwouldbe,right?Ihopewedon'thaveanycompetition…hmm…

Ihavetocheckthisone…

Oh…man…Icannotbelieveit!

ApparentlythereISahamster-mobile…ohhh…mydreamsjustshutteredlikewindows8…

HowcanIrecoverfromthisone?

Anyway…

Let’salsoaddabitofcodethattellusourcongratulationalerthasjustbeenstarted.Andalsoonetextthatourcongratsjustended.

Let’srunourthing!

Nothingshows!Iwonderwhy?

That’sbecausewesetourfunction,butwedidn’tcallit,right?

Solet’scallit.Justtypeanywhereoutsideofyourfunction,yournameofyourfunction,andthenopenparenthesisandcloseparenthesis.Andthenendwithsemicolon:

functionCongrats(){

document.write(“startingcongratulations…”);

alert(“Welcometothehamster-mobilewebsite.

Whereyoucanfindacheapvehicletoyourbeloved

hamster…“);

document.write(“endingcongratulations…”);

}

Congrats();

Saveit,refreshyourpage,and…BAM!We’vegotourweirdlycongratulationsupand

Page 39: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

running!

Noweverytimeyouwanttousethisthing,wewouldn’tneedtowriteourdocumentwriteagain,andouralert…Andanothertimethedocument.write…WejustneedtocallourCongratsfunctionagain,andthat’sit!

Congrats();

Congrats();

Page 40: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 41: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter12FunctionsParameters

Doyouknowthatgameshowcall“Let’smakeadeal”,thatdoyouhave3curtains,andyousupposetoguesswhichcurtainhasthebrandnewshinycarandwhichonehaslikealivingadultllama?

Ialwayswonderediftheyactuallyhavetotakethellamaafterwards…Andfeedit,cleaningafterit,bebestfriendwithit…Eveniftheyareallergictothatllama,buttheydon’tfeelsafeenoughbecausethatLlamaisaviciousLlama…

Anyway…

TodaywewillhavetheJavascriptversionoftheshow“Let’smakeadeal”!

First,wewillhave3inputs,typedbutton.Eachandeveryoneofthem,willrepresentacurtain.

Curtain1,curtain2andcurtain3.

<inputtype=”button”value=”Curtain1”/>

<inputtype=”button”value=”Curtain2”/>

<inputtype=”button”value=”Curtain3”/>

Nowlet’smakeroomtoourfunction:

Createanewfunctioncalled ShowCurtain ,butinsteadofleavingtheparenthesisorphaned,typeprize.(don’tworry,wewillexplaineverythinginamoment,justletmefinishupthisfunction…)

Nowwewillwriteinsideofthefunctionanalert,with“youwon”message,andalso,thesameprizethatwehaveinsideofourparenthesis.

functionShowCurtain(prize){

alert(“Youwon”+prize);

}

Alright,let’sexplainwhatisthatprizethingy…

Whateverwehaveinourparenthesis,called“parameter”,andourparameterisactuallyactinglikeadynamicvariable…

Thatmeans,whenwewillcallourfunction,wewillsettheparameterinourparenthesesjustlikeweseteveryvariable…Andthen,ourparameterwillliveandbeusedaslongasthefunctionisrunning.

Alright,solet’strysomethingnew,ey?

Page 42: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Insteadofcallingourfunctionthelasttime,wecancallitwhenourbuttonisbeingclicked.

Soaddtoeachbuttonanattributecalled“ onclick ”,andsetittoyourfunction,andremember,ourfunctionasksforaprizeparameter,sosetittowhateverprizeyouwanttoget.AndbecausewealreadyuseadoublequotationmarkforourHTMLattribute,usesinglequotationmarkinsteadtowrapourstring…Thatshouldwork.

<inputtype=”button”value=”Curtain1”onclick=”’ashinybrandnewtoothpick!’”/>

<inputtype=”button”value=”Curtain2”onclick=”’acolorfulrubberband’”/>

<inputtype=”button”value=”Curtain3”onclick=”’alivingLlama!’”/>

Alright,saveit,refreshyourpage,andlet’strytoseewhatwe’vegothere:

Let’sopenourcurtainnumber1…Its…its…yes!!!Ashinybrandnewtoothpick!veryhandy…veryhandy…

…Nowcurtainnumber2…Thecrowdroarwithenthusiasm…it’s…ohmy!Acolorfulrubberband!!!Cannotwaittouseit!

Now…curtainnumber3…whatitwouldbe?ohmy!!!Icannotbelieveit…myall-timefavorite!Alivingllama!!!whowouldfeedthisanimal!?

Icannotbelieveit…Whatawonderfulday…

Javascriptfunctionparameters???andalivingLlama?!Whatmorecananinstructoraskfor?!

Page 43: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 44: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter13MultipleParameters

Sometimes,youcanhavefunctions,thatcanholdparameters,butyouwillneedtoaddanotherparameteraswell.

Inourlastexample,wehadoneparameterthataskedtheprizemoney,andwehadamessagethattellstheuserwhatprizethathewon,butwhatifwewanttoaddanotherinformation,like,whatcurtainnumbertheuserjustopened?

Ifwewouldliketoachievethiskindoftask,wecanaddanotherparametertoourparenthesis.

Justaddacomma,andtypetheextraparameternameyouwanttoadd.

Forexample,tomakeourmessagecooler,wewilladdanotherparametercalled curtainNumber ,andthenpromptinourmessage“Youopenedcurtainnumber”andthenwewillhaveourparameter,andwewillcontinueourtextwithwhathewonlikewehavedoneinthelastexample:

functionShowCurtain(curtainNumber,prize){

alert(“Youopenedcurtainnumber”+curtainNumber+“,Youhavewon”+prize);

}

Nowwewilladdthedifferentcurtainnumberstoourbuttons,sotheparameterknowshowtobesetup.

onclick=”1,’ashinybrandnewtoothpick!’”

Butnotethattheorderoftheparameterisimportant,ifwehaveour curtainNumber thefirstparameter,wewillneedtosetitfirstaswell…

Alright,let’stestourcurtains!

Works!

yay!

Page 45: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 46: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter14ReturnStatement

Inthepreviouslectureswetalkedaboutfunctionsandourfunctionsjustdidsomething,right?

Weprintthingsonthescreen,pressonebuttonandamessagepoppedout,stufflikethat…

Butinsomecasesyouwantyourfunctiontoreturnsomevalue,soyoucoulduseitlater.

That'swhywehaveourreturnstatement.

Let’shaveanexample:

Writeafunctioncalled BasicAddition, thatrequest2parameters, num1 and num2 .Itwillreturntheadditionofbothofthem.

functionBasicAddition(num1,num2){

returnnum1+num2;

}

Nowwewillcallthefunction,andwewillplacetheparameters1and2.Andwewillexpecttogetthenumber3beout,right?

BasicAddition(1,2);

Ifwewillrunitrightnow,nothingwillshows.

Andthisisbecausewedidn’ttellourfunctiontodoanythingwithit.Itdidn’tprint,anddidn’tevenstoreitanywhere.

Let’smakeanewvariable,called result .Andwewillgettheresultrightoutofour BasicAddition function.Andthen,wewillprintresulttothepage.

varresult=BasicAddition(1,2);

document.write(result);

Let’ssaveitandrefreshit,and…bam!We’vegotit!

Wereturntheresultofthenumberweadded,westoreditonavariablecalledresult,andthen,weusedthevariablecalledresult,andprintitonthepage.

Page 47: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 48: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter15Callingfunctionfromanotherfunction

Oksoyoualreadyknowhowtowriteafunction,andhowtowriteaparameterforthisfunction,andevenmultipleparameters,andeven…(Godforbid!),areturnstatementforthisfunction!

NowI’llshowyoualittletrickthatwillcomehandyoneday…

Youcanactuallycallafunction…withinafunction!

Let’stryitout,createafunctioncalledGoodNight,andanotherfunctioncalledGoodMorning.Withouttakinganyparameters.

InsideoftheGoodNightfunctionwewouldhavedocument.write,andwewillsay“Goodnight!”andintheGoodMorningfunction,youguesseditright,wewilltype“Goodmorning!”

functionGoodNight(){

document.write(“GoodNight!”);

}

functionGoodMorning(){

document.write(“GoodMorning!”);

}

Andnowwewillhaveanotherfunction,calledStart,itandwewillcallbothfunctionsfromtheStartfunction.

functionStart(){

GoodMorning();

GoodNight();

}

Rightnow,ifwewillrefreshourpage,nothingwillhappen,becausealthoughwecalledGoodMorningandGoodNight,wehavenotinitiatetheStartfunction.OnlywhenwewillcalltheStartfunction,wewillseestuffgoingon.

Let’sdothat!

Start();

Page 49: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

See?WhenwestartedStartfunction,werunalsobothfunctionswithinit.

Nowlet’strytobreakourbrowserapart.(don’ttryitathome!Nahh…kiddin’.Youcan!)

WewilltaketheGoodMorningfunction,andplaceitwithintheGoodNightfunction,andviceversa,andthenwewillcallstartbytellingittocallGoodMorning.(andforthesakeofreadability,addabrtagtoeachwritestatement.

WewillexpectthebrowsertogotoGoodMorningandsaygoodmorning,andthengotoGoodNightandsay“goodnight!”.Andthenbacktogoodmorning,goodnight,goodmorning,goodnightgoodmorning,goodnightgoodmorning…Hesupposedtogetinsideofsomesortofalimbo…leavingitswifeanditschildren…Andevenitsownsanity!

functionGoodNight(){

document.write(“GoodNight!<br/>”);

GoodMorning();

}

functionGoodMorning(){

document.write(“GoodMorning!<br/>”);

GoodNight();

}

functionStart(){

GoodMorning();

}

Start();

Let’srefreshit,and…oh…wow…Betterthanfireworks!

Page 50: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 51: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter16Ifstatement

BeforeIwantedtobeawebdeveloper,Ialwayswantedtobeahamster-tamer.

Youknow,justlikealiontamerthatworkswithlions…But…withhamsters.

Yousupposetotamethem,sotheycan…dostuff.

Anyway,sometimesIwonderwhatifIwasgoingwithmydream.

Andtomakethisthoughtcometrue,Iwillusemyjavascriptskills!

InJavascript,youcanhaveconditionsinyourcode.

Forexample:

Ifxistrue,then…executethiscode.

Ifxisfalse…Then…dothatcode.

Ifxisgreaterthany,thenrunthosefunctions…

Let’smakeithappened!

Towriteanifstatement,youshouldtypeif,thenopenparenthesis,andtheninsideofthoseparenthesisyoushouldwriteyourcondition.

Thenyoushouldopencurlybrackets,andinsideofthosecurlybrackets,yourcodewillbeexecute,onlyiftheconditionistrue.

if(##YOURCONDITIONHERE##){

##YOURCODEHERE##

}

Solet’ssaywewanttocheckifthenumber2isreallyequalstothenumber2.(you’llneverknow,right?)

Let’smaketwovariables, num1 and num2 .Andwewillsetbothto2.

Sointhecondition,type num1==num2 .

Notethatwearehavingtwoequalsigns,andnotjustoneequalsign.Thereasonforthat,isthatifwewilltypejustoneequalsign,thebrowserwillmightconfuseandthinkwewanttosetanewvariable.Sotwoequalsignisthewaytogo,ifyouwanttocheckifsomethingisequaltosomething.

Let’schangeourcodeheretojustsay“IfIwasahamster-tamer,mycowwasbroken”,becauseshemightbesomeday!

Page 52: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

varnum2=2;

varnum1=2;

if(num1==num2){

document.write(“IfIwashamster-tamer,mycowwasbroken”);

}

Andlet’srunthisthing!

Andindeedthat’strue,2isequalto2,afterall,andwehaveabrokencowjustnow.

Whatifwewanttocheckratherif2isnotequalto2.

Weshouldtypeinsteadoftwoequalsign(let’serasethat),weneedtotypeexclamationmark,followedbyequalsign.That’s“notequal”.

Solet’stestjustthat.

if(num1!=num2){

document.write(“mycowisbroken”);

}

Let’srefreshthat,andyup!Aswesuspect!Wedon’tgetanymessage,thatmeansthat2stilldoesequalto2,andbecausewecheckforifit’snotequal,thecodedoesn’tfire…

Ifwewillchangenum1intothenumber3,andrunthecodeagain,wewillseethatthecoderunperfectly,because3isnotequalto2.

Let’slearnanotherone!Whatifwewanttocheckratherif3isgreaterthan2.

Wewillchangeourconditiontothisfunkyanglebracket…

varnum2=3;

varnum1=2;

if(num1>num2){

document.write(“mycowisbroken”);

}

Ifwewanttocheckif2isgreaterthan3,weneedtochangeittoagreatersign.

Page 53: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

if(num1<num2){

document.write(“mycowisbroken”);

}

Nowwecancheckifonenumberis“lessthan”theother,orequal…

if(num1<=num2){

document.write(“mycowisbroken”);

}

Soifwewillcheckthenumber4,itwon’trun,3,itwon’trun,2…?bam.Gotit.

Andwecanalsocheckifit’s“greaterthan”or“equal”

if(num1>=num2){

document.write(“mycowisbroken”);

}

Cool!

Page 54: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 55: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter17Else&Elseif

Let’ssayyouhaveacondition,forexample….theword“banana”equalstotheword“banana”:

Andwhenitdoes,youwillhaveafunctioncalled“ChoppingBanana”.

if(“banana”==“banana”){

ChoppingBanana();

}

Tillnow,nothin’new,right?

Bananaisabanana,andthecodewillbefire.

AndifIwillreplaceoneofthebananasintoaPineapple…theChoppingBananafunctionwillnotbefired…right?

Butlet’ssayIwantsomeotherfunctiontobefireiftheconditionisnottrue?WhatdoIdo?

Inthiscase,weneedtotyperightafterourlastcurlybracketsan“else”statement.andanothercurlybrackets,andinsideofthosecurlybracketswecanwriteourcode.

if(“banana”==“pineapple”){

ChoppingBanana();

}else{

ChoppingPineapple();

}

Ifwewant,wecanwriteanotherconditionaswell,wewillwrite“elseif”andanothercondition,say“banana”equalsto“cherry”,andthenanothercurlybrackets.

if(“banana”==“pineapple”){

ChoppingBanana();

}elseif(“banana”==“cherry”){

ChoppingCherry();

}

else{

Page 56: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

ChoppingPineapple();

}

Sointhisexample,thebrowserwillgofirstintothefirst if, andasktheconditionratherifabananaisapineapple.Ifit’snottrue,thenhewillgotothenextif,the“elseif”,andask…“Doesabananalookslikeacherry?”,wellitdoesn’t…Oh!Onemorething…Youcanhaveasmanyelseifaswecanwish!!!Wecanhavelike…Agazillion elseif …Ifsomeconditionistrue,itwillbefirethecodeinsideofit,andleavethewholebunchof ifs and“else”and“ elseifs alone…Butifitdoesn’t,itwillcontinuetoaskuntilitgetstothelastelse.

Theelseisthefinaltryofourbrowser,ifno if statementandno elseif wasfired,thanourbrowserwillbesatisfiedandgoin.

Ifyourbrowservisitedanycondition,the else statementwillnotbefired.

Page 57: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 58: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter18Switch

Whoknows,maybesomedayyouwillhaveyourownwebdevelopmentcompany.

Andasanyotherbigcompany,ithasitsown…vendingmachine!

Butwearenotlikeanyotherbigcompany,right?ourvendingmachinewillbespecial!

Sowewillhavethe…*drum*

TheVendingPendingMachine!

Ourvendingmachinewillmakeyoupending.And…that’sit.Nosodaoranything.Just…waitforawhile,andgoaway.

Alright,sofirst,ofcourse,wehavetobuildourvendingpendingmachinetitle,sowewilladdafewshticksinHTML…

<h1>TheVendingPendingMachine</h1>

<inputtype=”button”value=”1”/>

<inputtype=”button”value=”2”/>

<inputtype=”button”value=”3”/>

<inputtype=”button”value=”4”/>

NowLet’sbuildtheVendingPendingMachinefunction.

Iwilltypeafunctionnamed VendingPendingMachine ,thatasksfora pendingTime parameter,andinsideofourfunction,Iwillinitiatea switchcase statement,letmetypeitdown,andIwillexplainitfurtherafterwards:

functionVendingPendingMachine(pendingTime){

switch(pendingTime){

case1:

//CODEFOR#1…

break;

case2:

//CODEFOR#2…

break;

case3:

//CODEFOR#3…

Page 59: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

break;

Default:

//DEFAULTCODE…

}

}

Sothebrowsercomestoourfunction,withaparameterinhand,let’ssayithasthenumber1asaparametervalue,thencomestothe switchcase statement,itsetsthe switchcase withthe pendingTime as1,andthenitsearchfortherightcase,ifcaseis1,thenitcomestothefirstone,ifcasenumber2,thenitfiresthesecondone…Andsoonandsoforth…Itcouldbeevenanamelike…“Hamster”,iftheswitchisequaltothecase,thenitwillfireourcode.

Ifnocasematchesourcases,thenitwillbefireourdefaultcase,but…Ofcourse…Itsoptionalcase…

Let’spopulateourcases!

Wewillmakeamessagefunction,sothevendingpendingmachinecouldsaytoourusers,howmanyminutestheyaresupposetowait…

functionPendingMessage(time){

alert(“TheVendingPendingMachinesays

youhavetowait”+time+“minutes”);

}

SoIwillwriteafunctioncalled PendingMessage ,thatgetsa time parameter,andthenprintsthemessagewiththe time parameterwegot.

functionVendingPendingMachine(pendingTime){

switch(pendingTime){

case1:

PendingMessage(pendingTime);

break;

case2:

PendingMessage(pendingTime);

break;

case3:

Page 60: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

PendingMessage(pendingTime);

break;

default:

PendingMessage(pendingTime);

}

}

functionPendingMessage(time){

alert(“TheVendingPendingMachinesays

youhavetowait”+time+“minutes”);

}

Nowweneedtoplaceourfunctionsinsideofourbuttons:

<inputtype="button"onclick="VendingPendingMachine(1)"value="1"/>

<inputtype="button"onclick="VendingPendingMachine(2)"value="2"/>

<inputtype="button"onclick="VendingPendingMachine(3)"value="3"/>

<inputtype="button"onclick="VendingPendingMachine(7)"value="4"/>

Alright!

Let’stryourvendingpendingmachineforthefirsttime!

Let’spressbuttonnumber1.

Wewillhavetowait1minute…(Butwewon’t…because…Idon’twannawait.)

Let’spressnumber4,weshouldgetintoourdefaultcase…

Wehavetowait7minutes…Ohno…

Ok…yougotothenextlecture,I’llwaithere.

For….7minutesIguess.

Page 61: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 62: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter19Forloop

Backinthedays,andstillintheSimpson’sepisodes,therewasawidespreadpunishmentfornaughtystudents.Writinglikeagazilliontimeswhattheydidwrong…Forexample…“Imustnottalkinclass”or“Iwon’tforgettodomyhomeworkagain”…Andstufflikethat.

Sotodaywewillbreakallthenaughtystudentsfree,withourshinynewMachine,thatwritelinesforyou!

Sofirstofalllet’smakeourdocumentlookslikechalkboard…

<style>

body{background-color:#333333;color:#f0f0f0;}

</style>

Alright,firstthingfirst,let’sseehowcanwerepeatthesamestuffoverandoveragain…

Andtomakethathappen,wewilluseourbrother-from-another-mother,the“forloop”.

Theforloopisatechniquethatletsyouloopthroughanycode,untilyouhitsomesortofacounter…Let’swriteitdownandI’llexplainitfurther:

for(i=0;i<10;i++){

##…CODE…##

}

Alright,sotocreateaforloop,youhavetowritethewordfor,andopenparenthesis…Insideoftheparenthesisyouhave3sectionsdividedbysemicolons,thefirstsectionyousupposetoresetyourcounter.Becausetheforloopisrunninguntilyouhitthatcounter.Sothefirstsectionistoresetyourcounter,andyoucancallyourcounterwhateveryoulike,Inamedit i ,that’sshortenough,andresetittozero.

Rightafter,wehavethesecondsection.Itallabouttellingtheforloop:”ifthat’sconditionistrue…Well…justkeeploopin’willya?!“soIwrote“ i<10 ”,whichisinenglish:“aslongasourcounter‘i’isunder10,don’tmentionit,justkeeplooping…“

Andinthelastsection,isthethecounterincrement.Aftereveryloop,dotheplus-plusthingy,whichifyouareremember,means“incrementyourselfbyone!”,soifourcounteriis0,afteroneloopitwillchangeto1,andthento2,andthento3andsoon…

Andeverytimeourmiddlesectionissatisfied,ourcodeherewillkeeponrunning.

Alright,let’scombinealil’bitofforloopsandfunctions,andcreateourselvesaWritingLineMachine!

Page 63: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

?? ♫ …WritingLineMachineee….yeahh…eaa…ea…a… ♫ ??

Yeah,sofirstofall,wewillwriteafunctioncalled WriteLineMachine witha forloop insideofit,andthatfunctionwilltakeaparametercalled lineText .

Andwewillletthe forloop runningfor10timesfornow…

functionWriteLineMachine(lineText){

for(i=0;i<10;i++){

//…Somewritefunction…

}

}

Iwillleaveacommentnowinsideofthe forloop ,andnowwewillwriteafunctionthatwritingourtext,andthenwewillinsertitinsideofourforloop,k?

Solet’swriteitdown!

Iwillcreateanotherfunctioncalled Write ,andthisfunctionwillaskforaparametercalled lineText ,anditwillsimplywillwriteonourdocument,thesamevaluetheparameterhas.

functionWrite(lineText){

document.write(lineText);

}

Andwewillinsertournewfunctioninsideofour WriteLineMachine …Andlinktheparameterofthe WriteLineMachine

functionWriteLineMachine(lineText){

for(i=0;i<10;i++){

Write(lineText);

}

}

Alright,andnowwewillhaveanotherfunctionthatstartsourmachine,called StartMachine ,andwewilljustinsertour WriteLineMachine insideofit.Withaparameterof lineText.

functionStartMachine(lineText){

Page 64: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

WriteLineMachine(lineText);

}

Now,wewillhaveanewvariable,thatholdsatext.let’ssaywewanttorepeat…thistext:

“Iwillneverridemyhamster-mobiletoschooleveragain.”(Ipromise!!!)

vartext=“Iwillneverridemyhamster-mobiletoschooleveragain.”;

Andfinally,welinkalltogetherwitha StartMachine ,andlettingituseourtextvariable…

StartMachine(text);

Soourcodegotoour StartMachine function,withourtext,travelstoour WriteLineMachine functionwithourtext,loop10times,andeachandeveryloophewillvisitour Write function,thatjustprintinginsideofourdocument,ourtextwhichis…Well…myforbiddenridesonthehamster-mobile…

Bytheway,wecaneasilythinkofimprovingourmachine,andgiveitdynamicvariableofthenumberofloops…Likethat:

varloopNum=50;

for(i=0;i<loopNum;i++){

Write(lineText);

}

Andthat’sit.

Nowwecantrickourteachersandletourmachinetowritelinesforus!

Page 65: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 66: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter20Array

SonowwewilllearnwhatArraysis.

SometimesyouwillwanttoliststuffonyourJavascript,likealistofyourusernames,ordates,orwhatever.

Inordertodojustthat,youcansurelydeclareavariableforeveryoneofthem,likevaruser1,varuser2,varuser3,andsoon…Butitwillbecompletelyinefficient.(especiallyonbiggerlist…)

Soforthatkindoftask,wehaveArrays.

Arrayswillstorealist,butonjustonevariable.

LetmeshowyouwhatImean,Iwillcreateanarrayofnames.allyouneedtodoistotype“ new ”andthen“ Array ”,andthe Array wordissomethingyouhavetotype,youcannottypewhateveryouwant,that’sreservedname…

Youopenparenthesis,andinsideofthoseparenthesesyouwriteyourvariables,IwilltypeanarrayofstringnamesasIsaidearlier.

BigTony,AmazingBob,CoolJeff,andAwesomeJane.

varnames=newArray(“BigTony”,“AmazingBob”,“CoolJeff”,“AwesomeJane”);

Nowlet’ssayIwanttoprintonthescreenthenameAmazingBob,whatdoIdo?

Iwillwrite document.write ,andtheninsideofourparenthesisIwillwritename,becausethat’sthevariableofourarray,andthenwewanttoaccessBob.

Whatwedon’tknowisthateachandeveryoneofthatarray,hasasecretindexnumber,andinsteadofone,itstartswithzero.

SoBigTonywillbeindexedzero,AmazingBobwillbeindexedone,CoolJeffwillbeindexedastwo,andAwesomeJanewillbethree.

SotoaccessamazingBob,weneedtotypeindexone,right?

Sotomakethathappened,wewillopensquarebrackets,andtype1.

Let’stryit.

document.write(names[1]);

Andherewego,wehaveamazingBobrightthere.

Andifwewantedto…getAwesomeJaneprintedonthescreen…Let’sseewhat'sherindexnumber…0,1,2,3.

Page 67: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

ThreeistheindexofJane,let’schangeitto3here:

document.write(names[3]);

Andwe’vegotJane!

Nowlet’sdosomethingfunky!Let’ssayouruserAwesomeJane,decidedtochangehernametoTammy.

Inthatcase,wewouldwritenames[3]toaccesshername,andthensetit,justlikewesetanewvariable,“Tammy”,andlet’saddanotherdocument.write,toseethatindeeditchangedovertime.

varnames=newArray(“BigTony”,“AmazingBob”,“CoolJeff”,“AwesomeJane”);

document.write(names[3]+“<br/>”);

Names[3]=“Tammy”;

document.write(names[3]+“<br/>”);

Andyup.We’vegotit!

Page 68: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 69: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter21ArrayTricks

Alright!WehaveafewmoretricksforArrays!

Wecanaddanewitemwithapushmethod

Solet’ssaywewanttoadd2morenamesforexample…Martha,andGeorge.

names.push(“Martha”,“George”);

document.write(names+“<br/>”);

Let’sseeifwe’vegotit…

yup!

Wecanalsosortitalphabetically…Withasortmethod…

names.sort();

document.write(names+“<br/>”);

Let'ssee…Yup!Sorteditout!!!

Andwecanalso…reverseeverything!

names.reverse();

document.write(names+“<br/>”);

Let’srefreshitandseewhatwegot….Yup!

Stillgotit!

Page 70: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 71: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter22JavascriptonSteroids

Alright,sofar,wehavelearnedlotsofcoolstuff,butrightnow,it’stimetotakeitupanotch.

I’llwritesomeadvancedstuff,sobearwithme,k?

Alright…

Doyouknowallofthosemoviesthatyouhavethevillain,andhetakestheherostarringasTomCruz,andhehaslike…Abomb…Andeveryonewilldieifheisnotgoingtoplacetherightcombinationofpassword…?

Well,todaywewillbethevillainthatgoingtobuildthismachinethatpromptthepassword,andwewillknowifthepasswordisvalidornot!

SoLet’sbuildstuffonHTML…

<divid=”sendItem”>

<form>

Password:<br/>

<br/>

<inputtype=”password”id=”password”

placeholder=”password”/>

<br/>

<inputtype=”button”id=”submit”value=”send!”/>

</form>

</div>

Andlet’sstyleitabit,afterall,it’saspecialoccasion!

<style>

#sendItem{

background-color:red;

width:200px;

margin:30px;

padding:30px;

}

Page 72: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

</style>

Nowwewillhaveafunction,andwewillcallit CheckValidation ,itwill…checkvalidationofthepasswordcombination…Ofcourse…

Insideofourfunction,wewillhaveavariablenamedpassword,anditwilleventuallygetthevalue,oftheinputtypeelementwhohastheidofpassword,let’stypedocument,getElementById,value.

Soinsideofpasswordwestorethevalueoftheinputtag.

Thenwewillhaveanifstatement,checkingratherourcombinationisok,sowewillwritepassword,isnotequalto….Let’ssee…whatcombinationeventhePentagoncan’tcrack???…

Oh!1234.Thatwilldo.

Andwewillhavean alert ,says“Caution!Passwordisincorrect!;

varpassword=document.getElementById(“password”).value;

if(password!=“1234”){

alert(“Caution!PasswordisIncorrect!”);

}else{

//success!

}

Alright,let’splaceourfunctiononthebutton,onclick…

<inputtype=”button”id=”submit”value=”send!”onclick=”CheckValidation()”/>

Andlet’scheckifwetypesomething,it’ssayserror…

Yup!!!

Itdoes!

Cool!

Now…notethatwehavea“send”button…So…wehavetosendourformsomewhere,right?

Letmeaddafewshticksintoourstyletag…

<style>

Page 73: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

#sendItem{

background-color:red;

width:200px;

margin:30px;

padding:30px;

transition:3sall;

left:0;

}

.leftTrans{left:3000px!important;}

</style>

Iaddedanotherclasscalled leftTrans ,andaddafewmoremodificationstoour sendItemid…

Now,afterwewillsucceedourpasswordcombination,theformwillbesenttous,thevillains!

Let’saddintheelsestatement,vary,anditwilltaketheidof sendItem ,sowewillaccesstheelementof sendItem …Andnow,wewilltakevariabley,andaddaclasscalled, leftTrans .

else{

vary=document.getElementById(“sendItem”);

y.className+=“leftTrans”;

}

Andlet’strytofailonlyonce…Wegotourmessage…

Let’stryagainwithourstrongpassword1234….

Ooop!Wesentourform!Whoknowswhere?!Maybetomars.

Page 74: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because
Page 75: JavaScript: JavaScript Awesomeness Book (Awesomeness … Learning, Video Professor, D… · But if you thought “cool” is the only feature of Javascript, then you are wrong, because

Chapter23Nowwhat?

Congratulations!

Youaccomplishedthiscourse,youheardlotsofreallybadjokesinthisbook,

andI’mveryproudofyou!

Youmightaskyourself:

Now,thatI’veaccomplishedmyfirstJavascriptcourse,whatshouldIdonow?HowcanIimprovemywebdevelopingskills?

Well,myyoungpadawan,nowit’stimetocombineyourJavascriptskillswithsomeServerSide.

IdohaveaC#coursejustforyou,andbecauseyoupurchasedthisbook(orincompensationformybadjokes),Iwillgiveyou50%offallofmycoursesinUdemy.

Youcangrabyourcouponhere:http://basicjavascript.gilad.me/discount50/