Está en la página 1de 17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

ExpertMentors
ExpertMentors
WebProgramming
WebProgramming
Ruby
JavaScript
AngularJS
Python
PHP
HTML/CSS
jQuery
RubyonRails
Django
Node.js
CoffeeScript
Ember.js
Backbone.js
Meteor
Flask
Scala
Code
Code
Ruby
JavaScript
PHP
Python
Java
C#
C++
Go
C
.NET
Haskell
Perl
Erlang
Matlab
Debugging
Crystal
MobileAppProgramming
MobileAppProgramming
iOS
Android
Swift
PhoneGap
Cordova
Ionic
Titanium
Sencha
Design/UX
Design/UX
HTML/CSS
CSS
Sass
Twitterbootstrap
Famo.us
KendoUI
Responsivedesign
Foundation
Photoshop
Database/Operations
Database/Operations
Server
DevOps
MySQL
SQL
MongoDB
Hadoop
Apache
https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

1/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

Linux
AWS
Heroku
Database
Security
Azure
DevelopmentProcess/Tools
DevelopmentProcess/Tools
Git
DevOps
WordPress
Drupal
Joomla
SEO
Vim
Bower
Machinelearning
Xcode
Jenkins
TopDevelopers
TopDevelopers
Ruby
Javascript
AngularJS
Python
iOS
Swift
PHP
Java
1:1Mentorship
LiveClasses
FreeTutorials
LearntoCode
LiveClasses
LiveClasses
Meteor
Angular2
BeginnerPythonforML
MachineLearning
BeginnerReact
Hire ES6
Gigs ReactNative
Gigs BeginnerAngularJS
WebDevelopment
ReactandRedux
DesktopApps
FullStackWebDev
MobileApps&Web
PythonandFlask
Databases
Android
Support&Setup
Swift
QA&Test
OnlineCodingCourses
WordPress&CMS
OnlineCodingCourses
Other
WebDevelopment
HowitWorks
RubyonRails
BecomeaCodementor
Swift
AngularJS
SignUp
Python
SignInLearningCenter
0

JavaScriptTutorial

21EssentialJavaScriptInterviewQuestions
#JavaScript#Interview
September17th2015
Tweet

Share

128

10

Markdown

https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

2/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

<center><iframe
src="//www.slidesha
re.net/slideshow/em
bed_code/key/2t5rlg
NYI6xPD1"

Question1
WhatisthedifferencebetweenundefinedandnotdefinedinJavaScript?

InJavaScript,ifyoutrytouseavariablethatdoesn'texistandhasnotbeendeclared,thenJavaScriptwillthrowanerrorvarnameisnotdefined
andscriptwillstopexecuting.However,ifyouusetypeofundeclared_variable,thenitwillreturnundefined.
Beforegettingfurtherintothis,let'sfirstunderstandthedifferencebetweendeclarationanddefinition.
Let'ssayvarxisadeclarationbecauseyouhavenotdefinedwhatvalueitholdsyet,butyouhavedeclareditsexistenceandtheneedformemory
allocation.
>varx;//declaringx
>console.log(x);//output:undefined

Herevarx=1isbothadeclarationanddefinition(alsowecansaywearedoinganinitialisation).Intheexampleabove,thedeclarationand
assignmentofvaluehappeninlineforvariablex.InJavaScript,everyvariableorfunctiondeclarationyoubringtothetopofitscurrentscopeis
calledhoisting.
Theassignmenthappensinorder,sowhenwetrytoaccessavariablethatisdeclaredbutnotdefinedyet,wewillgettheresultundefined.
varx;//Declaration
if(typeofx==='undefined')//Willreturntrue

Ifavariablethatisneitherdeclarednordefined,whenwetrytoreferencesuchavariablewe'dgettheresultnotdefined.
>console.log(y);//Output:ReferenceError:yisnotdefined

https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

3/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

Wanttospeedupyourlearningprocess?LearnJavaScriptwithaLiveExpert

Question2
Whatwillbetheoutputofthecodebelow?
vary=1;
if(functionf(){}){
y+=typeoff;
}
console.log(y);

Theoutputwouldbe1undefined.Theifconditionstatementevaluatesusingeval,soeval(functionf(){})returnsfunctionf(){}(whichistrue).
Therefore,insidetheifstatement,executingtypeoffreturnsundefinedbecausetheifstatementcodeexecutesatruntime,andthestatement
insidetheifconditionisevaluatedduringruntime.
vark=1;
if(1){
eval(functionfoo(){});
k+=typeoffoo;
}
console.log(k);

Thecodeabovewillalsooutput1undefined.
vark=1;
if(1){
functionfoo(){};
k+=typeoffoo;
}
console.log(k);//output1function

Question3
WhatisthedrawbackofcreatingtrueprivatemethodsinJavaScript?

OneofthedrawbacksofcreatingtrueprivatemethodsinJavaScriptisthattheyareverymemoryinefficient,asanewcopyofthemethodwouldbe
createdforeachinstance.
varEmployee=function(name,company,salary){
this.name=name||"";//Publicattributedefaultvalueisnull
this.company=company||"";//Publicattributedefaultvalueisnull
this.salary=salary||5000;//Publicattributedefaultvalueisnull
//Privatemethod
varincreaseSalary=function(){
this.salary=this.salary+1000;
};
//Publicmethod
this.dispalyIncreasedSalary=function(){
increaseSlary();
console.log(this.salary);
};
};
//CreateEmployeeclassobject
varemp1=newEmployee("John","Pluto",3000);
//CreateEmployeeclassobject
varemp2=newEmployee("Merry","Pluto",2000);
//CreateEmployeeclassobject
varemp3=newEmployee("Ren","Pluto",2500);

Hereeachinstancevariableemp1,emp2,emp3hasitsowncopyoftheincreaseSalaryprivatemethod.
So,asarecommendation,dontuseprivatemethodsunlessitsnecessary.

Question4
WhatisaclosureinJavaScript?Provideanexample

Aclosureisafunctiondefinedinsideanotherfunction(calledtheparentfunction),andhasaccesstovariablesthataredeclaredanddefinedinthe
https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

4/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

parentfunctionscope.
Theclosurehasaccesstovariablesinthreescopes:
Variablesdeclaredintheirownscope
Variablesdeclaredinaparentfunctionscope
Variablesdeclaredintheglobalnamespace
varglobalVar="abc";
//Parentselfinvokingfunction
(functionouterFunction(outerArg){//beginofscopeouterFunction
//VariabledeclaredinouterFunctionfunctionscope
varouterFuncVar='x';
//Closureselfinvokingfunction
(functioninnerFunction(innerArg){//beginofscopeinnerFunction
//variabledeclaredininnerFunctionfunctionscope
varinnerFuncVar="y";
console.log(
"outerArg="+outerArg+"\n"+
"outerFuncVar="+outerFuncVar+"\n"+
"innerArg="+innerArg+"\n"+
"innerFuncVar="+innerFuncVar+"\n"+
"globalVar="+globalVar);
}//endofscopeinnerFunction)(5);//Pass5asparameter
}//endofscopeouterFunction)(7);//Pass7asparameter
innerFunctionisclosurethatisdefinedinsideouterFunctionandhasaccesstoallvariablesdeclaredanddefinedintheouterFunctionscope.In
addition,thefunctiondefinedinsideanotherfunctionasaclosurewillhaveaccesstovariablesdeclaredintheglobalnamespace.

Thus,theoutputofthecodeabovewouldbe:
outerArg=7
outerFuncVar=x
innerArg=5
innerFuncVar=y
globalVar=abc

ScheduleaMockInterviewwithaLeadEngineer

Question5
Writeamulfunctionwhichwillproducethefollowingoutputswheninvoked:
javascriptconsole.log(mul(2)(3)(4));//output:24console.log(mul(4)(3)(4));//output:48

Belowistheanswerfollowedbyanexplanationtohowitworks:
functionmul(x){
returnfunction(y){//anonymousfunction
returnfunction(z){//anonymousfunction
returnx*y*z;
};
};
}

Herethemulfunctionacceptsthefirstargumentandreturnsananonymousfunction,whichtakesthesecondparameterandreturnsanother
anonymousfunctionthatwilltakethethirdparameterandreturnthemultiplicationoftheargumentsthathavebeenpassed.
InJavaScript,afunctiondefinedinsideanotheronehasaccesstotheouterfunction'svariables.Therefore,afunctionisafirstclassobjectthatcan
bereturnedbyotherfunctionsaswellandbepassedasanargumentinanotherfunction.
AfunctionisaninstanceoftheObjecttype
Afunctioncanhavepropertiesandhasalinkbacktoitsconstructormethod
Afunctioncanbestoredasavariable
Afunctioncanbepassasaparametertoanotherfunction
Afunctioncanbereturnedfromanotherfunction

Question6
HowtoemptyanarrayinJavaScript?

Forinstance,
https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

5/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

vararrayList=['a','b','c','d','e','f'];

Howcanweemptythearrayabove?
Thereareacouplewayswecanusetoemptyanarray,solet'sdiscussthemall.
Method1

arrayList=[]

AbovecodewillsetthevariablearrayListtoanewemptyarray.Thisisrecommendedifyoudon'thavereferencestotheoriginalarray
arrayListanywhereelse,becauseitwillactuallycreateanew,emptyarray.Youshouldbecarefulwiththismethodofemptyingthearray,because
ifyouhavereferencedthisarrayfromanothervariable,thentheoriginalreferencearraywillremainunchanged.
ForInstance,
vararrayList=['a','b','c','d','e','f'];//Createdarray
varanotherArrayList=arrayList;//ReferencedarrayListbyanothervariable
arrayList=[];//Emptythearray
console.log(anotherArrayList);//Output['a','b','c','d','e','f']
Method2

arrayList.length=0;

Thecodeabovewillcleartheexistingarraybysettingitslengthto0.Thiswayofemptyingthearrayalsoupdatesallthereferencevariablesthat
pointtotheoriginalarray.Therefore,thismethodisusefulwhenyouwanttoupdateallreferencevariablespointingtoarrayList.
ForInstance,
vararrayList=['a','b','c','d','e','f'];//Createdarray
varanotherArrayList=arrayList;//ReferencedarrayListbyanothervariable
arrayList.length=0;//Emptythearraybysettinglengthto0
console.log(anotherArrayList);//Output[]
Method3

arrayList.splice(0,arrayList.length);

Theimplementationabovewillalsoworkperfectly.Thiswayofemptyingthearraywillalsoupdateallthereferencestotheoriginalarray.
vararrayList=['a','b','c','d','e','f'];//Createdarray
varanotherArrayList=arrayList;//ReferencedarrayListbyanothervariable
arrayList.splice(0,arrayList.length);//Emptythearraybysettinglengthto0
console.log(anotherArrayList);//Output[]

Method4
while(arrayList.length){
arrayList.pop();
}

Theimplementationabovecanalsoemptyarrays,butitisusuallynotrecommendedtousethismethodoften.

Question7
Howdoyoucheckifanobjectisanarrayornot?

ThebestwaytofindoutwhetherornotanobjectisaninstanceofaparticularclassistousethetoStringmethodfromObject.prototype:
vararrayList=[1,2,3];

OneofthebestusecasesoftypecheckinganobjectiswhenwedomethodoverloadinginJavaScript.Forexample,let'ssaywehaveamethod
calledgreet,whichtakesonesinglestringandalsoalistofstrings.Tomakeourgreetmethodworkableinbothsituations,weneedtoknowwhat
kindofparameterisbeingpassed.Isitasinglevalueoralistofvalues?
functiongreet(param){
if(){//herehavetocheckwhetherparamisarrayornot
}else{
}
}

However,astheimplementationabovemightnotnecessarilycheckthetypeforarrays,wecancheckforasinglevaluestringandputsomearray
logiccodeintheelseblock.Forexample:
https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

6/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

functiongreet(param){
if(typeofparam==='string'){
}else{
//Ifparamisoftypearraythenthisblockofcodewouldexecute
}
}

Nowit'sfinewecangowitheitheroftheaforementionedtwoimplementations,butwhenwehaveasituationwheretheparametercanbesingle
value,array,andobjecttype,wewillbeintrouble.
Comingbacktocheckingthetypeofanobject,asmentionedpreviouslywecanuseObject.prototype.toString
if(Object.prototype.toString.call(arrayList)==='[objectArray]'){
console.log('Array!');
}

IfyouareusingjQuery,thenyoucanalsousethejQueryisArraymethod:
if($.isArray(arrayList)){
console.log('Array');
}else{
console.log('Notanarray');
}

FYI,jQueryusesObject.prototype.toString.callinternallytocheckwhetheranobjectisanarrayornot.
Inmodernbrowsers,youcanalsouse
Array.isArray(arrayList);
Array.isArrayissupportedbyChrome5,Firefox4.0,IE9,Opera10.5andSafari5

Question8
Whatwillbetheoutputofthefollowingcode?
varoutput=(function(x){
deletex;
returnx;
})(0);
console.log(output);

Theoutputwouldbe0.Thedeleteoperatorisusedtodeletepropertiesfromanobject.Herexisnotanobjectbutalocalvariable.deleteoperators
don'taffectlocalvariables.

Question9
Whatwillbetheoutputofthefollowingcode?
varx=1;
varoutput=(function(){
deletex;
returnx;
})();
console.log(output);

Theoutputwouldbe1.Thedeleteoperatorisusedtodeletethepropertyofanobject.Herexisnotanobject,butratherit'stheglobalvariableof
typenumber.

Question10
Whatwillbetheoutputofthecodebelow?
varx={foo:1};
varoutput=(function(){
deletex.foo;
returnx.foo;
})();
console.log(output);

Theoutputwouldbeundefined.Thedeleteoperatorisusedtodeletethepropertyofanobject.Here,xisanobjectwhichhasthepropertyfoo,and
asitisaselfinvokingfunction,wewilldeletethefoopropertyfromobjectx.Afterdoingso,whenwetrytoreferenceadeletedpropertyfoo,the
https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

7/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

resultisundefined.

Question11
Whatwillbetheoutputofthecodebelow?
varEmployee={
company:'xyz'
}
varemp1=Object.create(Employee);
deleteemp1.company
console.log(emp1.company);

Theoutputwouldbexyz.Here,emp1objecthascompanyasitsprototypeproperty.Thedeleteoperatordoesn'tdeleteprototypeproperty.
emp1objectdoesn'thavecompanyasitsownproperty.Youcantestitconsole.log(emp1.hasOwnProperty('company'));//output:false.
However,wecandeletethecompanypropertydirectlyfromtheEmployeeobjectusingdeleteEmployee.company.Or,wecanalsodeletetheemp1
objectusingthe__proto__propertydeleteemp1.__proto__.company.

Question12
Whatisundefinedx1inJavaScript?
vartrees=["redwood","bay","cedar","oak","maple"];
deletetrees[3];

Whenyourunthecodeaboveandtypeconsole.log(trees);intoyourChromedeveloperconsole,youwillget["redwood","bay","cedar",
undefined1,"maple"].WhenyourunthecodeinFirefox'sbrowserconsole,youwillget["redwood","bay","cedar",undefined,"maple"].
Thus,it'sclearthattheChromebrowserhasitsownwayofdisplayinguninitialisedindexesinarrays.However,whenyouchecktrees[3]===
undefinedinbothbrowsers,youwillgetsimilaroutputastrue.
Note:Pleaserememberyoudonotneedtocheckfortheuninitialisedindexofarrayintrees[3]==='undefined1',asitwillgiveyouanerror.
'undefined1'isjustwayofdisplayinganarray'suninitialisedindexinChrome.

Question13
Whatwillbetheoutputofthecodebelow?
vartrees=["xyz","xxxx","test","ryan","apple"];
deletetrees[3];
console.log(trees.length);

Theoutputwouldbe5.Whenweusethedeleteoperatortodeleteanarrayelement,thearraylengthisnotaffectedfromthis.Thisholdsevenifyou
deletedallelementsofanarrayusingthedeleteoperator.
Inotherwords,whenthedeleteoperatorremovesanarrayelement,thatdeletedelementisnotlongerpresentinarray.Inplaceofvalueatdeleted
indexundefinedx1inchromeandundefinedisplacedattheindex.Ifyoudoconsole.log(trees)output["xyz","xxxx","test",undefined
1,"apple"]inChromeandinFirefox["xyz","xxxx","test",undefined,"apple"].

Question14
Whatwillbetheoutputofthecodebelow?
varbar=true;
console.log(bar+0);
console.log(bar+"xyz");
console.log(bar+true);
console.log(bar+false);

Thecodewilloutput1,"truexyz",2,1.Here'sageneralguidelineforadditionoperators:
Number+Number>Addition
Boolean+Number>Addition
Boolean+Number>Addition
Number+String>Concatenation
String+Boolean>Concatenation
String+String>Concatenation

Question15
https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

8/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

Whatwillbetheoutputofthecodebelow?
varz=1,y=z=typeofy;
console.log(y);

Theoutputwouldbeundefined.Accordingtotheassociativityrule,operatorswiththesameprecedenceareprocessedbasedontheassociativity
propertyoftheoperator.Here,theassociativityoftheassignmentoperatorisRighttoLeft,sotypeofywillevaluatefirst,whichisundefined.It
willbeassignedtoz,andthenywouldbeassignedthevalueofzandthenzwouldbeassignedthevalue1.

Question16
Whatwillbetheoutputofthecodebelow?
//NFE(NamedFunctionExpression
varfoo=functionbar(){return12;};
typeofbar();

TheoutputwouldbeReferenceError.Tomakethecodeabovework,youcanrewriteitasfollows:
Sample1
varbar=function(){return12;};
typeofbar();

or
Sample2
functionbar(){return12;};
typeofbar();

Afunctiondefinitioncanhaveonlyonereferencevariableasitsfunctionname.Insample1,bar'sreferencevariablepointstoanonymousfunction.
Insample2,thefunction'sdefinitionisthenamefunction.
varfoo=functionbar(){
//fooisvisiblehere
//barisvisiblehere
console.log(typeofbar());//Workhere:)
};
//fooisvisiblehere
//barisundefinedhere

Question17
Whatisthedifferencebetweenthefunctiondeclarationsbelow?
varfoo=function(){
//Somecode
};
functionbar(){
//Somecode
};

Themaindifferenceisthefunctionfooisdefinedatruntimewhereasfunctionbarisdefinedatparsetime.Tounderstandthisinbetterway,let's
takealookatthecodebelow:
RunTimefunctiondeclaration
<script>
foo();//CallingfoofunctionherewillgiveanError
varfoo=function(){
console.log("HiIaminsideFoo");
};
</script>
<script>
ParseTimefunctiondeclaration
bar();//CallingfoofunctionwillnotgiveanError
functionbar(){
console.log("HiIaminsideFoo");
};
</script>

Anotheradvantageofthisfirstonewayofdeclarationisthatyoucandeclarefunctionsbasedoncertainconditions.Forexample:
<script>
if(testCondition){//IftestConditionistruethen

https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

9/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

varfoo=function(){
console.log("insideFoowithtestConditionTruevalue");
};
}else{
varfoo=function(){
console.log("insideFoowithtestConditionfalsevalue");
};
}
</script>

However,ifyoutrytorunsimilarcodeusingtheformatbelow,you'dgetanerror:
<script>
if(testCondition){//IftestConditionistruethen
functionfoo(){
console.log("insideFoowithtestConditionTruevalue");
};
}else{
functionfoo(){
console.log("insideFoowithtestConditionfalsevalue");
};
}
</script>

Question18
WhatisfunctionhoistinginJavaScript?

FunctionExpression
varfoo=functionfoo(){
return12;
};

InJavaScript,variableandfunctionsarehoisted.Let'stakefunctionhoistingfirst.Basically,theJavaScriptinterpreterlooksaheadtofindall
variabledeclarationsandthenhoiststhemtothetopofthefunctionwherethey'redeclared.Forexample:
foo();//Herefooisstillundefined
varfoo=functionfoo(){
return12;
};

Behindthesceneofthecodeabovelookslikethis:
javascriptvarfoo=undefined;foo();//Herefooisundefinedfoo=functionfoo(){/Somecodestuff}javascriptvarfoo=
undefined;foo=functionfoo(){/Somecodestuff}foo();//Nowfooisdefinedhere

Question19
Whatwillbetheoutputofcodebelow?
varsalary="1000$";
(function(){
console.log("Originalsalarywas"+salary);
varsalary="5000$";
console.log("MyNewSalary"+salary);
})();

Theoutputwouldbeundefined,5000$.NewbiesoftengettrickedbyJavaScript'shoistingconcept.Inthecodeabove,youmightbeexpecting
salarytoretainitsvaluefromtheouterscopeuntilthepointthatsalarygetsredeclaredintheinnerscope.However,duetohoisting,thesalary
valuewasundefinedinstead.Tounderstandthisbetter,havealookofthecodebelow:
varsalary="1000$";
(function(){
varsalary=undefined;
console.log("Originalsalarywas"+salary);
salary="5000$";
console.log("MyNewSalary"+salary);
})();
salaryvariableishoistedanddeclaredatthetopinthefunction'sscope.Theconsole.loginsidereturnsundefined.Aftertheconsole.log,salaryis
redeclaredandassigned5000$.

https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

10/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

Question20
WhatistheinstanceofoperatorinJavaScript?Whatwouldbetheoutputofthecodebelow?
functionfoo(){
returnfoo;
}
newfoo()instanceoffoo;

Here,instanceofoperatorchecksthecurrentobjectandreturnstrueiftheobjectisofthespecifiedtype.
ForExample:
vardog=newAnimal();
doginstanceofAnimal//Output:true

HeredoginstanceofAnimalistruesincedoginheritsfromAnimal.prototype.
varname=newString("xyz");
nameinstanceofString//Output:true

HerenameinstanceofStringistruesincedoginheritsfromString.prototype.Nowlet'sunderstandthecodebelow:
functionfoo(){
returnfoo;
}
newfoo()instanceoffoo;

Herefunctionfooisreturningfoo,whichagainpointstofunctionfoo.
functionfoo(){
returnfoo;
}
varbar=newfoo();
//herebarispointertofunctionfoo(){returnfoo}.

Sothenewfoo()instanceoffooreturnfalse
RefLink

Question21
IfwehaveaJavaScriptassociativearray
varcounterArray={
A:3,
B:4
};
counterArray["C"]=1;

Howcanwecalculatethelengthoftheaboveassociativearray'scounterArray?

Therearenoinbuiltfunctionsandpropertiesavailabletocalculatethelengthofassociativearrayobjecthere.However,thereareotherwaysby
whichwecancalculatethelengthofanassociativearrayobject.Inadditiontothis,wecanalsoextendanObjectbyaddingamethodorpropertyto
theprototypeinordertocalculatelength.However,extendinganobjectmightbreakenumerationinvariouslibrariesormightcreatecrossbrowser
issues,soit'snotrecommendedunlessit'snecessary.Again,therearevariouswaysbywhichwecancalculatelength.
Objecthasthekeysmethodwhichcanbeusedtocalculatethelengthofanobject:
Object.keys(counterArray).length//Output2

Wecanalsocalculatethelengthofanobjectbyiteratingthroughanobjectandbycountingtheobject'sownproperty.
functiongetSize(object){
varcount=0;
for(keyinobject){
//hasOwnPropertymethodcheckownpropertyofobject
if(object.hasOwnProperty(key))count++;
}
returncount;
}

WecanalsoaddalengthmethoddirectlyonObject:
Object.length=function(){
varcount=0;

https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

11/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

for(keyinobject){
//hasOwnPropertymethodcheckownpropertyofobject
if(object.hasOwnProperty(key))count++;
}
returncount;
}
//Getthesizeofanyobjectusing
console.log(Object.length(counterArray))

Bonus:WecanalsouseUnderscore(recommended,Asit'slightweight)tocalculateobjectlength.

WriteforUs
GetNewTutorials
RSS
Author

NishantKumar
5.0

UIEngineeringLeadBigParser&TechContributor@Mozila
5+Yearsexperiencedsoftwareprofessionalwithexposuretomultipleprogramminglanguagesandarchitecturesandexperienceandunderstanding
of:Buildingscalableproductsandservices...
HiretheAuthor
Questionsaboutthistutorial?GetLive1:1helpfromJavaScriptexperts!

sureshatta
4.9

SrWebandJavaDeveloperbyprofessionandyourfriendbyNature.
Web&Javadeveloperandlovestofixbugs.IbelieveinKarmaandIbelieveinthebelowquote.REALPROGRAMMER'SEYEISA...
HirethisExpert

SakthidharanAshwinP
4.7

AnalystataTopNotchBankintheITdomain
CompletedM101JSCertification,MongoDBforNode.jsDevelopers.OracleCertifiedJavaProfessionalJavaSE6...
HirethisExpert
https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

12/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

OrBecomeaCodementor!

LearnFullStackWebDevelopmentwithMeteorOnline
WithaLiveExpertMentorin4Weeks.
YourEmailAddress
LEARNMORE
RelatedTutorials
HowtoConvertJSONtoMarkdownusingjson2md
AngularJS,Backbone.jsorEmber.jsWhichOnetoChooseforYourProject?
HowtoCreateCrossPlatformDesktopAppswithNW.js
MV*FrameworksOfficeHoursQ&A:REACT.js,AngularDesignPractices,andMore
ShouldYouUseaJavaScriptMVCFrameworktoBuildYourWebApplication?
18Comments

Codementor

Recommend 3

Share

Login

SortbyBest

Jointhediscussion
AdrianMobley 9monthsago

Thisisagreatlistofquestionsandanswers.Thanks!
2

Reply Share

JoannaGeorgescu 8monthsago

ThanksfortheseusefulQ&As.ArewesureObject.keys(counterArray).lengthresultsin2(not3)?IsitbeforecounterArray["C"]=1?
1

Reply Share

HiteshKumar 9daysago

IhavebeentomanyJavaScriptinterview.Noonehasaskedmequestionslikementionedinthispost.Someofthequestionlikewhatis
theoutputforcodeseemslikeanoverkillfora1hourJavaScriptinterview.Usuallypeoplegiveanalgorithmstylequestioniftheyreally
wanttoseeyourcodingskills.Thislookssomethingyoudidforyourownpractice.Thoughsomequestionaboutclosureandhoisting
weregood.

Reply Share

ArvindVyas 3monthsago

Niceone,butfixQ3privatemethodnameisincorrect"increaseSalary"whencallingfrompublicmethod

Reply Share

emmecinque 3monthsago

Thisisterrible.Muchoftheinformationhereiscompletelywrong.Functionexpressionsin"if"conditionsarenotevaluatedwith"eval()"
that'sridiculous."Trueprivate"methodsarenotreallysignificantlyinefficient,sincefunctioninstanceobjectsarenotverylarge(thecode
ofthefunctionisimmutableandthereforecanbesharedbyallinstances).Andonandon.Please,ifyou'relearningJavaScript,ignore
this.

Reply Share

https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

13/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor
mfssharma>emmecinque 3monthsago

@emmecinque:Iwouldhappytoresolveifyoucanpointwhichinformationiswronghere??andalsoIfyoupointmethe
validationforwrongstatementthenitwouldbeawesomesothaticandomedication.

Reply Share

krzysiek 4monthsago

Greatarticle!!However,inquestion16,inlastexampleYoushouldn'tcallbarfunction,just'typeofbar'insteadof'typeofbar()'.Otherwise
Youwillgetinfinitecallstack.

Reply Share

VinodTigadi 4monthsago

HiNishant,it'sanicearticlewithgoodcollectionofquestions,answersandexplanation.
Ihaveonesuggestionforcorrection.FortheQ19,theoutputofthefirstcodewillnotbe'undefined'.Itshouldbe1000$and5000$

Reply Share

Jesus>VinodTigadi 2monthsago

It'sundefinedbecausetheconsole.logareinsideanIIFE,so,JavaScriptwillrun,createthevariableinmemorybutwontgiveita
valueyet,thentheIIFEget'sexecutedinmediatelyandlogsundefined.

Reply Share

mfssharma>VinodTigadi 4monthsago

HeyVinod,
Thanksforyourquery!!
Icheckedtoconfirmyourdoubt,outputiscomingundefinedasitsamementionedinanswer.It'scomingduetosalaryhasbeen
hoistedinsidefunctiondefinition.
Thanks,
Nishant

Reply Share

Shasha 5monthsago

WhatisthedrawbackofcreatingtrueprivatemethodsinJavaScript?
Idontunderstandthepartwhereitsayseachcopyofemp1,emp2,emp3willhaveanowncopyoftheprivatemethod.So,doesntit
supposetohaveanowncopyasyouarecreatinganobject.?Pleaserespond.

Reply Share

mfssharma>Shasha 5monthsago

@shashaIfwecreatemethodonprototypethenIt'sbeingsharedwithalltheinstance.ButIncaseifwedeclareprivatemethod
andvariableinsidefunctionitwillconsistineveryinstance.
1

Reply Share

obouchari>mfssharma 2monthsago

Idon'tthinktheprivatemethod"increaseSalary"willbecreatedforeachinstancebutthepublicmethod
"dispalyIncreasedSalary"will!That'stheoneshouldbeontheprototype.Infactthewayyouarecalling"increaseSalary"
inside"dispalyIncreasedSalary"willreturnanerrorsincethiswillrefertothewrongobject.

Reply Share

Shasha>mfssharma 5monthsago

Afollowuponthis:
1)IsthecodebelowequivalenttocreatingaclassinJavaorC#?
2)DoesJava/C#alsomaintainsaseparatecopyforprivatemethodsineachofitsinstances?
varEmployee=function(name,company,salary){
this.name=name||""//Publicattributedefaultvalueisnull
this.company=company||""//Publicattributedefaultvalueisnull
this.salary=salary||5000//Publicattributedefaultvalueisnull
//SomePrivatemethod
https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

14/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

//SomePublicmethod
}

Reply Share

mfssharma>Shasha 5monthsago

1)No(JavaScriptisnotsimilartoJava/C#itdoesn'tfollowtheOOPSconstructsimilartoanotherOOLanguage
likeJava/C#).
2)InJava/C#privatememberisnotavailableoninstancetoaccess.HoweverIt'shaveowncopyofeveryprivate
member/Publicmemberexceptstaticmember

Reply Share

Jesus>Shasha 2monthsago

Whenyouhavemethodsinsideafunctionconstructorandcreatenewobjectswithit,thenanewmethodiscreatedinsideevery
objectcreatedusingthatfunctionconstructor.Youcanavoidthatandonlyhave1methodforallinstancesofitbydefiningthe
methodinsideit'sprototype.

Reply Share

MaxHo 7monthsago

Object.length=function(){
varcount=0
for(keyinobject){
//hasOwnPropertymethodcheckownpropertyofobject
if(object.hasOwnProperty(key))count++
}
returncount
}
//Getthesizeofanyobjectusing
console.log(Object.length(counterArray))
1.TheObject,lengthfunctiontakesanargumentofobjectwhichismissing
2."length"namedoesn'tseemtowork.Workswhennameischangedtosomethingotherthan"length"
Greatarticle!Thankyou!

Reply Share

TravisMiller 9monthsago

GreatQuestions!

Subscribe

Reply Share

AddDisqustoyoursiteAddDisqusAdd

Privacy

LearnFullStackWebDevelopmentwithMeteorOnline
WithaLiveExpertMentorin4Weeks.
YourEmailAddress
LEARNMORE

https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

15/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

LearnFullStackWebDevelopmentwithMeteorOnlineWithaLiveExpertMentorin4Weeks.
ViewClass

ReceiveNewJavaScriptTutorials
Emailaddress
SignUpNow
NoIdon'twantfreeresourcesfromexpertdevelopers.

ExpertHelp
TOPICS
WebProgrammingCodeMobileAppProgrammingDesign/UXDatabase/OperationsDevelopmentProcess/ToolsViewAll
POPULARCATEGORIES
JavascriptAngularJSRubyonRailsJavaiOSC#PythonAndroidPHP
GIGS
WebDevelopmentDesktopAppsMobileApps&WebDatabasesSupport&SetupQA&TestWordPress&CMSOtherViewAll
LearningCenter
TOPICS
LearnRubyonRailsLearnAngularJSLearnReactLearnPythonLearnAndroidLearnJavascript
RESOURCES
LearningCenterOfficeHoursJavascriptFrameworksTutorialsTipsTutorsCodingBootcamp
Company
INFO
BecomeaCodementorHowItWorksCodementorforBusinessTeamTrainingSuccessStoriesRefactor.ioWhatLanguagetoLearn

SupportJobsBlogDownloadsWriteforUs
Codementor
Instant1:1helpfromexpertdevelopers

Copyright2016Codementor
TermsofService

https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

16/17

6/11/2016

21EssentialJavaScriptInterviewQuestions|Codementor

LearnFullStackWebDevelopmentwithMeteorOnline
WithaLiveExpertMentorin4Weeks.
LearnFullStackWebDevelopmentwithMeteorOnlineWithaLiveExpertMentorin4Weeks.
ViewSyllabus
ViewClass

SignIn
SignUpandGetHelpNow
Emailaddress
IagreetoCodementorterms

Fullname

Newpassword

Signupforfree

WanttobecomeaCodementor?

https://www.codementor.io/javascript/tutorial/21essentialjavascripttechinterviewpracticequestionsanswers

17/17

También podría gustarte