Sunteți pe pagina 1din 22

Arrays

Accessingarrayelements
Youcangetelementsoutofarraysifyouknowtheirindex.Arrayelements'indexesstartat0
andincrementby1,sothefirstelement'sindexis0,thesecondelement'sindexis1,thethird
element'sis2,etc.
Syntax
array[index]
Example
varprimes=[2,3,5,7,11,13,17,19,23,29,31,37]
primes[0]//2
primes[3]//7
primes[150]//undefined

Arrayliterals
Youcancreatearraysintwodifferentways.Themostcommonofwhichistolistvaluesina
pairofsquarebrackets.JavaScriptarrayscancontainanytypesofvaluesandtheycanbeof
mixedtypes.
Syntax
vararrayName=[element0,element1,...,elementN]
Example
varprimes=[2,3,5,7,11,13,17,19,23,29,31,37]
Readmore
https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Array
http://www.javascripter.net/faq/creatingarrays.htm

MultidimensionalArrays
Atwodimensionalarrayisanarraywithinanarray.Ifyoufillthisarraywithanotherarrayyou
getathreedimensionalarrayandsoon.
Example
varmultidimensionalArray=[[1,2,3],[4,5,6],[7,8,9]]//twodimensions,3x3

Arrayconstructor
YoucanalsocreateanarrayusingtheArrayconstructor.
Example
varstuff=newArray()
stuff[0]=34
stuff[4]=20
stuff//[34,undefined,undefined,undefined,20]
Example
varmyArray=newArray(45,"HelloWorld!",true,3.2,undefined)
console.log(myArray)
//output:[45,'HelloWorld!',true,3.2,undefined]
Readmore
https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Global_Objects/Array#Example.3A_Creating_an_arra
y

Accessingnestedarrayelements
Accessingmultidimensionalarrayelementsisquitesimilartoonedimensionarrays.Theyare
accessedbyusing[index][index].....(numberofthemdependsuponthenumberofarraysdeep
youwanttogoinside).
Syntax
array[index][index]....
Example
varmyMultiArray=[
[1,2,3,4,5,[1,2,3,4,5]],
[6,7,8,9,10,[1,2,3,4,6]],
[11,12,13,14,15,[1,2,3,4,5]],
[16,17,18,19,20,[1,2,3,4,5]]
]
console.log(myMultiArray[1][5][4])//Outputs6,thevalueinthelastelementofthelastelementofth
esecondelementofmyMultiArray.

Booleans

Booleanliterals
Syntax
true
false

Booleanlogicaloperators
Syntax
expression1&&expression2//returnstrueifboththeexpressionsevaluatetotrue
expression3||expression4//returntrueifeitheroneoftheexpressionevaluatestotrue
!expression5//returnstheoppositebooleanvalueoftheexpression
Example
if(true&&false)alert("Notexecuted!")
//becausethesecondexpressionisfalse
if(false||true)alert("Executed!")
//becauseanyoneoftheexpressionistrue
if(!false)alert("Executed!")
//because!falseevaluatestotrue
!!true//remainstrue
Example
if(!false&&(false||(false&&true)))alert("Guesswhat...")
/*notexecutedbecause
!false&&(false||(false&&true))becomes
!false&&(false||false)becomes
true&&false,whichisfalse.*/
Example
/*AnimportantthingtonotehereistheOperatorPrecedencewhichdeterminestheorderinwhichoper
atorsareevaluated.Operatorswithhigherprecedenceareevaluatedfirst.Thusamongthefour(),&&,
||,!*/
//Bracketshavethehighestprecedence
//!lowerthanBrackets
//&&lowerthan!
//||thelowest
if(true&&!!false||true)alert("Guessagain??")

/*Executed,hereistheevaluationprocess
true&&!!false||truebecomes
true&&false||true(nobracketspresent,so!evaluated)becomes
false||true(then&&evaluated)whichbecomestrue*/
Example
/*NextimportantthingistheAssociativitywhichdeterminestheorderinwhichoperatorsofthesame
precedenceareprocessed.Forexample,consideranexpression:a*b*c.Leftassociativity(lefttoright
)meansthatitisprocessedas(a*b)*c,whilerightassociativity(righttoleft)meansitisinterpretedas
a*(b*c).*/
//Brackets,&&,||havelefttorightassociativity
//!hasrighttoleftassociativity
//So,
!false&&!!false//false
//evaluatedinthemanner!false&&falsetrue&&falsefalse

Comparisonoperators
Syntax
x===y//returnstrueiftwothingsareequal
x!==y//returnstrueiftwothingsarenotequal
x<=y//returnstrueifxislessthanorequaltoy
x>=y//returnstrueifxisgreaterthanorequaltoy
x<y//returnstrueifxislessthany
x>y//returnstrueifxisgreaterthany

"Truthy"and"Falsey"
OnlyBooleanliterals(trueandfalse)asserttruthorfalse,buttherearesomeotherwaystooto
derivetrueorfalse.Havealookattheexamples.
Example
if(1)console.log("True!")//outputTrue!,sinceanynonzeronumberisconsideredtobetrue
if(0)console.log("Idoubtifthisgetsexecuted")//notexecuted,since0isconsideredtobefalse
if("Hello")alert("So,anynonemptyStringisalsotrue.")//Getsexecuted
if("")alert("Hence,anemptyStringisfalse")//Notexecuted
Readmore
http://www.sitepoint.com/javascripttruthyfalsy/

== vs. ===
Asimpleexplanationwouldbethat==doesjustvaluechecking(notypechecking),whereas,

===doesbothvaluecheckingandtypechecking.Seeingtheexamplesmaymakeitallclear.
Itisalwaysadvisablethatyouneveruse==,because==oftenproducesunwantedresults
Syntax
expression==expression
expression===expression
Example
'1'==1//true(samevalue)
'1'===1//false(notthesametype)
true==1//true(because1standsfortrue,thoughit'snotthesametype)
true===1//false(notthesametype)

CodeComments
Code comments are used for increasing the readability of the code.If you write 100 lines of
codeandthenforgetwhateachfunctiondid,it'snotusefulatall.Commentsarelikenotes,
suggestions,warnings,etc.thatyoucanputforyourself.Codecommentsarenotexecuted

SingleLineComment
Anythingonthelinefollowing // willbeacommentwhileanythingbeforewillstillbecode.
Syntax
console.log("Thiscodewillberun")
//console.log("Becausethislineisinacomment,thiscodewillnotberun.")
//Thisisasinglelinecomment.

MultiLineComment
Anythingbetween /* and */ willbeacomment.
Syntax
/*Thisis
amultiline
comment!
*/
Example
/*
alert("Hello,Iwon'tbeexecuted.")

console.log("Hello,Ialsowillnotbeexecuted")
*/

Console
console.log
Printstexttotheconsole.Usefulfordebugging.
Example
varname="Codecademy"
console.log(name)

console.time
This function starts a timer which is useful for tracking how long an operation takes to
happen.Yougiveeachtimerauniquename,andmayhaveupto10,000timersrunningona
givenpage.Whenyoucall console.timeEnd() withthesamename,thebrowserwilloutputthe
time,inmilliseconds,thatelapsedsincethetimerwasstarted.
Syntax
console.time(timerName)
Example
console.time("MyMath")
varx=5+5
console.log(x)
console.timeEnd("MyMath")
console.log("Donethemath.")
/*Output:
10
MyMath:(timetaken)
Donethemath.
*/
Readmore
https://developer.mozilla.org/enUS/docs/Web/API/console.time
https://developer.mozilla.org/enUS/docs/Web/API/console.timeEnd

console.timeEnd
Stopsatimerthatwaspreviouslystartedbycalling console.time() .

Syntax
console.timeEnd(timerName)
Example
console.time("MyMath")
varx=5+5
console.log(x)
console.timeEnd("MyMath")
/*Output:
10
MyMath:(timetaken)
*/
Readmore
https://developer.mozilla.org/enUS/docs/Web/API/console.timeEnd

Functions
AfunctionisaJavaScriptprocedureasetofstatementsthatperformsataskorcalculatesa
value.Itislikeareusablepieceofcode.Imagine,having20forloops,andthenhavingasingle
function to handle it all . To use a function, you must define it somewhere in the scope from
whichyouwishtocallit.Afunctiondefinition(alsocalledafunctiondeclaration)consistsofthe
function keyword, followed by the name of the function, a list of arguments to the function,
enclosedinparenthesesandseparatedbycommas,theJavaScriptstatementsthatdefinethe
function,enclosedincurlybraces, {} .
Syntax
functionname(argument1,argument2....argumentN){
statement1
statement2
..
..
statementN
}
Example
functiongreet(name){
return"Hello"+name+"!"
}
Readmore
https://developer.mozilla.org/enUS/docs/Web/JavaScript/Guide/Functions

Functioncalling
Syntax
functionName(argument1,argument2,...,argumentN)
Example
greet("Anonymous")
//HelloAnonymous!

Functionhoisting
The two ways of declaring functions produce different results. Declaring a function one way
"hoists"ittothetopofthecall,andmakesitavailablebeforeit'sactuallydefined.
Example
hoistedFunction()//Hello!Iamdefinedimmediately!
notHoistedFunction()//ReferenceError:notHoistedFunctionisnotdefined
functionhoistedFunction(){
console.log('Hello!Iamdefinedimmediately!')
}
varnotHoistedFunction=function(){
console.log('Iamnotdefinedimmediately.')
}
Readmore
http://jamesallardice.com/explainingfunctionandvariablehoistinginjavascript/

Ifstatement
It simply states that if this condition is true, do this, else do something else (or nothing). It
occursinvariedforms.

if
Syntax
//Form:SingleIf
if(condition){
//codethatrunsiftheconditionistrue
}

Example
if(answer===42){
console.log('Toldyouso!')
}

else
Afallbacktoan if statement.Thiswillonlygetexecutedifthepreviousstatementdidnot.
Syntax
//Iftheconditionistrue,statement1willbeexecuted.
//Otherwise,statement2willbeexecuted.
if(condition){
//statement1:codethatrunsifconditionistrue
}else{
//statement2:codethatrunsifconditionisfalse
}
Example
if(gender=="male"){
console.log("Hello,sir!")
}else{
console.log("Hello,ma'am!")
}

elseif
Thisislikean else statement,butwithitsowncondition.Itwillonlyrunifitsconditionistrue,
andthepreviousstatement'sconditionwasfalse.
Syntax
//Form:elseif.Iftheconditionistrue,statement1willbeexecuted.Otherwise,condition2ischecked.i
fitistrue,thenstatement2isexecuted.Else,ifnothingistrue,statement3isexecuted.
if(condition1){
statement1
}elseif(condition2){
statement2
}else{
statement3
}
Example
if(someNumber>10){
console.log("Numberslargerthan10arenotallowed.")
}elseif(someNumber<0){

console.log("Negativenumbersarenotallowed.")
}else{
console.log("Nicenumber!")
}

Loops
ForLoops
Youuse for loops,ifyouknowhowoftenyou'llloop.ThemostoftenusedvarNameinloops
is i .
Syntax
for([vari=startValue][i<endValue][i+=stepValue]){
//Yourcodehere
}
Example
for(vari=0i<5i++){
console.log(i)//Printsthenumbersfrom0to4
}
Example
vari//"outsourcing"thedefinition
for(i=10i>=1i){
console.log(i)//Printsthenumbersfrom10to1
}
Example
/*Notethatallofthethreestatementsareoptional,i.e.,*/
vari=9
for(){
if(i===0)break
console.log(i)
i
}
//Thisloopisperfectlyvalid.

WhileLoops
Youuse while loops,ifyoudon'tknowhowoftenyou'llloop.
Syntax
while(condition){

//Yourcodehere
}
Example
varx=0
while(x<5){
console.log(x)//Printsnumbersfrom0to4
x++
}
Example
varx=10
while(x<=5){
console.log(x)//Won'tbeexecuted
x++
}
Readmore
https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Statements/while

DoWhileLoops
Youusedowhileloops,ifyouhavetoloopatleastonce,butifyoudon'tknowhowoften.
Syntax
do{
//Yourcodehere
}while(condition)
Example
varx=0
do{
console.log(x)//Printsnumbersfrom0to4
x++
}while(x<5)
Example
varx=10
do{
console.log(x)//Prints10
x++
}while(x<=5)
Readmore
https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Statements/do...while

Math
random
Returnsarandomnumberbetween0and1.
Syntax
Math.random()
Example
Math.random()//Arandomnumberbetween0and1.

floor
Returnsthelargestintegerlessthanorequaltoanumber.
Syntax
Math.floor(expression)
Example
Math.floor(9.99)//9
Math.floor(1+0.5)//1
Math.floor(Math.random()*X+1)//Returnsarandomnumberbetween1andX

pow
Returnsbaseraisedtoexponent.
Syntax
Math.pow(base,exponent)
Example
Math.pow(2,4)//gives16
Readmore
https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Global_Objects/Math/pows

ceil
Returnsthesmallestintegergreaterthanorequaltoanumber.

Syntax
Math.ceil(expression)
Example
Math.ceil(45.4)//46
Math.ceil(41.9)//3
Readmore
https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil

PI
Returns the ratio of the circumference of a circle to its diameter, approximately 3.14159 or in
better terms, the value of PI (). Note in syntax , we do not put () at the end
of Math.PI because Math.PI isnotafunction.
Syntax
Math.PI
Example
Math.round(Math.PI)//roundsthevalueofPI,gives3
Math.ceil(Math.PI)//4
Readmore
https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI

sqrt
Returnsthesquarerootofanumber.
Syntax
Math.sqrt(expression)
Example
Math.sqrt(5+4)//3
Math.sqrt(Math.sqrt(122+22)+Math.sqrt(16))//4
Readmore
https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt

Numbers
% (Modulus)
Itreturnstheremainderleftafterdividingthelefthandsidewiththerighthandside.
Syntax
number1%number2
Example
14%9//returns5

isNaN
Returnstrueifthegivennumberisnotanumber,elsereturnsfalse.
Syntax
isNaN([value])
Example
varuser_input=prompt("Enteranumber")//Enter"anumber"
if(isNaN(user_input))
alert("Itoldyoutoenteranumber.")
//alertexecuted,since"anumber"isnotanumber
//Anotherimportantthing:
if(isNaN("3"))
alert("bad")
//Notexecuted,becausethestring"3"getsconvertedinto3,and3isanumber

BasicArithmetic
Doingbasicarithmeticissimple.
Syntax
4+5//9
4*5//20
54//1
20/5//4

PrefixandPostfixincrement/decrementoperators
Prefixincrement/decrementoperatorsareoperatorsthatfirstincreasethevalueofthevariable
by1(increment)ordecreasethevalueofanexpression/variableby1(decrement)andthen
return this incremented / decremented value. They are used like ++ (variable) [increment]
or (varaible) [decrement] On the other hand , Postfix increment / decrement operators are
operatorsthatfirstreturnthevalueofthevariableandthenincreasethevalueofthatvariable
by 1 (increment) or decrease the value of the variable by 1 (decrement) . They are used like
(variable) ++ [increment]or(varaible) [decrement]
Syntax
variable//PrefixDecrement
++variable//PrefixIncrement
variable//PostfixDecrement
variable++//PostfixIncrement
Example
//Theexampleswillmakeitclear
varx=15//xhasavalueof15
vary=x++
//sinceitispostfix,thevalueofx(15)isfirstassignedtoyandthenthevalueofxisincrementedby1
console.log(y)//15
console.log(x)//16
vara=15//ahasavalueof15
varb=++a
//sinceitisprefix,thevalueofa(15)isfirstincrementedby1andthenthevalueofxisassignedtob
console.log(b)//16
console.log(a)//16

Objects
ObjectLiterals
Syntax
{
"property1":value1,
property2:value2,
number:value3
}
Example
varobj={

name:"Bob",
married:true,
"mother'sname":"Alice",
"yearofbirth":1987,
getAge:function(){
return2012obj["yearofbirth"]
},
1:'one'
}

PropertyAccess
Syntax
name1[string]
name2.identifier
Example
obj['name']//'Bob'
obj.name//'Bob'
obj.getAge()//24

OOP
Classes
Aclasscanbethoughtofasatemplatetocreatemanyobjectswithsimilarqualities.Classes
areafundamentalcomponentofobjectorientedprogramming(OOP).
Syntax
SubClass.prototype=newSuperClass()
Example
varLieutenant=function(age){
this.rank="Lieutenant"
this.age=age
}
Lieutenant.prototype=newPoliceOfficer()
Lieutenant.prototype.getRank=function(){
returnthis.rank
}
varJohn=newLieutenant(67)
John.getJob()//'PoliceOfficer'

John.getRank()//'Lieutenant'
John.retire()//true

Popupboxes
alert
DisplayanalertdialogwiththespecifiedmessageandanOKbutton.Thealertdialogshouldbe
usedformessageswhichdonotrequireanyresponseonthepartoftheuser,otherthanthe
acknowledgementofthemessage.
Syntax
alert(message)
Example
alert("HelloWorld")

confirm
Displaysadialogwiththespecifiedmessageandtwobuttons,OKandCancel.
Syntax
confirm("message")//returnstrueifconfirmed,falseotherwise
Example
if(confirm("Areyousureyouwanttodeletethispost?")){
deletePost()
}
Readmore
https://developer.mozilla.org/enUS/docs/Web/API/window.confirm

prompt
The prompt() displays a dialog with an optional message prompting the user to input some
text.Iftheuserclicksthe"Cancel"button,nullisreturned.
Syntax
prompt(message)
Example
varname=prompt("Enteryourname:")

console.log("Hello"+name+"!")
Readmore
https://developer.mozilla.org/enUS/docs/Web/API/window.prompt

Strings
Stringsaretext.Theyaredenotedbysurroundingtextwitheithersingleordoublequotes.
Syntax
"stringoftext"
'stringoftext'

Concatenation
Syntax
string1+string2
Example
"some"+"text"//returns"sometext"
varfirst="my"
varsecond="string"
varunion=first+second//unionvariablehasthestring"mystring"

length
Returnsthelengthofthestring.
Syntax
string.length
Example
"Myname".length//7,whitespaceisalsocounted
"".length//0

toUpperCase(),toLowerCase()
Changesthecasesofallthealphabeticallettersinthestring.
Example
"myname".toUpperCase()//Returns"MYNAME"
"MYNAME".toLowerCase()//Returns"myname"

trim()
Removeswhitespacefrombothendsofthestring.
Syntax
string.trim()
Example
"a".trim()//'a'
"aa".trim()//'aa'
Readmore
https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

replace()
Returnsastringwiththefirstmatchsubstringreplacedwithanewsubstring.
Example
"originalstring".replace("original","replaced")//returns"replacedstring"

charAt()
Returns the specified character from a string. Characters in a string are indexed from left to
right.Theindexofthefirstcharacteris0,andtheindexofthelastcharacterinastringcalled
stringNameis stringName.length1 .Iftheindexyousupplyisoutofrange,JavaScriptreturns
anemptystring.
Syntax
string.charAt(index)//indexisanintegerbetween0and1lessthanthelengthofthestring.
Example
"HelloWorld!".charAt(0)//'H'
"HelloWorld!".charAt(234)//''
Readmore
https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt

substring()

Returnsthesequenceofcharactersbetweentwoindiceswithinastring.
Syntax
string.substring(indexA[,indexB])
//indexA:Anintegerbetween0andthelengthofthestring
//indexB:(optional)Anintegerbetween0andthelengthofthestring.
Example
"adventures".substring(2,9)//Returns"venture"
//ItstartsfromindexA(2),andgoesuptobutnotincludingindexB(9)
"hello".substring(1)//returns"ello"
"WebFundamentals".substring(111)//returns''
"Inthemarket".substring(2,999)//returns'themarket'
"Fastandefficient".substring(3,3)//returns''
"Goaway".substring("abcd",5)//returns'Goaw'
//Anynonnumericthingistreatedas0

indexOf()
ReturnstheindexwithinthecallingStringobjectofthefirstoccurrenceofthespecifiedvalue,
startingthesearchat fromIndex ,Returns 1 ifthevalueisnotfound.The indexOf method
iscasesensitive.
Syntax
string.indexOf(searchValue[,fromIndex])//fromIndexisoptional.Itspecifiesfromwhichindexshouldth
esearchstart.Itsdefaultvalueis0.
Example
"Mynameisverylong.".indexOf("name")//returns3
"Mynameisverylong.".indexOf("Name")//returns1,it'scasesensitive
"Whereareyougoing?".indexOf("are",11)//returns1
"LearntoCode".indexOf("")//returns0
"LearntoCode".indexOf("",3)//returns3
"LearntoCode".indexOf("",229)returns13,whichisthestring.length
Readmore
https://developer.mozilla.org/en
US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

Switchstatements
Actslikeabigif/elseif/elsechain.Checksavalueagainstalistofcases,andexecutesthe
firstcasethatistrue.Itgoesonexecutingallothercasesitfindsafterthefirsttruecasetillit
findsabreakingstatement,afterwhichitbreaksoutoftheswitchIfitdoesnotfindanymatching

case,itexecutesthedefaultcase.
Syntax
switch(expression){
caselabel1:
statements1
[break]
caselabel2:
statements2
[break]
...
caselabelN:
statementsN
[break]
default:
statements_def
[break]
}
Example
vargender="female"
switch(gender){
case"female":
console.log("Hello,ma'am!")
case"male":
console.log("Hello,sir!")
default:
console.log("Hello!")
}

TernaryOperator
Theternaryoperatorisusuallyusedasashortcutfortheifstatement.
Syntax
condition?expr1:expr2
Example
vargrade=85
console.log("You"+(grade>50?"passed!":"failed!"))
//Output:Youpassed!
/*Theabovestatementissameassaying:
if(grade>50){
console.log("You"+"passed!")//orsimply"Youpassed!"

}
else{
console.log("You"+"failed!")
}
*/

Variables
VariableAssignment
Syntax
varname=value
Example
varx=1
varmyName="Bob"
varhisName=myName
Variablechanging
Syntax
varname=newValue
Example
varname="Michael"//declarevariableandgiveitvalueof"Michael"
name="Samuel"//changevalueofnameto"Samuel"

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