QuickJavaScriptInterviewQuestions
CopyrightBlurb
Allrightsreserved.Nopartofthisbookmaybereproducedinanyformorbyany
electronicormechanicalmeansincludinginformationstorageandretrievalsystems–
exceptinthecaseofbriefquotationsinarticlesorreviews–withoutthepermissionin
writingfromitspublisher,SandeepKumarPatel.
Allbrandnamesandproductnamesusedinthisbookaretrademarks,registered
trademarks,ortradenamesoftheirrespectiveholders.Iamnotassociatedwithany
productorvendorinthisbook.
PublishedBy
SandeepKumarPatel.
TableofContents
QuickJavaScriptInterviewQuestionsTableofContents
Chapter1Inheritance
Chapter2QuestionsonEvent
Chapter3Closure
Chapter5QuestionsonDOM
Chapter6DateObject
Chapter7RegularExpression
Chapter8QuestionsonCanvasAPIChapter9GeoLocationAPI
Chapter10WebWorkers
Chapter11LocalStorage
Chapter12FileAPI
Chapter13WebRTC
Chapter14Drag&DropAPI
Chapter15AppCacheAPI
Chapter16ServerSentEventsChapter17MiscellaneousQuestionsAboutThe
Author
OneLastThing…
Chapter1Inheritance
Q.Howtocreateaclass?
ANSWER
JavaScriptdoesnothaveaclassdefinition.TomimicclassesinJavaScriptfunctionscan
beusedtodeclareaclass.
Example:
Let’screateastudentclassinJavaScriptwhichtakestwoparametersnameandrollas
property.Thecodewilllooklikebelow,
functionStudent(name,roll){this.name=name;
this.roll=roll;
}
Q.Howtocreateanobject?
ANSWER
AnobjectinJavaScriptcanbecreatedusingtwoways:
NewKeyword:
TocreateastudentobjectfromtheabovestudentclasswecancalltheStudentfunction
usingnewkeyword.
varstudent1=newStudent(‘sandeep’,2)
AnonymousObject:
Anonymousobjectscanbecreatedusingpairofcurlybracescontainingpropertyname
andvaluepairs.
Varrose={‘color’:’red’}
Q.Howtodeclareaprivateandapublicmember?
Privatemembersaredeclaredusingvarkeywordandconstructorfunction.
functionStudent(name,roll){varid=ABCD123;
this.name=name;
this.roll=roll;
}
WhenaStudentobjectwillbecreatedthepropertiednameandrollwillbeaccessible
usingdotoperatorbutidwillnotbeaccessibleasitbehavesasaprivatememberand
returnundefinedoncall.
Theabovechromeconsoleisshowingastudent1objectiscreated.namepropertyis
accessibleasitisshowingsandeeponstudent1.namecall.Sonameisapublicpropertyfor
thestudentobject.Butidpropertyisnotaccessibleandreturnedundefinedonstudent1.id
call.Thisshowsidisaprivatepropertyinstudent1object.
Q.Whatisprototypeproperty?
ByUsingPrototypewecanaddnewmemberstoanexistingobject.EveryJavaScript
objecthasthispropertyinternally.Initiallyitisanemptyobject.
Example:
functionStudent(name,roll){
this.name=name;
this.roll=roll;
}
varstudent1=newStudent(‘sangeeta’,30);Student.prototype.mark=100;
Checkoutthebelowchromeconsolefortheuseofprotype.
Initiallythestudent1objecthasonlytwopropertiesnameandroll.Byusingprototypea
newpropertymarkhasbeenaddedtostudentobjectwithavalueof100.Nowtheconsole
showsthatthemarkpropertyisalsoaddedtotheexistingstudent1object.
Q.Whatisconstructorproperty?
ANSWER
Constructorpropertyofanobjectmaintainsareferencetoitscreatorfunction.
Example:
Letuscheckoutanexamplebycreatingastudentobjectandcallingtheconstructor
propertyonit.
functionStudent(name,mark){
this.name=name;
this.mark=mark;
}
varstudent1=newStudent(‘sandeep’,123);console.log(student1.constructor);
Checkoutthefollowingscreenshotforabovecodeinchromeconsole.Theconsolelogis
printingthereferencedfunctionbystudent1object.
Q.Howtocallotherclassmethods?
ANSWER
Usingcall()andapply()methodwecanusemethodsfromdifferentcontexttothecurrent
context.Itisreallyhelpfulinreusabilityofcodeandcontextbinding.
call():Itisusedtocallsafunctionwithagiventhisvalueandargumentsprovided
individually.
apply():Itisusedtocallafunctionwithagiventhisvalueandargumentsprovidedasan
array.
BelowcodehastwofunctiongetTypeOfNumber()andgetTypeOfAllNumber().The
detailspfthesefunctionsarebelow.getTypeOfNumber:Thismethodtakessingle
numberas
parameterandreturnthetypeeitherEvenorOdd.
getTypeOfAllNumber:Thismethodtakesarrayofnumbers
asparameterandreturnthetypesinanarraywithEvenor
Odd.
varMyNumber={
getTypeOfNumber:function(number){
vartype=(number%2===0)?“Even”:“Odd”;returntype;
},
getTypeOfAllNumber:function(){
varresult=[],i=0;
for(;i
vartype=
MyNumber.getTypeOfNumber.call(null,arguments[i]);
result.push(type)
}
returnresult;
}
};
vartypeOfNumber=
MyNumber.getTypeOfNumber.call(null,21)console.log(typeOfNumber)
vartypeOfAllNumber=
MyNumber.getTypeOfAllNumber.apply(null,[2,4,5,78,21])
console.log(typeOfAllNumber)
BelowscreenshotshowsoutputoftheabovecodeFirebugconsole.
Q.ExplainmethodoverridingwithanExample?
ANSWER
WecanoverrideanyinbuiltmethodofJavaScriptbydeclaringitsdefinitionagain.The
existingdefinitionisaccessibletooverridebytheprototypeproperty.Considerthebelow
example,split()isanbuilt-inmethodforastringobject.Itsdefaultbehaviourtobreakthe
specifiedstringtoanarrayandisamemberfunctionofStringclass.Butwehave
overriddenitsdefinitionusingitsprototypeproperty.
Belowscreenshotshowstheinbuiltbehaviourofsplit()method.Ithasdividedthestring
intoanarrayofelement.
Thefollowingscreenshotshowsthenewoverriddendefinitionofsplit()method.Itisnow
normallyreturnsstring“Iamoverriden”.
Q.Howtoinheritfromaclass?
ANSWER
InheritancecanbeachievedinJavaScriptusingprototypeproperty.
Weneedtofollow2stepstocreateaninheritance.
Step1:
Childclassprototypeshouldpointtoparentclassobject.
<ChildClassName>.prototype=new<ParentClass>();
Step2:
Resetthechildclassprototypeconstructortopointself.
<ChildClassName>.prototype.constructor=<ChildClassName>
Example:
BelowexampleshowsScienceStudentclassasachildclassofStudentclass.Asthe
methodshowMyType()isavailableforScienceStudentobject.
functionStudent(name){
this.name=name;
}
Student.prototype.sayMyType=function(){
console.log(“Iamstudenttype”)
}
functionScienceStudent(name){
}
ScienceStudent.prototype=newStudent();
ScienceStudent.prototype.constructor=ScienceStudent;
varstudent2=newScienceStudent(‘sangeeta’);
console.log(student2.sayMyType());
Checkoutthebelowscreenshotfortheoutputoftheabovecodeinthedeveloperconsole.
TotestthetypeofanobjectbelongstoaclassornotinstanceOfcanbeused.Thisreturns
aBooleanvalue,TRUEforanobjectbelongstoaclassorelseFALSE.Checkthebelow
screenshotforthetestofstudent2objectusinginstanceOf.
Q.Whatisdifferentialinheritance?
ANSWER
DifferentialInheritanceisacommonprototype-orientedmodelthatusestheconceptthat
mostobjectsarederivedfromother,moregenericobjects,andonlydifferinafewsmall
aspects.Eachobjectmaintainsareferencetoitsprototypeandatableofpropertiesthatare
different.
Q.WhatisObject.create()methoddo?
ANSWER
ECMAScript5.1hasthismethodinitsspecification.Thismethodcanbeusedtocreatea
newobjectwithgivenprototypeobjectandproperties.Thesyntaxofthismethodislisted
below.
Object.create(proto[,propertiesObject])
Example:
BelowcodehasaStudentclassfunctionwithnamepropertyandtheprototypeobjecthas
amethodgetStudentName()whichreturnthenameofthestudent.Anewstudent1objecthas
beencreatesusingObject.create()methodbypassingtheprototypeobjectofStudentwith
valueofthenameassandeep.ThenthegetStudentName()methodiscalledonstudent1object
andloggedintheconsole.
functionStudent(name){
this.name=name;
}
Student.prototype={
getStudentName:function(){
return“NameofStudentis:”+this.name;}
};
varstudent1=Object.create(Student.prototype);student1.name=“Sandeep”;
console.log(student1.getStudentName());
Thefollowingscreenshotshowstheoutputoftheabovecodeinthedeveloperconsole.
Q.WriteapolyfillforObject.create()methodifitisnotpresentinthebrowser?
ANSWER
ECMAScript5.1hasthismethodinitsspecification.IfthebrowserisoldthenObject.create()
methodisnotpresent.Toresolvethisweneedtowriteapolyfill.Belowcodeshowsthe
polyfillforObject.create()method.
//checkifcreatemethodispresentinsideObjectif(typeofObject.create!=‘function’){
//definethecreatemethod
Object.create=(function(){
varObject=function(){};
returnfunction(prototype){
if(arguments.length>1){
throwError(‘Secondargumentnotsupported’);
}
if(typeofprototype!=‘object’){
throwTypeError(‘Argumentmustbeanobject’);
}
Object.prototype=prototype;
varresult=newObject();
Object.prototype=null;
returnresult;};
})();
}
Theabovecodechecksifthecreate()methodisalreadypresentinsidetheObjectusingif
conditionandcomparingitstypetofunction.Ifthisconditiontrueitmeansthecreate()
methodisnotpresent.Thenthepolyfillcodeblockgetsexecutesandassignstheempty
objecttoObject.createproperty.
Q.WhatisthepurposeofObject.defineProperties()method?ANSWER
ECMAScript5.1providesObject.defineProperties()methodtocreatenewpropertiestoa
definedobject.Itprovidesmanyconfigurationoptionstoinitializethesemembers.Below
codeshowstheuseofthismethod.
functionStudent(name){
this.name=name;
}
varstudent1=Object.create(Student.prototype),
properties={
“subject”:{
value:“Computer”,
writable:true,
enumerable:true
},
“marks”:{
value:0,
writable:false,
enumerable:true
}
};
Object.defineProperties(student1,properties);
student1.name=“Sandeep”;
student1.subject=“Mathematics”;
student1.marks=75;
console.log(student1);
Intheabovecodeastudent1objectcreatedusingObject.create()method.Thensomenew
propertieslikesubjectandmarksareaddedtothisobject.Theenumerableoptiondecided
whetherthepropertycanbeenumeratedasownproperty.Writablepropertydecideswhether
thepropertyismodifiableornot.Thevaluepropertytakesthedefaultvalueoftheproperty.
Belowscreenshotshowstheoutputoftheabovecodeinthedeveloperconsole.
Q.HowcanyoudistinguishscopeandcontextinJavaScript?ANSWER
Scopepertainstothevisibilityofvariablesandcontextreferstotheobjecttowhicha
methodbelongsandcanbechangedbyusingcallorapplies.
Q.Whataretwowaysinwhichthevariablecanbeassignedtoanemptyobject?
ANSWER
Whencreatinganewemptyobject,youcaninstantiatetheObject()constructororyoucan
simplycreateanemptyobjectliteral.Ineithercase,youcanthenaddpropertiestothe
newobject.Thesyntaxofcreatingemptyobjectislistedbelow.
varaEmptyObject=newObject();
varaEmptyObject=={};
Chapter2QuestionsonEvent
Q.HowEventworks?
ANSWER
Eventpropagationfollowstwophasescapturingandbubblingphase.
CapturingPhase:
Inthisphase,eventfirstmakesitswaydownwardsfromtheDOCUMENTtothetarget
elementbypassingallinnerelements.
BubblingPhase:
Inthisphaseeventmakesitswaybackupwardsfromthetargetelementto
DOCUMENTbypassingallouterwrappedelements.
Q.Howtoattacheventtoanelement?
ANSWER
AccordingtoDOMLevel2EventSpecificationaneventcanbeattachedtoanelement
usingaddEventListener()methodusingthreearguments.
Syntax:
<element>.addEventListener(<eventname>,<eventcallback>,<booleanphase>)
eventname:
RepresentstypeofeventasStringparameter.ForExampleclick,mouseover,mouseout
etc.
eventcallback:
Thisrepresentsthecallbackfunctiontobecalledfortheeventtobehandled.
booleanphase:
Thisrepresentsthephaseoftheeventwherethelistenerisattached.AFALSEvalue
representsthebubblingphaseandaTRUEvaluerepresentsacapturingphase.
Example:
Aclickeventlistenerisaddedtothedocumentwhichalertsamessagewhenclickoccur.
document.addEventListener(‘click’,function(){alert(“InsiderEventListener”);
},false);
Q.HowtoattacheventpriortoIE9browserversion?ANSWER
InIEolderbowseraneventcanbeattachedtoanelementusingattachEvent()method.
OnlyForbubblingphasealistenercanbeadded.
Syntax:
<element>.attachEvent(<eventname>,<eventcallback>)
Example:
Aclickeventlistenerisaddedtothedocumentwhichalertsamessagewhenclickoccur.
BelowscreenshotshowsaddingaclickeventinIE10developertoolbar.
ExceptIE,theotherbrowseraddedbyaddEventListener()method.Belowscreenshot
showsthedemonstrationthismethodinFirebug.
Q.Howtoremoveeventlistener?
ANSWER
AccordingtoDOMLevel2EventSpecificationanEventListenercanberemovedusing
removeEventListener()method.ForIEbrowsersdetachEvent()methodmustbeused.
ThefollowingscreenshotshowsdetachingclickeventhandlerfromdocumentforIE
browser.
ThefollowingscreenshotshowsremovingclickeventhandlerfromdocumentforFirefox
browser.
Q.HowsetTimeOut()andclearTimeOut()functionworks?ANSWER
ThesetTimeout()methodcallsafunctionorevaluatesanexpressiononceaftera
specifiednumberofmilliseconds.clearTimeOut()methodstoptheexecutionofthe
functionspecifiedinthesetTimeout()method.
Syntax:
vartimeOut=setTimeout(function,milliseconds,lang)clearTimeout(timeOut)
Belowcodeshowsthedemonstrationofthesetimeoutmethods.
vartimeOutHandler=function(){
console.log(“insideTimeNow“,newDate().getSeconds());clearTimeout(timeOut)
}
console.log(“TimeNow“,newDate().getSeconds());vartimeOut=
setTimeout(timeOutHandler,4000);
BelowscreenshotshowtheexecutionofthetimeOutHandler()methodafter4seconds.
Q.HowsetInterval()andclearInterval()functionworks?ANSWER
ThesetInterval()methodcallsafunctionorevaluatesanexpressioninspecifiedinterval
ofmilliseconds.clearInterval()methodstoptheexecutionofthefunctionspecifiedinthe
setInterval()method.
Syntax:
vartimeInterval=setInterval(function,milliseconds)clearInterval(timeInterval)
Belowcodedemonstratetheseintervalhandlers.
varcounter=0,
timeIntervaltHandler=function(){
console.log(“insideTimeNow“,newDate().getSeconds());counter++;
console.log(“HandlerCalledcount“,counter)
if(counter===4){
clearInterval(timeInterval);
console.log(“Clearingtheintervalhandler”)
}
}
console.log(“TimeNow“,newDate().getSeconds());vartimeInterval=
setInterval(timeIntervaltHandler,2000);
Belowscreenshotshowsthehandlercalledevery2secondfor4times.After4thcalled
clearInterval()removetheexecution.
Chapter3Closure
Q.WhatisClosure?
ANSWER
Aclosureisaninnerfunctionthathasaccesstotheouterwrappedfunction’svariables.It
hasthreedifferentscopeaccesses:-Self-scope:
Ithasaccesstopropertiespresentinitsownscope.
Wrappedfunction’sscope:
Ithasaccesstothepropertiespresenttofromitsenclosingfunction.
GlobalScope:
Ithasaccesstothepropertiespresentinglobalscopethatiswindowscope.
Example:
Theinnerfunctionstillhastheaccesstoprop1thoughprop1belongstoouterfunction
scope.
functionmyOuterFunction(){varprop1=5;
returnfunctioninnerFunction(){
returnprop1;
}
}
varres=myOuterFunction();console.log(res.name);
console.log(res());
Belowscreenshotshowstheoutputoftheabovecodeintheconsole.
Q.Giveanexampleofpracticalimplicationofclosureconcept?ANSWER
Inwebpagedevelopmentclosuresaremorefrequentlyusedbythedevelopers.Amost
commonscenarioiswhenweneedsomekindoffactorywhichwillreturnafunction
objectwithdifferentvaluethatcanbeusedbyapplication.
Example:
ThefollowingcodehasabackgroundcolorfactorynamedbackgroundColorFactorywhich
returnsafunctionwithaninputcolor.UsingthisfactorywehavecreatedgreenBackground
andblueBackgroundfunctionobjectsandbindedwiththe2buttons.Onceuserclicksthese
buttonsthebackgroundcolorofthebodyischangedtothetargetedcolor.
<!DOCTYPEhtml>
<html>
<head>
<metacharset=“utf-8”>
<title>PracticalClosureExample</title>
</head>
<body>
<buttonid=“greenButton”>GreenBackground</button><buttonid=“blueButton”>Blue
Background</button><script>
varbackgroundColorFactory=function(color){returnfunction(){
document.body.style.background=color;};
};
vargreenBackground=backgroundColorFactory(‘green’);varblueBackground=
backgroundColorFactory(‘blue’);
document.getElementById(‘greenButton’).onclick=greenBackground;
document.getElementById(‘blueButton’).onclick=blueBackground;
</script>
</body>
</html>
Theoutputoftheabovecodeislistedinbelowscreenshot.
Q.Emulatetheprivatedatausingclosure?
ANSWER
Thefollowingcodedemonstratesthedeclarationofprivatevariable_name.Itmeanswe
canassignthe_namevalueusingStudentconstructorwithanewkeyword.
functionStudent(name){var_name=name;
this.getName=function(){return_name;
};
}
varstudent1=newStudent(“Sandeep”);student1._name=“John”;
console.log(student1.getName());
Thedetailsofthepreviouscodeareasfollows:
AStudentobjectstudent1iscreatedwith_namehasvalueSandeep.
AnewnamevalueJohnisassignedto_namebutthegetName()methodprintsSandeep
totheconsole.Itproves_nameisprivate.
ThefollowingscreenshotshowstheChromeconsolewiththeoutputofthepreviouscode.
Chapter4QuestionsonJSON
Q.WhatisJSON?
ANSWER
TheJSONtextformatissyntacticallyidenticaltothecodeforcreatingJavaScriptobjects.
JSONisonlyasubsetofJSobjectliteralnotation,butapartfromlookingsimilar,they
havenothingincommon.JSONisusedasdataexchangeformat,likeXML.JSONisbuilt
ontwostructures:
Acollectionofname/valuepairs.Invariouslanguages,thisisrealizedasanobject,record,
struct,dictionary,hashtable,keyedlist,orassociativearray.
Anorderedlistofvalues.Inmostlanguages,thisisrealizedasanarray,vector,list,or
sequence.
Q.WhydoesGoogleprependwhile(1);totheirJSONresponses?ANSWER
ItpreventsJSONhijacking.Thisistoensuresomeothersitecan’tdonastytrickstotryto
stealdata.Byreplacingthearrayconstructor,thenincludingthisJSONURLviaa<script>
tag,amaliciousthirdpartysitecouldstealthedatafromtheJSONresponse.Byputtinga
while(1);atthestart,thescriptwillcrashinstead.Asame-siterequestusingXHRanda
separateJSONparser,ontheotherhand,caneasilyignorethewhile(1);prefix.
Q.WhatisJSONP?
ANSWER
JSONPstandsfor“JSONwithPadding”.ItmeansJSONdatawrappedinafunctioncall.
Acallback(processing/padding)functionalreadydefinedintheWebpageatthetimeof
requestingremoteJSONdata.
Example:
ThebelowJavaScriptcodeshowsacallbackfunctionpaddingFunction()foraremoteURL
//abcdurl.
functionpaddingFunction(data){
console.log(“responsedataprocessingcode”)
}
varscript=document.createElement(‘script’);
script.src=‘//abcdurl?callback=paddingFunction’
document.getElementsByTagName(‘head’)[0].appendChild(script);
Q.WhyuseJSONoverXML?
ANSWER
ThefollowingpointsareinfavorofJSONoverXMLformat:
JSONcancontainInteger,String,List,Arrays.XMLisjustnodesandelementsthatneeds
tobeparsedintoInteger,Stringandsoonbeforeitisusedbyyourapplication.JSONis
smaller,fasterandlightweightcomparedtoXML.Sofordatadeliverybetweenservers
andbrowsers,JSONisabetterchoice.
JSONisbestforuseofdatainwebapplicationsfromwebservicesbecauseofJavaScript
whichsupportsJSON.TheoverheadofparsingXMLnodesismorecomparetoaquick
lookupinJSON.
Foranewbie,JSONmightlookcomplextoreadandunderstandbecauseofitsstructure