0% found this document useful (0 votes)
11K views22 pages

JavaScript Glossary - Codecademy

Arrays allow accessing elements by index, with indexes starting at 0. Elements can be accessed using arrayName[index]. Arrays can be created using array literals by listing values in square brackets or the Array constructor. Multidimensional arrays contain other arrays, accessed with multiple indexes like arrayName[index1][index2]. Functions are reusable blocks of code defined with the function keyword that can be called. If statements execute code conditionally based on a boolean test.

Uploaded by

Kire Todosov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11K views22 pages

JavaScript Glossary - Codecademy

Arrays allow accessing elements by index, with indexes starting at 0. Elements can be accessed using arrayName[index]. Arrays can be created using array literals by listing values in square brackets or the Array constructor. Multidimensional arrays contain other arrays, accessed with multiple indexes like arrayName[index1][index2]. Functions are reusable blocks of code defined with the function keyword that can be called. If statements execute code conditionally based on a boolean test.

Uploaded by

Kire Todosov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Arrays

Accessingarrayelements
[Link]'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
[Link]
[Link]
mixedtypes.
Syntax
vararrayName=[element0,element1,...,elementN]
Example
varprimes=[2,3,5,7,11,13,17,19,23,29,31,37]
Readmore
[Link]
[Link]

MultidimensionalArrays
[Link]
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)
[Link](myArray)
//output:[45,'HelloWorld!',true,3.2,undefined]
Readmore
[Link]
US/docs/Web/JavaScript/Reference/Global_Objects/Array#Example.3A_Creating_an_arra
y

Accessingnestedarrayelements
[Link]
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]]
]
[Link](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
[Link](),&&,
||,!*/
//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
[Link],consideranexpression:a*b*[Link](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
[Link].
Example
if(1)[Link]("True!")//outputTrue!,sinceanynonzeronumberisconsideredtobetrue
if(0)[Link]("Idoubtifthisgetsexecuted")//notexecuted,since0isconsideredtobefalse
if("Hello")alert("So,anynonemptyStringisalsotrue.")//Getsexecuted
if("")alert("Hence,anemptyStringisfalse")//Notexecuted
Readmore
[Link]

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

===[Link].
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 [Link] you write 100 lines of
codeandthenforgetwhateachfunctiondid,it'[Link],
suggestions,warnings,[Link]

SingleLineComment
Anythingonthelinefollowing // willbeacommentwhileanythingbeforewillstillbecode.
Syntax
[Link]("Thiscodewillberun")
//[Link]("Becausethislineisinacomment,thiscodewillnotberun.")
//Thisisasinglelinecomment.

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

[Link]("Hello,Ialsowillnotbeexecuted")
*/

Console
[Link]
[Link].
Example
varname="Codecademy"
[Link](name)

[Link]
This function starts a timer which is useful for tracking how long an operation takes to
[Link],andmayhaveupto10,000timersrunningona
[Link] [Link]() withthesamename,thebrowserwilloutputthe
time,inmilliseconds,thatelapsedsincethetimerwasstarted.
Syntax
[Link](timerName)
Example
[Link]("MyMath")
varx=5+5
[Link](x)
[Link]("MyMath")
[Link]("Donethemath.")
/*Output:
10
MyMath:(timetaken)
Donethemath.
*/
Readmore
[Link]
[Link]

[Link]
Stopsatimerthatwaspreviouslystartedbycalling [Link]() .

Syntax
[Link](timerName)
Example
[Link]("MyMath")
varx=5+5
[Link](x)
[Link]("MyMath")
/*Output:
10
MyMath:(timetaken)
*/
Readmore
[Link]

Functions
AfunctionisaJavaScriptprocedureasetofstatementsthatperformsataskorcalculatesa
[Link],having20forloops,andthenhavingasingle
function to handle it all . To use a function, you must define it somewhere in the scope from
[Link](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
[Link]

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(){
[Link]('Hello!Iamdefinedimmediately!')
}
varnotHoistedFunction=function(){
[Link]('Iamnotdefinedimmediately.')
}
Readmore
[Link]

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){
[Link]('Toldyouso!')
}

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

elseif
Thisislikean else statement,[Link],
andthepreviousstatement'sconditionwasfalse.
Syntax
//Form:[Link],[Link],condition2ischecked.i
fitistrue,[Link],ifnothingistrue,statement3isexecuted.
if(condition1){
statement1
}elseif(condition2){
statement2
}else{
statement3
}
Example
if(someNumber>10){
[Link]("Numberslargerthan10arenotallowed.")
}elseif(someNumber<0){

[Link]("Negativenumbersarenotallowed.")
}else{
[Link]("Nicenumber!")
}

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

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

//Yourcodehere
}
Example
varx=0
while(x<5){
[Link](x)//Printsnumbersfrom0to4
x++
}
Example
varx=10
while(x<=5){
[Link](x)//Won'tbeexecuted
x++
}
Readmore
[Link]

DoWhileLoops
Youusedowhileloops,ifyouhavetoloopatleastonce,butifyoudon'tknowhowoften.
Syntax
do{
//Yourcodehere
}while(condition)
Example
varx=0
do{
[Link](x)//Printsnumbersfrom0to4
x++
}while(x<5)
Example
varx=10
do{
[Link](x)//Prints10
x++
}while(x<=5)
Readmore
[Link]

Math
random
Returnsarandomnumberbetween0and1.
Syntax
[Link]()
Example
[Link]()//Arandomnumberbetween0and1.

floor
Returnsthelargestintegerlessthanorequaltoanumber.
Syntax
[Link](expression)
Example
[Link](9.99)//9
[Link](1+0.5)//1
[Link]([Link]()*X+1)//Returnsarandomnumberbetween1andX

pow
Returnsbaseraisedtoexponent.
Syntax
[Link](base,exponent)
Example
[Link](2,4)//gives16
Readmore
[Link]
US/docs/Web/JavaScript/Reference/Global_Objects/Math/pows

ceil
Returnsthesmallestintegergreaterthanorequaltoanumber.

Syntax
[Link](expression)
Example
[Link](45.4)//46
[Link](41.9)//3
Readmore
[Link]
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 [Link] because [Link] isnotafunction.
Syntax
[Link]
Example
[Link]([Link])//roundsthevalueofPI,gives3
[Link]([Link])//4
Readmore
[Link]
US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI

sqrt
Returnsthesquarerootofanumber.
Syntax
[Link](expression)
Example
[Link](5+4)//3
[Link]([Link](122+22)+[Link](16))//4
Readmore
[Link]
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
[Link](y)//15
[Link](x)//16
vara=15//ahasavalueof15
varb=++a
//sinceitisprefix,thevalueofa(15)isfirstincrementedby1andthenthevalueofxisassignedtob
[Link](b)//16
[Link](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]
[Link]
Example
obj['name']//'Bob'
[Link]//'Bob'
[Link]()//24

OOP
Classes
[Link]
areafundamentalcomponentofobjectorientedprogramming(OOP).
Syntax
[Link]=newSuperClass()
Example
varLieutenant=function(age){
[Link]="Lieutenant"
[Link]=age
}
[Link]=newPoliceOfficer()
[Link]=function(){
[Link]
}
varJohn=newLieutenant(67)
[Link]()//'PoliceOfficer'

[Link]()//'Lieutenant'
[Link]()//true

Popupboxes
alert
[Link]
usedformessageswhichdonotrequireanyresponseonthepartoftheuser,otherthanthe
acknowledgementofthemessage.
Syntax
alert(message)
Example
alert("HelloWorld")

confirm
Displaysadialogwiththespecifiedmessageandtwobuttons,OKandCancel.
Syntax
confirm("message")//returnstrueifconfirmed,falseotherwise
Example
if(confirm("Areyousureyouwanttodeletethispost?")){
deletePost()
}
Readmore
[Link]

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

[Link]("Hello"+name+"!")
Readmore
[Link]

Strings
[Link].
Syntax
"stringoftext"
'stringoftext'

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

length
Returnsthelengthofthestring.
Syntax
[Link]
Example
"Myname".length//7,whitespaceisalsocounted
"".length//0

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

trim()
Removeswhitespacefrombothendsofthestring.
Syntax
[Link]()
Example
"a".trim()//'a'
"aa".trim()//'aa'
Readmore
[Link]
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
[Link](index)//indexisanintegerbetween0and1lessthanthelengthofthestring.
Example
"HelloWorld!".charAt(0)//'H'
"HelloWorld!".charAt(234)//''
Readmore
[Link]
US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt

substring()

Returnsthesequenceofcharactersbetweentwoindiceswithinastring.
Syntax
[Link](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 [Link] indexOf method
iscasesensitive.
Syntax
[Link](searchValue[,fromIndex])//[Link]
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,[Link]
Readmore
[Link]
US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

Switchstatements
Actslikeabigif/elseif/[Link],andexecutesthe
[Link]
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":
[Link]("Hello,ma'am!")
case"male":
[Link]("Hello,sir!")
default:
[Link]("Hello!")
}

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

}
else{
[Link]("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"

You might also like