javascript: the ultimate crash course - programmer books · 2018. 5. 27. · chapter 2: javascript...

31

Upload: others

Post on 07-Mar-2021

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values
Page 2: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

JavaScript:TheUltimateCrashCourseLearningJavaScriptwithinaDaywithNewApproachforFasterProgramming

(SaveTimeandEffort)

By:JMShepal

PublishedByShepalPublishing,AllRightsReserved,

Copyright2016

NewYork

Page 3: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

Introduction

Inthiseraofleadingtechnology,beingabletouseacomputerisessentialforanyonewhowantstoaccomplishsomethingintheirlives.However,simplyputtingacomputeronandsendingemailisnotenough.Thebasiccomputerskillsareinadequateinmostindustries,thereforeonehastopursuemoreskillsandknowledgeintheuseofcomputersinordertobeabletodoalotmore.

It isfor thisreasonthatprogramminglanguagesarebecomingveryimportanteverydayfor people from all walks of life. It would not be a surprise for people to require aqualification or understanding of programming, in all the industries that support theeconomy. That is why a lot of people are looking into more ways to master a fewprogrammingskillsandensuretheyhaveanedgeintheemploymentsector.

Learning programming is known as mastering code. There are range of programminglanguages to learn, though it is important to at least master one language for betteropportunitiesforyouinlife.

JavaScriptisanexceptionalprogramminglanguage;itiseasytomaster,simpleyetverypowerful.Thisisthelanguagethatwillputyouinagoodpositioninanysectorthatyouworkin.Thisprogramminglanguageisgreattouseonyourownpersonalprojects.ThiseBookprovidesyouwithachancetolearnthisamazingprogramminglanguageinjustaday!

Page 4: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values
Page 5: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

Chapter1:JavaScriptBasics

JavaScript is a programming language that is rich and expressive. Itwas established in1991 by SunMicrosystems, from a team thatwasmade of three individualswhowereMikeSheridan,PatrickNaughtonandJamesGosling.ItusedtobecalledOak,andthenitwas calledGreen and in1995, thename Javawasgiven, havingbeingnamedafter thecoffee.ThebasicconceptsofJavaScriptarethemostimportantthingsabeginnerneedstomaster.Youshouldalsoknowsomeofthepitfallsthathavebefallenpeoplewhohavenotusedthisexpressiveprograminglanguagebeforesothatyoucanmasteritwellandstartprogramminglikeanexpert.

JavaScriptisagreatplacetostartlearningaboutprogramming,andwiththisknowledge,youwillfinditeasiertomasterdifferentprogramminglanguages.Tobeginwith,wewillexplorethemeaningofSyntax.Herearesomesyntaxbasicsthatshouldgetyoustarted:

SyntaxBasicsJavaScript syntax refers toa setof rules thatdefinea JavaScriptprogram thathasbeenwellstructured.SomeoftheimportantsyntaxthatyouneedtolearnasyougetstartedinJavaScript programming include statements, variable naming, and white space amongothers. First of all, you need to know what a computer program. At its most basic, acomputerprogramisthelistofinstructionsthattellacomputerwhatitmustexecute.Inaprogramminglanguagetheseprograminstructionsarewhatwewillcallstatements.

Casesensitivity:JavaScript isacasesensitiveprogramminglanguage.Youwillhave tostart the name of a constructorwith a capital letter then the name of a functionwith alower-case letter.This is important to remember as someother programming languagesarenotcasesensitive,meaningthatyouhaveadifferentexperienceusingthem.

Whitespace:Thesearethespaces,thetabsandthenewlinesthatareusedoutsideofstringconstants.Stringconstantscanbeidentifiedassomelettersandsymbolsthatareusedtocreate code in JavaScript programming language. Whitespace in JavaScript is verysignificant and it can directly impact semantics,which is not the casewith some otherprogramminglanguageslikeC.

Semicolon: Statements in JavaScript are usually separated by semicolons. There is atechnique in JavaScript called Automatic Semicolon Insertion. This means that somestatements thathavebeenwellformedafteranewlinehasbeenparsedwillbetakenascomplete,justthesamewaytheywouldbeconsideredifthesemicolonwereinsertedjustbefore the newline. You can opt for statements that terminate semicolons explicitly inordertoreducetheunintendedeffectsoftheautomaticsemicoloninsertion.

Page 6: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

Hereisanexampleofthesemicolonuse:

vara=8;

varb=9;

varc=a+b;

JavaScriptStatements

In JavaScript, statements have several components which include: Values, Operators,Expressions,Keywords,andComments.

Values: in JavaScript syntax, youwill get toknowabout two typesof values: the fixedvalues and the variable values. The fixed values are called the literals and the variablevaluesarewhatwecallvariables.

ThemostimportantrulesforwritingJavaScriptfixedvalues/literalsare:

-Numberscanbewrittenwithorwithoutdecimals.Example:

10.50

1001

- Strings are a text and they are written within double or a single quote.Example:

“AlphaDelta”

‘AlphaDelta’

JavaScript variables on the other hand, are used to store data values, just like in otherprogramminglanguages.Thevarkeywordwill thereforebeused todeclarevariables intheprogramming.Anequalsignwillbeused toassignavalue toavariable.Here isanexample:

vara;

a=8;

Hereisanexampleofasimplevariabledeclaration:

varfoo=‘helloworld’;

The whitespace does not have significant meaning outside the quotation marks asillustrated:

varfoo=‘helloworld’;

Theparenthesiswillindicateprecedenceasshown:

3*2+6;//returns12;asfirstyouhavemultiplication

3*(5+3);//returns24;asfirstyouhaveaddition

Page 7: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

Tabswillhavenomeaningatallbuttheywillenhancereadability:

varfoo=function(){

console.log(‘hello’);

};

JavaScriptexpressions

AnexpressioninJavaScriptwillbeusedtorefertothecombinationofvalues,variablesandoperators,allofwhichwillcomputetoacertainvalue.Theendcomputationwillbecalledanevaluation.Hereisanexampleofasimpleexpression:

2*10evaluatesto20:

2*10

Expressionsdocontainvariablevaluesaswell,a*10.

Thevaluesusedinsuchexpressionscanbeofvarioustypeslikesaynumbersandstrings.“Alpha”+””+“Delta”,evaluatesto“AlphaDelta”:canbeillustratedas:

“Alpha”+””+“Delta”

JavaScriptkeywords

Theseareusedtoidentifytheactionsthataretobeperformed.Thevariablekeywordwillbeusedtotellthebrowsertocreateanewvariable.Example:

vara=8+9;

varb=a*10;

Comments

Firstofall,youneedtorealizethatnotallJavaScriptstatementsendupbeingexecuted.Thecodethatappearsafterdoubleslashes//orinbetween/*and*/willbetreatedasacomment.Thecommentsaresupposedtobeignored,nottobeexecuted.Example:

vara=8;//Iwillbeexecuted

//vara=9;IwillNOTbeexecuted

Identifiers

Identifiers are basically names. In JavaScript, they will be used to name variables,keywords, functions and labels.Legal namesbehave the same and the rules remain thesame in all programming languages. In JavaScript, the very first character has to be a

Page 8: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

letter, an underscore (_), or a dollar sign ($). The characters that will follow can beanythingbetween letters, digits, underscores, ordollar signs.Note that numbers arenotallowedas firstcharacters.Thismakes iteasy forone todistinguishbetween identifiersandnumberswitheaseinJavaScript.

Page 9: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values
Page 10: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

Chapter2:JavaScriptBasicOperators

JavaScriptbasicoperatorsareused tomanipulatedifferentvalues inyourprogramming.JavaScript uses an assignment operator, an equal sign in order to assign values to avariable.Anillustrationisasbelow:

vara=8;

varb=9;

Arithmeticoperatorson theotherhandareused tocomputevalues.Thesearegiven thesigns+-*/.Belowisanexample:

(8+9)*17

Theseincludesdivisionandmultiplication,forexample:

5*6;

5/6;

Anddecrementingandincrementing:

varx=6;

vary=++x;//pre-increment:yequals5;xequals6

varz=x++;//post-increment:zequals5;xequals6

Concatenationwillalsobeuseful.Hereisanexample:

varfoo=‘hello’;

varbar=‘world’;

console.log(foo+‘‘+bar);//‘helloworld’

NumbersandStringsOperations

In JavaScript, the behavior of strings andnumbers is oftenvery differentmannerwhencomparedtohowtheybehavewithotherprogramminglanguages.Itisthereforeimportantto understand each step carefully to be able to operate themwith ease when you startprogramming:

Additionvs.concatenation

Hereisanexampleofhowadditionsandconcatenationshappenonnumbersandstrings:

varfoo=5;

varbar=‘6’;

console.log(foo+bar);//56.uhoh

Howtoforceastringtobehavelikenumbers:

Page 11: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

varfoo=5;

varbar=‘6’;

//coercestringstowardsanumber

console.log(foo+Number(bar));

Whenanumberconstructorisidentifiedasafunctionasitisillustratedabove,itwillhavetheability tocast itsargument tonumerical form.Theunaryplusoperatorcarriesoutasimilarfunction,thereforeitcanalsobeused.Hereisanillustration:

console.log(foo++bar);

Logicaloperators

The logical operators in JavaScriptmake it possible to gauge a sequence of operationsusingANDaswellasORoperations.Lookattheillustrationbelow:

varfoo=5;

varbar=0;

varbaz=6;

foo||bar;//takesback5,thatistrue

bar||foo;//takesback5,thatistrue

foo&&bar;//takesback0,thatisfalse

foo&&baz;//takesback6,thatistrue

baz&&foo;//takesback5,thatistrue

Fromtheillustrationabove:

-Theoperator//bringsbackthevalueoftheinitialoperation.Shoulditoccurthatnoneoftheoperationsistrue,thelastofthetwooperationswillbereturned.

-The&&operatorbringsthevalueoftheprimaryfalseoperationorthatofthefinaloperationifbothoftheoperationsweretrue.

Sometimes logicaloperationsareused for the flowcontrol rather thanmakinguseof ifstatementsbysomedevelopers.Seetheexamplebelow:

//doathingwithfooiffooistrue

foo&&dosomething(foo);

//setbartobaxifbaxistrue;

//orelse,setittothetakeback

Page 12: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

//valueof==forcreateBar()

varbar=bax||createBar();

Theaboveisadifferentkindofstyle,thatiselegantandquitepleasantbutitisnoteasytoread, particularly for those without experience. Only after advancing the skills inJavaScriptcanabeginnerbeabletoreadthat.

Note:youneedtoknowwhichkindsofvaluesaretruthandwhichonesarefalsesoastouseflowcontroleffectivelyallthetime.Therearetimeswhenvaluesthatlookliketheyshouldevaluateinonewayevaluateinadifferentwayinstead.Valuesthatevaluatetotrueareillustratedas:

‘0’;

‘anystring’;

[];//anemptyarray

{};//anemptyobject

1;//anynon-zeronumber

Andthosethatevaluatetothefalseareillustratedas:

0;

”;//anemptystring

NaN;//JavaScript’s“not-a-number”variable

null;

undefined;//becareful—undefinedcanberedefined!

Theconditionalcode

This isonlyapplicablewhenyouwant to runa largeamountofcodeas longascertainconditionsapply.Here,youwilluseFlowcontrol throughifandelseblocks.Here isanexampleinaflowcontrol:

varfoo=right;

varbar=wrong;

if(bar){

//thiscodeshallneverrun

console.log(‘hello!’);

Page 13: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

}

if(bar){

//thiscodeshan’trun

}or{

if(foo){

//thiscodewillrun

}else{

//thiscodewouldruniffooandbarwerebothwrong

}

}

Alwaysrememberthatuseofcurlybraceswillhelpyouinthecreationofmorereadablecodes, evenwhen they are not really necessary with single-line if statements. You canthereforeusethemasmuchasyouwantforbetterresults.Also,avoiddefiningfunctionsusingtheanamewhichisthesamemanytimeswithindifferentif/elseblocks.Thismaypreventyoufromachievingthedesiredresults.

Page 14: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values
Page 15: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values
Page 16: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

Chapter3:JavaScriptLoops

LoopsinJavaScript’senableaprogrammertoquicklyandeasilydosomethingrepeatedly.Aloop isbasicallyacomputerizedversionofhaving todosomethingseveral timesandanother thingseveralmore times.Ifyouwant to takeeightsteps to theeast, thiscanbeexpressedasbelowinJavaScript:

varstep;

for(step=0;step<8;step++){

//Runs8times,withvaluesofstep0through7.

console.log(‘Walkingeastonestep’);

}

Youwilllearnaboutseveralkindsofloopsinthisprogramminglanguage,butonethingforsureisthattheyalldothesamething,whichisrepeatingthesameactionanumberoftimes. The number of times can be zero.What the different types of loopmechanismsofferaredifferentwaystodeterminethestartpointandtheendpointsoftheloop.Therearevarioussituationsthatwillbemoreeasilyservedbyonetypeofloopcomparedtotheothers.

JavaScriptprovidesavarietystatementsthatwillbeusedforloops/.Theseare:

1. Forstatement:

This statement will repeat until a specified condition evaluates to a false. Here is an -examplestatement:

for([initialExpression];[condition];[incrementExpression])

statement

Theresultsofaforloopexecutionare:

Theinitializingexpression,ifany,willbeexecuted.

The condition expressionwill be evaluated. If the value of condition is true, theloopstatementwillexecute it. If thevalueofcondition is false, the for loopwillterminateit.Iftheconditionexpressionistotallyomitted,theconditionwillthenbeassumedtobetrue.

The statement executes. If youwant to executemultiple statements, use a blockstatement({…})inordertogroupthosestatements.

Theupdateexpression,whichisincrementExpression,willexecuteifit ispresentthenthecontrolreturnstostep2.

2. Thedo…whilestatement

Thiskindof statementwill repeatuntil a specifiedconditionevaluates to false. This is

Page 17: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

howitlooks:

do

statement

while(condition);

your statements will be executed once before the condition is checked. If youwant toexecutemorethanonestatements,youuseablockstatement({…})soastogroupthosestatements. If the conditions turns out to be true, the statementwill execute again.Thecondition shouldbe checked after every execution. If you find it false, the execution isstoppedandtotalcontrolisnowpassedontothestatementthatfollowsdo…while.Hereisanexample:

do{

i+=1;

console.log(i);

}while(i<5);

3. Thewhilestatement

This statementwill execute its statements as long as a specified condition evaluates totrue.Thisishowawhilestatementwilllooklike:

while(condition)

statement

If the condition evaluates to false, the statement in that loop stops executing and thecontrolnowispassedtothestatementthatfollowstheloop.

Youhavetotesttheconditionbeforethestatementintheloopisexecuted.Iftheresultsaretrue,thestatementisexecutedandtheconditionistestedoncemore.Thisisdoneuntiltheconditionreturnsfalse.

Inordertoexecutemultiplestatements,useablockstatement({…})soastogroupthosestatements.Example:

n=0;

x=0;

while(n<3){

n++;

x+=n;

}

4. Thelabelstatement

Page 18: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

This statement will provide a statement with an identifier that will let you refer to itelsewhere inyourprogram.Youcanuse the label statement inorder to identifya loop,thenusethebreakorthecontinuestatementsinordertoindicatewhetheraprogramwillinterruptthelooporitwillcontinueitsexecution.Thissohowthelabelstatementlookslike:

label:

statement

WherethevalueofthelabelcanbeanyJavaScriptidentifierthatisnotentirelyareservedwordand the statement thatyou identifywith the label statementcanbeanystatement.HereisanexampleofalabelmarkLoopidentifyingawhileloop:

markLoop:

while(theMark==true){

doSomething();

}

5. Breakstatement

The break statement is used to terminate a loop, switch or in conjunctionwith a labelstatement.When it is used without the label, it will terminate the innermost enclosingwhile,do..while,for,orswitchimmediately,thentransferthecontroltothestatementthatfollows.Whenbreakisusedwithlabelontheotherhand,itwill terminatethespecifiedlabeledstatement.Thisishowthebreakstatementlookslike:

break;

breaklabel;

Wherethefirstformofthesyntaxterminatestheinnermostenclosinglooporswitch,thesecondformofthesyntaxterminatesthespecifiedenclosinglabelstatement.Example:

for(i=0;i<a.length;i++){

if(a[i]==theValue){

break;

}

}

6. Continuestatement

Thisisthestatementthatwillbeusedtorestartawhile,do..while,fororlabelstatements.When the statement isusedwithouta label, itwill terminate thecurrent iterationof theinnermost enclosing while, do-while, or for statement and continue executing the loopwiththenextiteration.Thiscontraststheworkingofthebreakstatementinthatcontinuedoesnotterminatetheexecutionoftheloopentirely.Whenusedinawhileloop,itjumpsbacktotheconditionandinaforloop,itjumpstotheincrement-expression.Thisishow

Page 19: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

itssyntaxlookslike:

continue;

continuelabel;

Hereisanexampleofawhileloopwithacontinuestatementthatexecuteswhenthevalueofiisthree.Intheexample,ntakesonthevaluesone,three,seven,andtwelve:

i=0;

n=0;

while(i<5){

i++;

if(i==3){

continue;

}

n+=i;

}

7. for…instatement

Thisstatementiteratesaspecificvariableoveralltheenumerablepropertiesofanobject.Itssyntaxisasbelow:

for(variableinobject){

statements

}

8. for…ofstatement

This is the statement that will create a loop that will Iterate over objects that can beiterated for instance Array, Map, Set, arguments object among many. It will invoke acustomiterationhookwithstatementsthataretobeexecutedforthevalueofeachdistinctproperty.Itssyntaxwilllooklike:

for(variableofobject){

statement

}

Page 20: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values
Page 21: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values
Page 22: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

Chapter4:JavaScriptFunctionsandScope

Functions in JavaScript contain blocks of codewhich needs to be executed repeatedly.Functionsherecantakezeroormorearguments,andtheycanreturnavalueiftheyoptto.ThereismorethanonewayinwhichyoucancreatefunctionsinJavaScript:

-Functiondeclaration:functionfoo(){/*dosomething*/}

-Anamedfunctionexpression:varfoo=function(){/*dosomething*/}

Hereareexamplesofdifferenttypesoffunctions:

i)Asimplefunctionwillbeillustratedas:

vargreet=function(person,greeting){

vartext=greeting+‘,‘+person;

console.log(text);

};

greet(‘Rebecca’,‘Hello’);

ii)Afunctionthatreturnsavaluewillbeillustratedas:

vargreet=function(person,greeting){

vartext=greeting+‘,‘+person;

returntext;

};

console.log(greet(‘Richard’,‘hello’));

iii)Afunctionthatreturnsanotherfunctionwillbeillustratedas:

vargreet=function(person,greeting){

vartext=greeting+‘,‘+person;

returnfunction(){console.log(text);};

};

vargreeting=greet(‘Richard’,‘Hello’);

greeting();

Page 23: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

TheSelf-ExecutingAnonymousFunctions

ThisisacommonpatterninJavaScript today.Thepatterncreatesafunctionexpression,thenimmediatelyexecutesthefunction.Thisisapatternthatwillbeveryusefulifyoudonot want to create a mess in the global namespace with your code. Note that all thevariablesthatwillbedeclaredinsideofthefunctionwillbevisibleontheoutside.Thisishowtheself-executinganonymousfunctionwilllooklike:

(function(){

varfoo=‘Helloworld’;

})();

console.log(foo);//undefined!

JavaScriptfunctionsasarguments

FunctionsareveryimportantinJavaScript;theyaretreatedasfirst-classcitizensandthismeansthattheycanbeassignedtovariableswitheaseortheycanbepassedovertotheother functions as arguments. The syntax for passing an anonymous function as anargumentwillbe:

varmyFn=function(fn){

varresult=fn();

console.log(result);

};

myFn(function(){return‘helloworld’;});//logs‘helloworld’

whilethesyntaxforpassinganamedfunctionasanargumentwillbe:

varmyFn=function(fn){

varresult=fn();

console.log(result);

};

varmyOtherFn=function(){

return‘helloworld’;

};

myFn(myOtherFn);//logs‘helloworld’

Testing

There is awayonecan test the typeofvariable in JavaScript.This is shownbyuseoftypeofoperatorinordertodeterminethetypeofaspecificvalue.Belowisanillustration

Page 24: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

ofhowonecantestthetypeofvariousvariablesinprogramming:

varmyFunction=function(){

console.log(‘hello’);

};

varmyObject={

foo:‘bar’

};

varmyArray=[‘a’,‘b’,‘c’];

varmyString=‘hello’;

varmyNumber=3;

typeofmyFunction;//takesback‘function’

typeofmyObject;//takesback‘object’

typeofmyArray;//takesback‘object’—careful!

typeofmyString;//takesback‘string’;

typeofmyNumber;//takesback‘number’

typeofnull;//takesback‘object’—careful!

if(myArray.push&&myArray.slice&&myArray.join){

//probablyanarray

//(thisiscalled“ducktyping”)

}

if(Object.prototype.toString.call(myArray)===‘[objectArray]’){

//Definitelyanarray!

Page 25: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

//Thisiswidelyconsideredasthemostrobustway

//todetermineifaspecificvalueisanArray.

Scope

Scopeisbasicallyavariablethatisavailableinacertaincodeatagiventime.Ifyouareunabletounderstandscope,youwillhaveconstantissueswithdebugging,thereforethisisvery important.Whenyoudeclareavariable insideafunctionusing thevarkeyword, itwillonlybeavailabletothecodeinsideofthatfunctionandthecodeoutsidethefunctionwillnotbeabletoaccessthevariable.Again,functionsthathavebeendefinedinsidethatfunctionwillbeabletoaccessthedeclaredvariable.

Thosevariables thatwill bedeclared inside a functionwithout thevarkeyword arenotlocaltothefunctionasthismeansthatJavaScriptwillgobackthescopechainuptothewindowscope inorder to find thepointwhere thevariablewasdefinedat first. If therewasnodeclarationatthebeginning,thevariablewillthenbedeclaredintheglobalscope,andthiscanhavegreatexpectedconsequences.

The example below shows functions that have access to variables defined in the samescope:

varfoo=‘hello’;

varsayHello=function(){

console.log(foo);

};

sayHello();//logs‘hello’

console.log(foo);//alsologs‘hello’

Thisexampleshowsthatacodeoutside thescope inwhichavariablewasdefineddoesnothaveaccesstothevariable

varsayHello=function(){

varfoo=‘hello’;

console.log(foo);

};

sayHello();//logs‘hello’

console.log(foo);//doesn’tloganything

Page 26: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values
Page 27: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values
Page 28: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

Chapter5:JavaScriptFeatures

JavaScript is a very powerful programming language. It is quite popular as a clientscripting language for differentwebbrowsers. It canbeused in anyweb application inordertoimplementsimplebutveryimportantfeatures,rollerofimages.Ithasbeenusedformanyyearsnowtoaddbeautifuleffectstowebpagesbecauseofitspowerfulfeatures,and this issomething thatmakes itoneof thebestprogramminglanguages in theentireworldtoday.Herearesomeofthebestfeaturesthatshouldpromptyoutolearnthisgreatprogramminglanguage:

JavaScript’sbrowsersupport

With JavaScript, one does not need to install flash plugin in their browser, like it isrequiredwhenonewants toaccessany flashcontent.This isbecauseallbrowsershavefully accepted JavaScript as their main scripting language, therefore they provide anintegratedsupportforit.WhataprogrammerwouldhavetodoisjusttohandlesomeofthetasksthatdependonDOMofdifferentbrowsersproperlyandyouwillbefreetouseJavaScriptonyourbrowser.

JavaScriptasafunctionalprogramminglanguage

Programmers using JavaScript are at liberty to code in a functional programming style,which is easy andmore exciting than any other style. This is because of a number ofreasons.AfunctioninJavaScriptcanbeassignedtovariables, just thesamewayasanyothertypeofdata.Afunctioncanalsoacceptanotherfunctionasitsparameter.Itcanalsoreturnafunction.Youcanalsohavefunctionsthatdonothaveanynamesaswell.Thisistheabilitythatmanyprogrammerswouldlovetoenjoyastheywork.

JavaScriptcanbeusedonboththeclientandontheserverside

JavaScript has access to the document model object of any browser therefore one caneasily change the structure of web pages at runtime. This is what gives users of theprogramminglanguagemorecontrolovertheirbrowsers.Youcanusethelanguagetoadddifferenteffectstowebpages.Theprogramminglanguagecanalsobeusedontheserversideaswell,forinstanceitisusedinAlfrescotocreatewebscripts.ThisiswhatmakesitveryeasyforaprogrammertoaddcustomtaskstoAlfresco.

Itsabilitytodetecttheuser’sbrowserandOS

This is something thatwillhelpaprogrammer tobeable toperformoperations thataredependentontheplatformwhenitisrequired.

Theability todetect theuser’sbrowserandOSallowsyour script toperformplatform-

Page 29: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

dependentoperations,ifnecessary.

JavaScript’ssupportforobjects

JavaScriptisaprograminglanguagethatisorientedbyobjectsbutithandlesobjectsandinheritanceinamuchdifferentwaywhencomparedtohowotherprogramminglanguagesthat are object oriented do. What it does is that it offers immense support to objectoriented concepts but then it remains simple to learn and use. That is why thisprogramming language can be used to execute both the simple tasks and the complextasks.Thisisalsowhathasenablesit tostaytopinthelistasoneofthemostpreferredprogramming languages in the industry today. It is now the best language to learn forpeoplewhoareinterestedincomputerprogrammingduetoitssupportforobjectorientedconceptsandfunctionconcepts.Itisalsoeasytouseandyouonlyneedabrowserandatexteditortoenjoywhatithastooffer.

Page 30: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values
Page 31: JavaScript: The Ultimate Crash Course - Programmer Books · 2018. 5. 27. · Chapter 2: JavaScript Basic Operators JavaScript basic operators are used to manipulate different values

Conclusion

Many people believe that one has to actually go back to school in order to learn aprogramminglanguageandothercomputerskills,but this isnot trueatall.The internethasbroughta lotofpossibilities inour livesandsomuchinformation isout there.ThiseBookcangetyoustartedinJavaScriptwithoutnecessarilyattendingclasses,andyoucanlearnsomuchmorewithtimetoprogramlikeanexpert.

Otherpeoplebelievethatprogramminglanguagesaremeantforcertainkindsofpeople,which isalsoamyth.JavaScript isaprogramming language thatcanbe learnedbyanykind of person, for any reason at all.You do not have to be amathematic genius or asciencegurutobeabletoprogramlikeanexpert.This issomethingthatanyonecandowithsomuchease.Likeyouhavealreadyseen,itisaveryeasyprogramminglanguagetolearn,whichopensopportunitiesforallkindsofpeople.

Aneffectiveway to learnprogramming language is to learn thebasics, thenpracticeasmuchasyoucan.Practice iswhatmakesoneaproandcodinggetsbetterwitha lotofpractice.Youhavetodedicateaconsiderableamountoftimetoitaswell,fortheskillstobe well mastered. Check out what other people are doing and try new ways ofprogrammingandseehowmuchyouwillhaveachievedinashortperiodoftime.