- Notifications
You must be signed in to change notification settings - Fork1.2k
JavaScript interview Questions
License
ganqqwerty/123-Essential-JavaScript-Interview-Questions
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
This book's goal is to help javascript frontend developers prepare for technical job interviews through a collection of carefully compiled questions.
- This Book will be soon completed and then it will be available to buy in paper form. If you want me to send you an early copy of this book, please add your name and email address in thisGoogle Form.
- If you don't want to wait, you can buyYuri's JavaScript Flashcards, a set of frontend interview questions sorted by popularity among interviewers printed on beautiful poker-size flashcards.
Answer
In JavaScript if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an errorvar name is not defined
and the script will stop executing thereafter. But If you usetypeof undeclared_variable
then it will returnundefined
.
Before starting further discussion let's understand the difference between declaration and definition.
var x
is a declaration because we are not defining what value it holds yet, but we are declaring its existence and the need for memory allocation.
varx;// declaring xconsole.log(x);// output: undefined
var x = 1
is both declaration and definition, here declaration and assignment of value happen inline for variable x—what we are doing is called "initialisation". In JavaScript both variable declarations and function declarations go to the top of the scope in which they are declared, then assignment happens—this series of events is called "hoisting".
A variable can be declared but not defined. When we try to access it, It will resultundefined
.
varx;// Declarationtypeofx==='undefined';// Will return true
A variable can be neither declared nor defined. When we try to reference such variable then the result will benot defined
.
console.log(y);// Output: ReferenceError: y is not defined
http://stackoverflow.com/questions/20822022/javascript-variable-definition-declaration
if(x<=100){...}if(!(x>100)){...}
Answer
NaN <= 100
isfalse
andNaN > 100
is alsofalse
, so if thevalue ofx
isNaN
, the statements are not the same.
The same holds true for any value of x that being converted to type Number, returnsNaN
, e.g.:undefined
,[1,2,5]
,{a:22}
, etc.
This is why you need to pay attention when you deal with numeric variables.NaN
can’t be equal, less than or more than any other numeric value, so the only reliable way to check if the value isNaN
, is to use theisNaN()
function.
Answer
One of the drawbacks of declaring methods directly in JavaScript objects is that they are very memory inefficient. When you do that, a new copy of the method is created for each instance of an object. Here's an example:
varEmployee=function(name,company,salary){this.name=name||"";this.company=company||"";this.salary=salary||5000;// We can create a method like this:this.formatSalary=function(){return"$ "+this.salary;};};// Alternatively we can add the method to Employee's prototype:Employee.prototype.formatSalary2=function(){return"$ "+this.salary;}//creating objectsvaremp1=newEmployee('Yuri Garagin','Company 1',1000000);varemp2=newEmployee('Dinesh Gupta','Company 2',1039999);varemp3=newEmployee('Erich Fromm','Company 3',1299483);
In this case each instance variableemp1
,emp2
,emp3
has its own copy of theformatSalary
method. However theformatSalary2
will only be added once toEmployee.prototype
.
Answer
A closure is a function defined inside another function (called parent function) and as such it has access to the variables declared and defined within its parent function's scope.
The closure has access to the variables in three scopes:
- Variable declared in its own scope
- Variable declared in its parent function's scope
- Variable declared in the global namespace
varglobalVar="abc";//Global variable// Parent self-invoking function(functionouterFunction(outerArg){// start of outerFunction's scopevarouterFuncVar='x';// Variable declared in outerFunction's function scope// Closure self-invoking function(functioninnerFunction(innerArg){// start of innerFunction's scopevarinnerFuncVar="y";// variable declared in innerFunction's function scopeconsole.log("outerArg = "+outerArg+"\n"+"outerFuncVar = "+outerFuncVar+"\n"+"innerArg = "+innerArg+"\n"+"innerFuncVar = "+innerFuncVar+"\n"+"globalVar = "+globalVar);// end of innerFunction's scope})(5);// Pass 5 as parameter to our Closure// end of outerFunction's scope})(7);// Pass 7 as parameter to the Parent function
innerFunction
is a closure which is defined insideouterFunction
and consequently has access to all the variables which have been declared and defined withinouterFunction
's scope as well as any variables residing in the program's global scope.
The output of the code above would be:
outerArg=7outerFuncVar=xinnerArg=5innerFuncVar=yglobalVar=abc
console.log(mul(2)(3)(4));// output : 24console.log(mul(4)(3)(4));// output : 48
Answer
functionmul(x){returnfunction(y){// anonymous functionreturnfunction(z){// anonymous functionreturnx*y*z;};};}
Here themul
function accepts the first argument and returns an anonymous function which then takes the second parameter and returns one last anonymous function which finally takes the third and final parameter; the last function then multipliesx
,y
andz
, and returns the result of the operation.
In Javascript, a function defined inside another function has access to the outer function's scope and can consequently return, interact with or pass on to other functions, the variables belonging to the scopes that incapsulate it.
- A function is an instance of the Object type
- A function can have properties and has a link to its constructor method
- A function can be stored as a variable
- A function can be passed as a parameter to another function
- A function can be returned by another function
For instance:
vararrayList=['a','b','c','d','e','f'];
How can we empty the array above?
Answer
There are a couple of ways by which we can empty an array, So let's discuss all the possible way by which we can empty an array.
arrayList=[];
The code above will set the variablearrayList
to a new empty array. This is recommended if you don't havereferences to the original arrayarrayList
anywhere else because It will actually create a new empty array. You should be careful with this way of empty the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged, Only use this way if you have only referenced the array by its original variablearrayList
.
For instance:
vararrayList=['a','b','c','d','e','f'];// Created arrayvaranotherArrayList=arrayList;// Referenced arrayList by another variablearrayList=[];// Empty the arrayconsole.log(anotherArrayList);// Output ['a', 'b', 'c', 'd', 'e', 'f']
arrayList.length=0;
The code above will clear the existing array by setting its length to 0. This way of emptying an array will also update all the reference variables that point to the original array.
For instance:
vararrayList=['a','b','c','d','e','f'];// Created arrayvaranotherArrayList=arrayList;// Referenced arrayList by another variablearrayList.length=0;// Empty the array by setting length to 0console.log(anotherArrayList);// Output []
arrayList.splice(0,arrayList.length);
Above implementation will also work perfectly. This way of empty the array will also update all the references of the original array.
vararrayList=['a','b','c','d','e','f'];// Created arrayvaranotherArrayList=arrayList;// Referenced arrayList by another variablearrayList.splice(0,arrayList.length);// Empty the array by setting length to 0console.log(anotherArrayList);// Output []
while(arrayList.length){arrayList.pop();}
Above implementation can also empty the array. But not recommended to use often.
Answer
The best way to find whether an object is instance of a particular class or not usingtoString
method fromObject.prototype
vararrayList=[1,2,3];
One of the best use cases of type checking of an object is when we do method overloading in JavaScript. To understand this, let's say we have a method calledgreet
which can take a single string and also a list of strings. To make ourgreet
method workable in both situation we need to know what kind of parameter is being passed: is it single value or list of values?
functiongreet(param){if(){// here have to check whether param is array or not}else{}}
However, in the above implementation it might not necessary to check the type of the array, we can check for single value string and put array logic code in else block, let see below code for the same.
functiongreet(param){if(typeofparam==='string'){}else{// If param is of type array then this block of code would execute}}
Now it's fine we can go with the previous two implementations, but when we have a situation like a parameter can besingle value
,array
, andobject
type then we will be in trouble.
Coming back to checking the type of an object, As we mentioned that we can useObject.prototype.toString
if(Object.prototype.toString.call(arrayList)==='[object Array]'){console.log('Array!');}
If you are usingjQuery
then you can also used jQueryisArray
method:
if($.isArray(arrayList)){console.log('Array');}else{console.log('Not an array');}
FYI jQuery usesObject.prototype.toString.call
internally to check whether an object is an array or not.
In modern browser, you can also use:
Array.isArray(arrayList);
Array.isArray
is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5
varoutput=(function(x){deletex;returnx;})(0);console.log(output);
Answer
The code above will output0
as output.delete
operator is used to delete a property from an object. Herex
is not an object, it's alocal variable.delete
operator doesn't affect local variables.
varx=1;varoutput=(function(){deletex;returnx;})();console.log(output);
Answer
The code above will output1
as output.delete
operator is used to delete a property from an object. Herex
is not an object it'sglobal variable of typenumber
.
varx={foo :1};varoutput=(function(){deletex.foo;returnx.foo;})();console.log(output);
Answer
The code above will outputundefined
as output.delete
operator is used to delete a property from an object. Herex
is an object which has foo as a property and from a self-invoking function, we are deleting thefoo
property of objectx
and after deletion, we are trying to reference deleted propertyfoo
which resultundefined
.
varEmployee={company:'xyz'}varemp1=Object.create(Employee);deleteemp1.companyconsole.log(emp1.company);
Answer
The code above will output `xyz` as output. Here `emp1` object got company as **prototype** property. delete operator doesn't delete prototype property.emp1
object doesn't havecompany as its own property. you can test itconsole.log(emp1.hasOwnProperty('company')); //output : false
However, we can delete company property directly fromEmployee
object usingdelete Employee.company
or we can also delete fromemp1
object using__proto__
propertydelete emp1.__proto__.company
.
vartrees=["redwood","bay","cedar","oak","maple"];deletetrees[3];
Answer
- When you run the code above and do `console.log(trees);` in chrome developer console then you will get `["redwood", "bay", "cedar", undefined × 1, "maple"]`. - In the recent versions of Chrome you will see the word `empty` of `undefined x 1`. - When you run the same code in Firefox browser console then you will get `["redwood", "bay", "cedar", undefined, "maple"]`Clearly we can see that Chrome has its own way of displaying uninitialized index in arrays. However when you checktrees[3] === undefined
in any browser you will get similar output astrue
.
Note: Please remember that you need not check for the uninitialized index of the array intrees[3] === 'undefined × 1'
it will give an error because'undefined × 1'
this is just way of displaying an uninitialized index of an array in chrome.
vartrees=["xyz","xxxx","test","ryan","apple"];deletetrees[3];console.log(trees.length);
Answer
The code above will output `5` as output. When we used `delete` operator for deleting an array element then, the array length is not affected by this. This holds even if you deleted all elements of an array using `delete` operator.So when delete operator removes an array element that deleted element is no longer present in the array. In place of value at deleted indexundefined x 1
inchrome andundefined
is placed at the index. If you doconsole.log(trees)
output["xyz", "xxxx", "test", undefined × 1, "apple"]
in Chrome and in Firefox["xyz", "xxxx", "test", undefined, "apple"]
.
varbar=true;console.log(bar+0);console.log(bar+"xyz");console.log(bar+true);console.log(bar+false);
Answer
The code above will output1, "truexyz", 2, 1
as output. Here's a general guideline for the plus operator:
- Number + Number -> Addition
- Boolean + Number -> Addition
- Boolean + Boolean -> Addition
- Number + String -> Concatenation
- String + Boolean -> Concatenation
- String + String -> Concatenation
varz=1,y=z=typeofy;console.log(y);
Answer
The code above will print string"undefined"
as output. According to associativity rule operator with the same precedence are processed based on their associativity property of operator. Here associativity of the assignment operator isRight to Left
so firsttypeof y
will evaluate first which is string"undefined"
and assigned toz
and theny
would be assigned the value of z. The overall sequence will look like that:
varz;z=1;vary;z=typeofy;y=z;
// NFE (Named Function Expression)varfoo=functionbar(){return12;};typeofbar();
Answer
The output will beReference Error
. To fix the bug we can try to rewrite the code a little bit:
Sample 1
varbar=function(){return12;};typeofbar();
or
Sample 2
functionbar(){return12;};typeofbar();
The function definition can have only one reference variable as a function name, Insample 1bar
is reference variable which is pointing toanonymous function
and insample 2 we have function statement andbar
is the function name.
varfoo=functionbar(){// foo is visible here// bar is visible hereconsole.log(typeofbar());// Works here :)};// foo is visible here// bar is undefined here
varfoo=function(){// Some code}
functionbar(){// Some code}
Answer
The main difference is that functionfoo
is defined atrun-time
and is called a function expression, whereas functionbar
is defined atparse time
and is called a function statement. To understand it better, let's take a look at the code below :
// Run-Time function declarationfoo();// Call foo function here, It will give an errorvarfoo=function(){console.log("Hi I am inside Foo");};
// Parse-Time function declarationbar();// Call bar function here, It will not give an Errorfunctionbar(){console.log("Hi I am inside Foo");}
bar();(functionabc(){console.log('something')})();functionbar(){console.log('bar got called')};
Answer
The output will be :
bar got calledsomething
Since the function is called first and defined during parse time the JS engine will try to find any possible parse time definitions and start the execution loop which will mean function is called first even if the definition is post another function.
Answer
Let's take the followingfunction expression
varfoo=functionfoo(){return12;}
In JavaScriptvar
-declared variables and functions arehoisted
. Let's take functionhoisting
first. Basically, the JavaScript interpreter looks ahead to find all the variable declaration and hoists them to the top of the function where it's declared. For example:
foo();// Here foo is still undefinedvarfoo=functionfoo(){return12;};
The code above behind the scene look something like this:
varfoo=undefined;foo();// Here foo is undefinedfoo=functionfoo(){// Some code stuff}
varfoo=undefined;foo=functionfoo(){// Some code stuff}foo();// Now foo is defined here
varsalary="1000$";(function(){console.log("Original salary was "+salary);varsalary="5000$";console.log("My New Salary "+salary);})();
Answer
The code above will output:undefined, 5000$
because of hoisting. In the code presented above, you might be expectingsalary
to retain it values from outer scope until the point thatsalary
was re-declared in the inner scope. But due tohoisting
salary value wasundefined
instead. To understand it better have a look of the following code, heresalary
variable is hoisted and declared at the top in function scope. When we print its value usingconsole.log
the result isundefined
. Afterwards the variable is redeclared and the new value"5000$"
is assigned to it.
varsalary="1000$";(function(){varsalary=undefined;console.log("Original salary was "+salary);salary="5000$";console.log("My New Salary "+salary);})();
Answer
typeof
is an operator that returns a string with the type of whatever you pass.
Thetypeof
operator checks if a value belongs to one of the seven basic types:number
,string
,boolean
,object
,function
,undefined
orSymbol
.
typeof(null)
will returnobject
.
instanceof
is much more intelligent: it works on the level of prototypes. In particular, it tests to see if the right operand appears anywhere in the prototype chain of the left.instanceof
doesn’t work with primitive types. Theinstanceof
operator checks the current object and returns true if the object is of the specified type, for example:
vardog=newAnimal();doginstanceofAnimal;// Output : true
Heredog instanceof Animal
is true sincedog
inherits fromAnimal.prototype
varname=newString("xyz");nameinstanceofString;// Output : true
Ref Link:http://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript
varcounterArray={A :3,B :4};counterArray["C"]=1;
Answer
First of all, in the case of JavaScript an associative array is the same as an object. Secondly, even though there is no built-in function or property available to calculate the length/size an object, we can write such function ourselves.
Object
haskeys
method which can be used to calculate the length of object.
Object.keys(counterArray).length;// Output 3
We can also calculate the length of object by iterating through the object and by doing a count of own property of object. This way we will ignoge the properties that came from the object's prototype chain:
functiongetLength(object){varcount=0;for(keyinobject){// hasOwnProperty method check own property of objectif(object.hasOwnProperty(key))count++;}returncount;}
All modern browsers (including IE9+) support thegetOwnPropertyNames
method, so we can calculate the length using the following code:
Object.getOwnPropertyNames(counterArray).length;// Output 3
Underscore andlodash libraries have the methodsize
dedicated to calculate the object length. We don't recommend to include one of these libraries just to use thesize
method, but if it's already used in your project - why not?
_.size({one:1,two:2,three:3});=>3
Answer
If your are familiar with Object-oriented programming, More likely familiar to thinking of functions, methods, and class constructors as three separate things. But In JavaScript, these are just three different usage patterns of one single construct.
functions : The simplest usages of function call:
functionhelloWorld(name){return"hello world, "+name;}helloWorld("JS Geeks");// "hello world JS Geeks"
Methods in JavaScript are nothing more than object properties that are functions.
varobj={helloWorld :function(){return"hello world, "+this.name;},name:'John Carter'}obj.helloWorld();// // "hello world John Carter"
Notice howhelloWorld
refer tothis
properties of obj. Here it's clear or you might have already understood thatthis
gets bound toobj
. But the interesting point that we can copy a reference to the same functionhelloWorld
in another object and get a difference answer. Let see:
varobj2={helloWorld :obj.helloWorld,name:'John Doe'}obj2.helloWorld();// "hello world John Doe"
You might be wonder what exactly happens in a method call here. Here we call the expression itself determine the binding of thisthis
, The expressionobj2.helloWorld()
looks up thehelloWorld
property of obj and calls it with receiver objectobj2
.
The third use of functions is as constructors. Like function and method,constructors
are defined with function.
functionEmployee(name,age){this.name=name;this.age=age;}varemp1=newEmployee('John Doe',28);emp1.name;// "John Doe"emp1.age;// 28
Unlike function calls and method calls, a constructor callnew Employee('John Doe', 28)
creates a brand new object and passes it as the value ofthis
, and implicitly returns the new object as its result.
The primary role of the constructor function is to initialize the object.
functionUser(name){this.name=name||"JsGeeks";}varperson=newUser("xyz")["location"]="USA";console.log(person);
Answer
The output of above code would be"USA"
. Herenew User("xyz")
creates a brand new object and created propertylocation
on that andUSA
has been assigned to object property location and that has been referenced by the person.
Let saynew User("xyz")
created a object calledfoo
. The value"USA"
will be assigned tofoo["location"]
, but according toECMAScript Specification , pt 12.14.4 the assignment will itself return the rightmost value: in our case it's"USA"
.Then it will be assigned to person.
To better understand what's going on here, try to execute this code in console, line by line:
functionUser(name){this.name=name||"JsGeeks";}varperson;varfoo=newUser("xyz");foo["location"]="USA";// the console will show you that the result of this is "USA"
Answer
It’s a technology that allows your web application to use cached resources first, and provide default experience offline, before getting more data from the network later. This principle is commonly known as Offline First.
Service Workers actively use promises. A Service Worker has to be installed,activated and then it can react on fetch, push and sync events.
As of 2017, Service Workers are not supported in IE and Safari.
Answer
In JS, that difference is quite subtle. A function is a piece of code that is called by name and function itself not associated with any object and not defined inside any object. It can be passed data to operate on (i.e. parameter) and can optionally return data (the return value).
// Function statementfunctionmyFunc(){// Do some stuff;}// Calling the functionmyFunc();
Here myFunc() function call is not associated with object hence not invoked through any object.
A function can take a form of immediately invoked function expression (IIFE):
// Anonymous Self-invoking Function(function(){// Do some stuff;})();
Finally there are also arrow functions:
constmyFunc=arg=>{console.log("hello",arg)}
A method is a piece of code that is called by its name and that is associated with the object. Methods are functions. When you call a method like thisobj1.myMethod()
, the reference toobj1
gets assigned (bound) tothis
variable. In other words, the value ofthis
will beobj1
insidemyMethod
.
Here are some examples of methods:
varobj1={attribute:"xyz",myMethod:function(){// Methodconsole.log(this.attribute);}};// Call the methodobj1.myMethod();
Hereobj1
is an object andmyMethod
is a method which is associated withobj1
.
In ES6 we have classes. There the methods will look like this:
classMyAwesomeClass{myMethod(){console.log("hi there");}}constobj1=newMyAwesomeClass();obj1.myMethod();
Understand: the method is not some kind of special type of a function, and it's not about how you declare a function. It's the way wecall a function. Look at that:
varobj1={prop1:"buddy"};varmyFunc=function(){console.log("Hi there",this);};// let's call myFunc as a function:myFunc();// will output "Hi there undefined" or "Hi there Window"obj1.myMethod=myFunc;//now we're calling myFunc as a method of obj1, so this will point to obj1obj1.myMethod();// will print "Hi there" following with obj1.
Answer
IIFE a function that runs as soon as it's defined. Usually it's anonymous (doesn't have a function name), but it also can be named. Here's an example of IIFE:
(function(){console.log("Hi, I'm IIFE!");})();// outputs "Hi, I'm IIFE!"
So, here's how it works. Remember the difference between function statements (function a () {}
) and function expressions (var a = function() {}
)? So, IIFE is a function expression. To make it an expression we surround our function declaration into the parens. We do it to explicitly tell the parser that it's an expression, not a statement (JS doesn't allow statements in parens).
After the function you can see the two()
braces, this is how we run the function we just declared.
That's it. The rest is details.
The function inside IIFE doesn't have to be anonymous. This one will work perfectly fine and will help to detect your function in a stacktrace during debugging:
(functionmyIIFEFunc(){console.log("Hi, I'm IIFE!");})();// outputs "Hi, I'm IIFE!"
It can take some parameters:
(functionmyIIFEFunc(param1){console.log("Hi, I'm IIFE, "+param1);})("Yuri");// outputs "Hi, I'm IIFE, Yuri!"
Here there value
"Yuri"
is passed to theparam1
of the function.It can return a value:
varresult=(functionmyIIFEFunc(param1){console.log("Hi, I'm IIFE, "+param1);return1;})("Yuri");// outputs "Hi, I'm IIFE, Yuri!"// result variable will contain 1
You don't have to surround the function declaration into parens, although it's the most common way to define IIFE. Instead you can use any of the following forms:
~function(){console.log("hi I'm IIFE")}()
!function(){console.log("hi I'm IIFE")}()
+function(){console.log("hi I'm IIFE")}()
-function(){console.log("hi I'm IIFE")}()
(function(){console.log("hi I'm IIFE")}());
var i = function(){console.log("hi I'm IIFE")}();
true && function(){ console.log("hi I'm IIFE") }();
0, function(){ console.log("hi I'm IIFE") }();
new function(){ console.log("hi I'm IIFE") }
new function(){ console.log("hi I'm IIFE") }()
Please don't use all these forms to impress colleagues, but be prepared that you can encounter them in someone's code.
Variables and functions that you declare inside an IIFE are not visible to the outside world, so you can:
- Use the IIFE for isolating parts of the code to hide details of implementation.
- Specify the input interface of your code by passing commonly used global objects (window, document, jQuery, etc.) IIFE’s parameters, and then reference these global objects within the IIFE via a local scope.
- Use it in closures, when you use closures in loops.
- IIFE is the basis of in the module pattern in ES5code, it helps to prevent polluting the global scope and provide the module interface to the outside.
Answer
The singleton pattern is an often used JavaScript design pattern. It provides a way to wrap the code into a logical unit that can be accessed through a single variable. The Singleton design pattern is used when only one instance of an object is needed throughout the lifetime of an application. In JavaScript, Singleton pattern have many uses, they can be used for NameSpacing, which reduce the number of global variables in your page (prevent from polluting global space), organizing the code in a consistent manner, which increase the readability and maintainability of your pages.
There are two important points in the traditional definition of Singleton pattern:
- There should be only one instance allowed for a class and
- We should allow global point of access to that single instance
Let me define singleton pattern in JavaScript context:
It is an object that is used to create namespace and group together a related set of methods and attributes (encapsulation) and if we allow to initiate then it can be initiated only once.
In JavaScript, we can create singleton though object literal. However, there is some another way but that I will cover in next post.
A singleton object consists of two parts: The object itself, containing the members (Both methods and attributes) within it, and global variable used to access it. The variable is global so that object can be accessed anywhere in the page, this is a key feature of the singleton pattern.
#"auto">As I have already stated above that singleton can be used to declare Namespace in JavaScript. NameSpacing is a large part of responsible programming in JavaScript. Because everything can be overwritten, and it is very easy to wipe out variable by mistake or a function, or even a class without even knowing it. A common example which happens frequently when you are working with another team member parallel,
functionfindUserName(id){}/* Later in the page another programmeradded code */varfindUserName=$('#user_list');/* You are trying to call :( */console.log(findUserName())
One of the best ways to prevent accidentally overwriting variable is to namespace your code within a singleton object.
/* Using Namespace */varMyNameSpace={findUserName :function(id){},// Other methods and attribute go here as well}/* Later in the page another programmeradded code */varfindUserName=$('#user_list');/* You are trying to call and you make this time workable */console.log(MyNameSpace.findUserName());
/* Lazy Instantiation skeleton for a singleton pattern */varMyNameSpace={};MyNameSpace.Singleton=(function(){// Private attribute that holds the single instancevarsingletonInstance;// All of the normal code goes herefunctionconstructor(){// Private membersvarprivateVar1="Nishant";varprivateVar2=[1,2,3,4,5];functionprivateMethod1(){// code stuff}functionprivateMethod1(){// code stuff}return{attribute1 :"Nishant",publicMethod:function(){alert("Nishant");// some code logic}}}return{// public method (Global access point to Singleton object)getInstance:function(){//instance already exist then returnif(!singletonInstance){singletonInstance=constructor();}returnsingletonInstance;}}})();// getting access of publicMethodconsole.log(MyNamespace.Singleton.getInstance().publicMethod());
The singleton implemented above is easy to understand. The singleton class maintains a static reference to the lone singleton instance and return that reference from the static getInstance() method.
Answer
This method is useful if we want to create several similar objects. In the code sample below, we wrote the functionEmployee
and used it as a constructor by calling it with thenew
operator.
functionEmployee(fName,lName,age,salary){this.firstName=fName;this.lastName=lName;this.age=age;this.salary=salary;}// Creating multiple object which have similar property but diff value assigned to object property.varemployee1=newEmployee('John','Moto',24,'5000$');varemployee2=newEmployee('Ryan','Jor',26,'3000$');varemployee3=newEmployee('Andre','Salt',26,'4000$');
Object Literal is best way to create an object and this is used frequently. Below is code sample for create employee object which contains property as well as method.
varemployee={name :'Nishant',salary :245678,getName :function(){returnthis.name;}}
The code sample below is Nested Object Literal, Here address is an object inside employee object.
varemployee={name :'Nishant',salary :245678,address :{addressLine1 :'BITS Pilani',addressLine2 :'Vidya Vihar'.phoneNumber:{workPhone:7098889765,homePhone:1234567898}}}
In the code below, a sample object has been created usingObject
's constructor function.
varemployee=newObject();// Created employee object using new keywords and Object()employee.name='Nishant';employee.getName=function(){returnthis.name;}
Object.create(obj)
will create a new object and set theobj
as its prototype. It’s a modern way to create objects that inherit properties from other objects.Object.create
function doesn’t run the constructor. You can useObject.create(null)
when you don’t want your object to inherit the properties ofObject
.
Question 29. Write a function called deepClone which takes an object and creates a object copy of it.
varnewObject=deepClone(obj);
Answer
functiondeepClone(object){varnewObject={};for(varkeyinobject){if(typeofobject[key]==='object'&&object[key]!==null){newObject[key]=deepClone(object[key]);}else{newObject[key]=object[key];}}returnnewObject;}
Explanation: We have been asked to do deep copy of object so What's basically it's mean ??. Let's understand in this way you have been given an objectpersonalDetail
this object contains some property which again a type of object here as you can seeaddress
is an object andphoneNumber
in side anaddress
is also an object. In simple termpersonalDetail
is nested object(object inside object). So Here deep copy means we have to copy all the property ofpersonalDetail
object including nested object.
varpersonalDetail={name :'Nishant',address :{location:'xyz',zip :'123456',phoneNumber :{homePhone:8797912345,workPhone :1234509876}}}
So when we do deep clone then we should copy every property (including the nested object).
Answer
Suppose we have given an object
person
varperson={name:'Nishant',age :24}
Here theperson
object has aname
andage
property. Now we are trying to access thesalary property which we haven't declared on the person object so while accessing it will return undefined. So how we will ensure whether property is undefined or not before performing some operation over it?
Explanation:
We can usetypeof
operator to check undefined
if(typeofsomeProperty==='undefined'){console.log('something is undefined here');}
Now we are trying to access salary property of person object.
if(typeofperson.salary==='undefined'){console.log("salary is undefined here because we haven't declared");}
Question 31. Write a function calledClone
which takes an object and creates a object copy of it but not copy deep property of object.
varobjectLit={foo :'Bar'};varcloneObj=Clone(obj);// Clone is the function which you have to writeconsole.log(cloneObj===Clone(objectLit));// this should return falseconsole.log(cloneObj==Clone(objectLit));// this should return true
Answer
functionClone(object){varnewObject={};for(varkeyinobject){newObject[key]=object[key];}returnnewObject;}
Answer
We use promises for handling asynchronous interactions in a sequential manner. They are especially useful when we need to do an async operation and THEN do another async operation based on the results of the first one. For example, if you want to request the list of all flights and then for each flight you want to request some details about it. The promise represents the future value. It has an internal state (pending
,fulfilled
andrejected
) and works like a state machine.
A promise object hasthen
method, where you can specify what to do when the promise is fulfilled or rejected.
You can chainthen()
blocks, thus avoiding the callback hell. You can handle errors in thecatch()
block. After a promise is set to fulfilled or rejected state, it becomes immutable.
Also mention that you know about more sophisticated concepts:
async/await
which makes the code appear even more linear- RxJS observables can be viewed as the recyclable promises
Be sure that you can implement the promise, readone of the articles on a topic, and learn the source code of thesimplest promise implementation.
Answer
Let say we haveperson
object with propertyname andage
varperson={name:'Nishant',age:24}
Now we want to check whethername
property exist inperson
object or not ?
In JavaScript object can have own property, in above example name and age is own property of person object. Object also have some of inherited property of base object like toString is inherited property of person object.
So how we will check whether property is own property or inherited property.
Method 1: We can usein
operator on objet to check own property or inherited property.
console.log('name'inperson);// checking own property print trueconsole.log('salary'inperson);// checking undefined property print false
in
operator also look into inherited property if it doesn't find property defined as own property. For instance If I check existence of toString property as we know that we haven't declared this property on person object soin
operator look into there base property.
Here
console.log('toString'inperson);// Will print true
If we want to test property of object instance not inherited properties then we will usehasOwnProperty
method of object instance.
console.log(person.hasOwnProperty('toString'));// print falseconsole.log(person.hasOwnProperty('name'));// print trueconsole.log(person.hasOwnProperty('salary'));// print false
Answer
NaN
stands for “not a number.” and it can break your table of numbers when it has an arithmetic operation that is not allowed. Here are some examples of how you can getNaN
:
Math.sqrt(-5);Math.log(-1);parseFloat("foo");/* this is common: you get JSON from the server, convert some strings from JSON to a number and end up with NaN in your UI. */
NaN
is not equal to any number, it’s not less or more than any number, also it's not equal to itself:
NaN!==NaNNaN<2// falseNaN>2// falseNaN===2// false
To check if the current value of the variable is NaN, you have to use theisNaN
function. This is why we can often see NaN in the webpages: it requires special check which a lot of developers forget to do.
Further reading:great blogpost on ariya.io
vararr=[10,32,65,2];for(vari=0;i<arr.length;i++){setTimeout(function(){console.log('The index of this number is: '+i);},3000);}
Answer
For ES6, you can just replacevar i
withlet i
.
For ES5, you need to create a function scope like here:
vararr=[10,32,65,2];for(vari=0;i<arr.length;i++){setTimeout(function(j){returnfunction(){console.log('The index of this number is: '+j)};}(i),3000);}
This can also achieve by forEach (allows you to keep that variable within the forEach’s scope)
vararr=[10,32,65,2];arr.forEach(function(ele,i){setTimeout(function(){console.log('The index of this number is: '+i);},3000);})
Answer
We always encounter in such situation where we need to know whether value is type of array or not.
For instance : the code below perform some operation based value type
function(value){if("value is an array"){// Then perform some operation}else{// otherwise}}
Let's discuss some way to detect an array in JavaScript.
Method 1:
Juriy Zaytsev (Also known as kangax) proposed an elegant solution to this.
functionisArray(value){returnObject.prototype.toString.call(value)==='[object Array]';}
This approach is most popular way to detecting a value of type array in JavaScript and recommended to use. This approach relies on the fact that, native toString() method on a given value produce a standard string in all browser.
Method 2:
Duck typing test for array type detection
// Duck typing arraysfunctionisArray(value){returntypeofvalue.sort==='function';}
As we can see above isArray method will return true if value object havesort
method of typefunction
. Now assume you have created a object with sort method
varbar={sort:function(){// Some code}}
Now when you checkisArray(bar)
then it will return true because bar object has sort method, But the fact is bar is not an array.
So this method is not a best way to detect an array as you can see it's not handle the case when some object has sort method.
Method 3:
ECMAScript 5 has introducedArray.isArray() method to detect an array type value. The sole purpose of this method is accurately detecting whether a value is an array or not.
In many JavaScript libraries you may see the code below for detecting an value of type array.
function(value){// ECMAScript 5 featureif(typeofArray.isArray==='function'){returnArray.isArray(value);}else{returnObject.prototype.toString.call(value)==='[object Array]';}}
Method 4:
You can query the constructor name:
functionisArray(value){returnvalue.constructor.name==="Array";}
Method 5:
You check if a given value is aninstanceof Array
:
functionisArray(value){returnvalueinstanceofArray;}
Answer
In Javascript Object are called as reference type, Any value other then primitive is definitely a reference type. There are several built-in reference type such asObject,Array,Function,Date,null andError.
Detecting object usingtypeof
operator
console.log(typeof{});// objectconsole.log(typeof[]);// objectconsole.log(typeofnewArray());// objectconsole.log(typeofnull);// objectconsole.log(typeofnewRegExp());// objectconsole.log(typeofnewDate());// object
But the downside of using typeof operator to detect an object is that typeof returnsobject
fornull
(However this is fact that null is an object in JavaScript).
The best way to detect an object of specific reference type usinginstanceof
operator.
Syntax :value instanceofconstructor
//Detecting an arrayif(valueinstanceofArray){console.log("value is type of array");}
// Employee constructor functionfunctionEmployee(name){this.name=name;// Public property}varemp1=newEmployee('John');console.log(emp1instanceofEmployee);// true
instanceof
not only check the constructor which is used to create an object but also check it's prototype chain see below example.
console.log(emp1instanceofObject);// true
Answer
The ECMAScript 5Object.create() method is the easiest way for one object to inherit from another, without invoking a constructor function.
For instance:
varemployee={name:'Nishant',displayName:function(){console.log(this.name);}};varemp1=Object.create(employee);console.log(emp1.displayName());// output "Nishant"
In the example above, we create a new objectemp1
that inherits fromemployee
. In other wordsemp1
's prototype is set toemployee
. After this emp1 is able to access the same properties and method on employee until new properties or method with the same name are defined.
For instance: DefiningdisplayName()
method onemp1
will not automatically override the employeedisplayName
.
emp1.displayName=function(){console.log('xyz-Anonymous');};employee.displayName();//Nishantemp1.displayName();//xyz-Anonymous
In addition to thisObject.create(
) method also allows to specify a second argument which is an object containing additional properties and methods to add to the new object.
For example
varemp1=Object.create(employee,{name:{value:"John"}});emp1.displayName();// "John"employee.displayName();// "Nishant"
In the example above,emp1
is created with it's own value for name, so callingdisplayName() method will display"John"
instead of"Nishant"
.
Object created in this manner give you full control over newly created object. You are free to add, remove any properties and method you want.
Answer
Let say we havePerson
class which has name, age, salary properties andincrementSalary() method.
functionPerson(name,age,salary){this.name=name;this.age=age;this.salary=salary;this.incrementSalary=function(byValue){this.salary=this.salary+byValue;};}
Now we wish to create Employee class which contains all the properties of Person class and wanted to add some additional properties into Employee class.
functionEmployee(company){this.company=company;}//Prototypal InheritanceEmployee.prototype=newPerson("Nishant",24,5000);
In the example above,Employee type inherits fromPerson. It does so by assigning a new instance ofPerson
toEmployee
prototype. After that, every instance ofEmployee
inherits its properties and methods fromPerson
.
//Prototypal InheritanceEmployee.prototype=newPerson("Nishant",24,5000);varemp1=newEmployee("Google");console.log(emp1instanceofPerson);// trueconsole.log(emp1instanceofEmployee);// true
Let's understand Constructor inheritance
//Defined Person classfunctionPerson(name){this.name=name||"Nishant";}varobj={};// obj inherit Person class properties and methodPerson.call(obj);// constructor inheritanceconsole.log(obj);// Object {name: "Nishant"}
Here we saw callingPerson.call(obj) define the name properties fromPerson
toobj
.
console.log(nameinobj);// true
Type-based inheritance is best used with developer defined constructor function rather than natively in JavaScript. In addition to this also allows flexibility in how we create similar type of object.
Answer
ECMAScript 5 introduce several methods to prevent modification of object which lock down object to ensure that no one, accidentally or otherwise, change functionality of Object.
There are three levels of preventing modification:
1: Prevent extensions :
No new properties or methods can be added to the object, but one can change the existing properties and method.
For example:
varemployee={name:"Nishant"};// lock the objectObject.preventExtensions(employee);// Now try to change the employee object property nameemployee.name="John";// work fine//Now try to add some new property to the objectemployee.age=24;// fails silently unless it's inside the strict mode
2: Seal :
It is same as prevent extension, in addition to this also prevent existing properties and methods from being deleted.
To seal an object, we useObject.seal() method. you can check whether an object is sealed or not usingObject.isSealed();
varemployee={name:"Nishant"};// Seal the objectObject.seal(employee);console.log(Object.isExtensible(employee));// falseconsole.log(Object.isSealed(employee));// truedeleteemployee.name// fails silently unless it's in strict mode// Trying to add new property will give an erroremployee.age=30;// fails silently unless in strict mode
when an object is sealed, its existing properties and methods can't be removed. Sealed object are also non-extensible.
3: Freeze :
Same as seal, In addition to this prevent existing properties methods from being modified (All properties and methods are read only).
To freeze an object, use Object.freeze() method. We can also determine whether an object is frozen using Object.isFrozen();
varemployee={name:"Nishant"};//Freeze the objectObject.freeze(employee);// Seal the objectObject.seal(employee);console.log(Object.isExtensible(employee));// falseconsole.log(Object.isSealed(employee));// trueconsole.log(Object.isFrozen(employee));// trueemployee.name="xyz";// fails silently unless in strict modeemployee.age=30;// fails silently unless in strict modedeleteemployee.name// fails silently unless it's in strict mode
Frozen objects are considered both non-extensible and sealed.
Recommended:
If you are decided to prevent modification, sealed, freeze the object then use in strict mode so that you can catch the error.
For example:
"use strict";varemployee={name:"Nishant"};//Freeze the objectObject.freeze(employee);// Seal the objectObject.seal(employee);console.log(Object.isExtensible(employee));// falseconsole.log(Object.isSealed(employee));// trueconsole.log(Object.isFrozen(employee));// trueemployee.name="xyz";// fails silently unless in strict modeemployee.age=30;// fails silently unless in strict modedeleteemployee.name;// fails silently unless it's in strict mode
Question 41. Write a log function which will add prefix(your message)
to every message you log using console.log ?
For example, If you logconsole.log("Some message")
then output should be(your message) Some message
Answer
Logging error message or some informative message is always required when you dealing with client side JavaScript using console.log method. Some time you want to add some prefix to identify message generated log from your application hence you would like to prefix your app name in every console.log.
A general way to do this keep adding your app name in every console.log message like
console.log('your app name'+'some error message');
But doing in this way you have to write your app name everytime when you log message using console.
There are some best way we can achieve this
functionappLog(){varargs=Array.prototype.slice.call(arguments);args.unshift('your app name');console.log.apply(console,args);}appLog("Some error message");//output of above console: 'your app name Some error message'
For example: We can create string using string literal and using String constructor function.
// using string literalvarltrlStr="Hi I am string literal";// using String constructor functionvarobjStr=newString("Hi I am string object");
Answer
We can use typeof operator to test string literal and instanceof operator to test String object.
functionisString(str){returntypeof(str)=='string'||strinstanceofString;}varltrlStr="Hi I am string literal";varobjStr=newString("Hi I am string object");console.log(isString(ltrlStr));// trueconsole.log(isString(objStr));// true
Answer
Anonymous functions basically used in following scenario.
No name is needed if function is only used in one place, then there is no need to add a name to function.
Let's take the example of setTimeout function
setTimeout(function(){alert("Hello");},1000);
Here there is no need of using named function when we are sure that function which will alert
hello
would use only once in application.Anonymous functions are declared inline and inline functions have advantages in the case that they can access variable in the parent scopes.
Let's take a example of event handler. Notify event of particular type (such as click) for a given object.
Let say we have HTML element (button) on which we want to add click event and when user do click on button we would like to execute some logic.
<buttonid="myBtn"></button>
Add Event Listener
varbtn=document.getElementById('myBtn');btn.addEventListener('click',function(){alert('button clicked');});
Above example shows used of anonymous function as a callback function in event handler.
Passing anonymous function as a parameter to calling function.
Example:
// Function which will execute callback functionfunctionprocessCallback(callback){if(typeofcallback==='function'){callback();}}// Call function and pass anonymous function as callbackprocessCallback(function(){alert("Hi I am anonymous callback function");});
The best way to make a decision for using anonymous function is to ask the following question:
Will the function which I am going to define, be used anywhere else?
If your answer is yes then go and create named function rather anonymous function.
Advantage of using anonymous function:
- It can reduce a bit of code, particularly in recursive function and in callback function.
- Avoid needless global namespace pollutions.
Answer
If you are coming from python/c# you might be using default value for function parameter incase value(formal parameter) has not been passed. For instance :
//DefinesentEmailfunction//configuration :Configurationobject//provider :EmailServiceprovider,DefaultwouldbegmaildefsentEmail(configuration,provider='Gmail'):# Your code logic
In Pre ES6/ES2015
There are a lot of ways by which you can achieve this in pre ES2015.
Let's understand the code below by which we achieved setting default parameter value.
Method 1: Setting default parameter value
functionsentEmail(configuration,provider){// Set default value if user has not passed value for providerprovider=typeofprovider!=='undefined' ?provider :'Gmail'// Your code logic;}// In this call we are not passing provider parameter valuesentEmail({from:'xyz@gmail.com',subject:'Test Email'});// Here we are passing Yahoo Mail as a provider valuesentEmail({from:'xyz@gmail.com',subject:'Test Email'},'Yahoo Mail');
Method 2: Setting default parameter value
functionsentEmail(configuration,provider){// Set default value if user has not passed value for providerprovider=provider||'Gmail'// Your code logic;}// In this call we are not passing provider parameter valuesentEmail({from:'xyz@gmail.com',subject:'Test Email'});// Here we are passing Yahoo Mail as a provider valuesentEmail({from:'xyz@gmail.com',subject:'Test Email'},'Yahoo Mail');
Method 3: Setting default parameter value in ES6
functionsendEmail(configuration,provider="Gmail"){// Set default value if user has not passed value for provider// Value of provider can be accessed directlyconsole.log(`Provider:${provider}`);}// In this call we are not passing provider parameter valuesentEmail({from:'xyz@gmail.com',subject:'Test Email'});// Here we are passing Yahoo Mail as a provider valuesentEmail({from:'xyz@gmail.com',subject:'Test Email'},'Yahoo Mail');
Let say you have two objects
varperson={name :'John',age :24}varaddress={addressLine1 :'Some Location x',addressLine2 :'Some Location y',city :'NewYork'}
Write merge function which will take two object and add all the own property of second object into first object.
Answer
merge(person,address);/* Now person should have 5 propertiesname , age , addressLine1 , addressLine2 , city */
Method 1: Using ES6, Object.assign method
constmerge=(toObj,fromObj)=>Object.assign(toObj,fromObj);
Method 2: Without using built-in function
functionmerge(toObj,fromObj){// Make sure both of the parameter is an objectif(typeoftoObj==='object'&&typeoffromObj==='object'){for(varproinfromObj){// Assign only own properties not inherited propertiesif(fromObj.hasOwnProperty(pro)){// Assign property and valuetoObj[pro]=fromObj[pro];}}}else{throw"Merge function can apply only on object";}}
Answer
Object can have properties that don't show up when you iterate through object using for...in loop or using Object.keys() to get an array of property names. This properties is know as non-enumerable properties.
Let say we have following object
varperson={name:'John'};person.salary='10000$';person['country']='USA';console.log(Object.keys(person));// ['name', 'salary', 'country']
As we know that person object propertiesname
,salary
,country
are enumerable hence it's shown up when we called Object.keys(person).
To create a non-enumerable property we have to useObject.defineProperty(). This is a special method for creating non-enumerable property in JavaScript.
varperson={name:'John'};person.salary='10000$';person['country']='USA';// Create non-enumerable propertyObject.defineProperty(person,'phoneNo',{value :'8888888888',enumerable:false})Object.keys(person);// ['name', 'salary', 'country']
In the example abovephoneNo
property didn't show up because we made it non-enumerable by settingenumerable:false
Bonus
Now let's try to change value ofphoneNo
person.phoneNo='7777777777';
Object.defineProperty() also lets you create read-only properties as we saw above, we are not able to modify phoneNo value of a person object. This is because descriptor haswritable property, which isfalse
by default. Changing non-writable property value will return error in strict mode. In non-strict mode it won't through any error but it won't change the value of phoneNo.
Answer
Function binding falls in advance JavaScript category and this is very popular technique to use in conjunction with event handler and callback function to preserve code execution context while passing function as a parameter.
Let's consider the following example:
varclickHandler={message:'click event handler',handleClick:function(event){console.log(this.message);}};varbtn=document.getElementById('myBtn');// Add click event to btnbtn.addEventListener('click',clickHandler.handleClick);
Here in this example clickHandler object is created which contain message properties and handleClick method.
We have assigned handleClick method to a DOM button, which will be executed in response of click. When the button is clicked, then handleClick method is being called and console message. Here console.log should log theclick event handler
message but it actually logundefined
.
The problem of displayingundefined
is because of the execution context of clickHandler.handleClick method is not being saved hencethis
pointing to buttonbtn
object. We can fix this issue using bind method.
varclickHandler={message:'click event handler',handleClick:function(event){console.log(this.message);}};varbtn=document.getElementById('myBtn');// Add click event to btn and bind the clickHandler objectbtn.addEventListener('click',clickHandler.handleClick.bind(clickHandler));
bind
method is available to all the function similar to call and apply method which take argument value ofthis
.
Answer
- Part I Callbackhell.
- Calling one callback function inside another and so on is callbackhell.
- First we are defining three functions addTen, subFive and mulTwo.
- These three functions while called with a number, will return a callback.
- The callback function will return either result or error.
constaddTen=(num,callback)=>{returncallback(num+10,false)}
constsubFive=(num,callback)=>{returncallback(num-5,false)}
constmulTwo=(num,callback)=>{returncallback(num*2,false)}
- Now lets call these one by one in nested way.
- The result of previous will serve as input for next callback.
constans=addTen(5,(addRes,addErr)=>{// addRess = 15if(!addErr){returnsubFive(addRes,(subRes,subErr)=>{//subRes = 10if(!subErr){returnmulTwo(subRes,(mulRes,mulErr)=>{if(!mulErr){returnmulRes;//20}})}})}})console.log(ans);// 20
- Part II Promise.
- Promise has two parameters resolve and reject.
- Rewrting those three function definations as well, without a callback.
constaddTen=(num)=>{returnnum+10}
constsubFive=(num)=>{returnnum-5}
constmulTwo=(num)=>{returnnum*2}
- Creating a promise.
constpromise=newPromise((resolve,reject)=>{if(true)resolve(5)elsereject("Something went wrong ")})
- Calling those three functions one by one.
- "then" will keep on returning the result and if any error "catch" will catch it.
promise.then(addTen).then(subFive).then(mulTwo).then((ans)=>{console.log(ans)}).catch((err)=>{console.log(err)});
- Part III Async / Await.
- It actually uses promise internally.
constaddTen=(num)=>{returnnewPromise((resolve,reject)=>{resolve(num+10)})}
constsubFive=(num)=>{returnnewPromise((resolve,reject)=>{resolve(num-5)})}
constmulTwo=(num)=>{returnnewPromise((resolve,reject)=>{resolve(num*2)})}
- Put Async keyword before function name and Await before the statments inside the function
- Await will make the later code wait until the result of that statement is returned.
- Always put this inside a try/catch block.
constans=async(num)=>{try{varaddRes=awaitaddTen(num);varsubRes=awaitsubFive(addRes);varmulRes=awaitmulTwo(subRes);console.log(mulRes)}catch(err){console.log(err)}}ans(5)
For a JS developer, it's crucially important to understand which values are passed by reference,and which ones are passed by value. Remember that objects, including arrays are passed by referencewhile strings, booleans and numbers are passed by value.
varstrA="hi there";varstrB=strA;strB="bye there!";console.log(strA)
Answer
The output will be'hi there'
because we're dealing with strings here. Strings arepassed by value, that is, copied.
varobjA={prop1:42};varobjB=objA;objB.prop1=90;console.log(objA)
Answer
The output will be{prop1: 90}
because we're dealing with objects here. Objects arepassed by reference, that is,objA
andobjB
point to the same object in memory.
varobjA={prop1:42};varobjB=objA;objB={};console.log(objA)
Answer
The output will be{prop1: 42}
.
When we assignobjA
toobjB
, theobjB
variable will pointto the same object as theobjB
variable.
However, when we reassignobjB
to an empty object, we simply change whereobjB
variable references to.This doesn't affect whereobjA
variable references to.
vararrA=[0,1,2,3,4,5];vararrB=arrA;arrB[0]=42;console.log(arrA)
Answer
The output will be[42,1,2,3,4,5]
.
Arrays are object in JavaScript and they are passed and assigned by reference. This is whybotharrA
andarrB
point to the same array[0,1,2,3,4,5]
. That's why changing the firstelement of thearrB
will also modifyarrA
: it's the same array in the memory.
vararrA=[0,1,2,3,4,5];vararrB=arrA.slice();arrB[0]=42;console.log(arrA)
Answer
The output will be[0,1,2,3,4,5]
.
Theslice
function copies all the elements of the array returning the new array. That's whyarrA
andarrB
reference two completely different arrays.
vararrA=[{prop1:"value of array A!!"},{someProp:"also value of array A!"},3,4,5];vararrB=arrA;arrB[0].prop1=42;console.log(arrA);
Answer
The output will be[{prop1: 42}, {someProp: "also value of array A!"}, 3,4,5]
.
Arrays are object in JS, so both varaibles arrA and arrB point to the same array. ChangingarrB[0]
is the same as changingarrA[0]
vararrA=[{prop1:"value of array A!!"},{someProp:"also value of array A!"},3,4,5];vararrB=arrA.slice();arrB[0].prop1=42;arrB[3]=20;console.log(arrA);
Answer
The output will be[{prop1: 42}, {someProp: "also value of array A!"}, 3,4,5]
.
Theslice
function copies all the elements of the array returning the new array. However,it doesn't do deep copying. Instead it does shallow copying. You can imagine slice implemented like this:
functionslice(arr){varresult=[];for(i=0;i<arr.length;i++){result.push(arr[i]);}returnresult;}
Look at the line withresult.push(arr[i])
. Ifarr[i]
happens to be a number or string,it will be passed by value, in other words, copied. Ifarr[i]
is an object, it will be passed by reference.
In case of our arrayarr[0]
is an object{prop1: "value of array A!!"}
. Only the referenceto this object will be copied. This effectively means that arrays arrA and arrB share firsttwo elements.
This is why changing the property ofarrB[0]
inarrB
will also change thearrA[0]
.
- Some Value
- Undefined
- Type Error
- ReferenceError: employeeId is not defined
Answer
- ReferenceError: employeeId is not defined
console.log(employeeId);varemployeeId='19000';
- Some Value
- undefined
- Type Error
- ReferenceError: employeeId is not defined
Answer
- undefined
varemployeeId='1234abe';(function(){console.log(employeeId);varemployeeId='122345';})();
- '122345'
- undefined
- Type Error
- ReferenceError: employeeId is not defined
Answer
- undefined
varemployeeId='1234abe';(function(){console.log(employeeId);varemployeeId='122345';(function(){varemployeeId='abc1234';}());}());
- '122345'
- undefined
- '1234abe'
- ReferenceError: employeeId is not defined
Answer
- undefined
(function(){console.log(typeofdisplayFunc);vardisplayFunc=function(){console.log("Hi I am inside displayFunc");}}());
- undefined
- function
- 'Hi I am inside displayFunc'
- ReferenceError: displayFunc is not defined
Answer
- undefined
varemployeeId='abc123';functionfoo(){employeeId='123bcd';return;}foo();console.log(employeeId);
- undefined
- '123bcd'
- 'abc123'
- ReferenceError: employeeId is not defined
Answer
- '123bcd'
varemployeeId='abc123';functionfoo(){employeeId='123bcd';return;functionemployeeId(){}}foo();console.log(employeeId);
- undefined
- '123bcd'
- 'abc123'
- ReferenceError: employeeId is not defined
Answer
- 'abc123'
varemployeeId='abc123';functionfoo(){employeeId();return;functionemployeeId(){console.log(typeofemployeeId);}}foo();
- undefined
- function
- string
- ReferenceError: employeeId is not defined
Answer
- 'function'
functionfoo(){employeeId();varproduct='Car';return;functionemployeeId(){console.log(product);}}foo();
- undefined
- Type Error
- 'Car'
- ReferenceError: product is not defined
Answer
- undefined
(functionfoo(){bar();functionbar(){abc();console.log(typeofabc);}functionabc(){console.log(typeofbar);}}());
- undefined undefined
- Type Error
- function function
- ReferenceError: bar is not defined
Answer
- function function
(function(){'use strict';varperson={name:'John'};person.salary='10000$';person['country']='USA';Object.defineProperty(person,'phoneNo',{value:'8888888888',enumerable:true})console.log(Object.keys(person));})();
- Type Error
- undefined
- ["name", "salary", "country", "phoneNo"]
- ["name", "salary", "country"]
Answer
- ["name", "salary", "country", "phoneNo"]
(function(){'use strict';varperson={name:'John'};person.salary='10000$';person['country']='USA';Object.defineProperty(person,'phoneNo',{value:'8888888888',enumerable:false})console.log(Object.keys(person));})();
- Type Error
- undefined
- ["name", "salary", "country", "phoneNo"]
- ["name", "salary", "country"]
Answer
- ["name", "salary", "country"]
(function(){varobjA={foo:'foo',bar:'bar'};varobjB={foo:'foo',bar:'bar'};console.log(objA==objB);console.log(objA===objB);}());
- false true
- false false
- true false
- true true
Answer
- false false
(function(){varobjA=newObject({foo:"foo"});varobjB=newObject({foo:"foo"});console.log(objA==objB);console.log(objA===objB);}());
- false true
- false false
- true false
- true true
Answer
- false false
(function(){varobjA=Object.create({foo:'foo'});varobjB=Object.create({foo:'foo'});console.log(objA==objB);console.log(objA===objB);}());
- false true
- false false
- true false
- true true
Answer
- false false
(function(){varobjA=Object.create({foo:'foo'});varobjB=Object.create(objA);console.log(objA==objB);console.log(objA===objB);}());
- false true
- false false
- true false
- true true
Answer
- false false
(function(){varobjA=Object.create({foo:'foo'});varobjB=Object.create(objA);console.log(objA.toString()==objB.toString());console.log(objA.toString()===objB.toString());}());
- false true
- false false
- true false
- true true
Answer
- true true
(function(){varobjA=Object.create({foo:'foo'});varobjB=objA;console.log(objA==objB);console.log(objA===objB);console.log(objA.toString()==objB.toString());console.log(objA.toString()===objB.toString());}());
- true true true false
- true false true true
- true true true true
- true true false false
Answer
- true true true true
(function(){varobjA=Object.create({foo:'foo'});varobjB=objA;objB.foo='bar';console.log(objA.foo);console.log(objB.foo);}());
- foo bar
- bar bar
- foo foo
- bar foo
Answer
- bar bar
(function(){varobjA=Object.create({foo:'foo'});varobjB=objA;objB.foo='bar';deleteobjA.foo;console.log(objA.foo);console.log(objB.foo);}());
- foo bar
- bar bar
- foo foo
- bar foo
Answer
- foo foo
(function(){varobjA={foo:'foo'};varobjB=objA;objB.foo='bar';deleteobjA.foo;console.log(objA.foo);console.log(objB.foo);}());
- foo bar
- undefined undefined
- foo foo
- undefined bar
Answer
- undefined undefined
(function(){vararray=newArray('100');console.log(array);console.log(array.length);}());
- undefined undefined
- [undefined × 100] 100
- ["100"] 1
- ReferenceError: array is not defined
Answer
- ["100"] 1
(function(){vararray1=[];vararray2=newArray(100);vararray3=newArray(['1',2,'3',4,5.6]);console.log(array1);console.log(array2);console.log(array3);console.log(array3.length);}());
- [] [] [Array[5]] 1
- [] [undefined × 100] Array[5] 1
- [] [] ['1',2,'3',4,5.6] 5
- [] [] [Array[5]] 5
Answer
- [] [] [Array[5]] 1
(function(){vararray=newArray('a','b','c','d','e');array[10]='f';deletearray[10];console.log(array.length);}());
- 11
- 5
- 6
- undefined
Answer
- 11
(function(){varanimal=['cow','horse'];animal.push('cat');animal.push('dog','rat','goat');console.log(animal.length);})();
- 4
- 5
- 6
- undefined
Answer
- 6
(function(){varanimal=['cow','horse'];animal.push('cat');animal.unshift('dog','rat','goat');console.log(animal);})();
- [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ]
- [ 'cow', 'horse', 'cat', 'dog', 'rat', 'goat' ]
- Type Error
- undefined
Answer
- [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ]
(function(){vararray=[1,2,3,4,5];console.log(array.indexOf(2));console.log([{name:'John'},{name :'John'}].indexOf({name:'John'}));console.log([[1],[2],[3],[4]].indexOf([3]));console.log("abcdefgh".indexOf('e'));})();
- 1 -1 -1 4
- 1 0 -1 4
- 1 -1 -1 -1
- 1 undefined -1 4
Answer
- 1 -1 -1 4
(function(){vararray=[1,2,3,4,5,1,2,3,4,5,6];console.log(array.indexOf(2));console.log(array.indexOf(2,3));console.log(array.indexOf(2,10));})();
- 1 -1 -1
- 1 6 -1
- 1 1 -1
- 1 undefined undefined
Answer
- 1 6 -1
(function(){varnumbers=[2,3,4,8,9,11,13,12,16];vareven=numbers.filter(function(element,index){returnelement%2===0;});console.log(even);varcontainsDivisibleby3=numbers.some(function(element,index){returnelement%3===0;});console.log(containsDivisibleby3);})();
- [ 2, 4, 8, 12, 16 ] [ 0, 3, 0, 0, 9, 0, 12]
- [ 2, 4, 8, 12, 16 ] [ 3, 9, 12]
- [ 2, 4, 8, 12, 16 ] true
- [ 2, 4, 8, 12, 16 ] false
Answer
- [ 2, 4, 8, 12, 16 ] true
(function(){varcontainers=[2,0,false,"",'12',true];varcontainers=containers.filter(Boolean);console.log(containers);varcontainers=containers.filter(Number);console.log(containers);varcontainers=containers.filter(String);console.log(containers);varcontainers=containers.filter(Object);console.log(containers);})();
- [ 2, '12', true ][ 2, '12', true ][ 2, '12', true ][ 2, '12', true ]
- [false, true][ 2 ]['12'][ ]
- [2,0,false,"", '12', true][2,0,false,"", '12', true][2,0,false,"", '12', true][2,0,false,"", '12', true]
- [ 2, '12', true ][ 2, '12', true, false ][ 2, '12', true,false ][ 2, '12', true,false]
Answer
- [ 2, '12', true ][ 2, '12', true ][ 2, '12', true ][ 2, '12', true ]
(function(){varlist=['foo','bar','john','ritz'];console.log(list.slice(1));console.log(list.slice(1,3));console.log(list.slice());console.log(list.slice(2,2));console.log(list);})();
- [ 'bar', 'john', 'ritz' ][ 'bar', 'john' ][ 'foo', 'bar', 'john', 'ritz' ][][ 'foo', 'bar', 'john', 'ritz' ]
- [ 'bar', 'john', 'ritz' ][ 'bar', 'john','ritz ][ 'foo', 'bar', 'john', 'ritz' ][][ 'foo', 'bar', 'john', 'ritz' ]
- [ 'john', 'ritz' ][ 'bar', 'john' ][ 'foo', 'bar', 'john', 'ritz' ][][ 'foo', 'bar', 'john', 'ritz' ]
- [ 'foo' ][ 'bar', 'john' ][ 'foo', 'bar', 'john', 'ritz' ][][ 'foo', 'bar', 'john', 'ritz' ]
Answer
- [ 'bar', 'john', 'ritz' ][ 'bar', 'john' ][ 'foo', 'bar', 'john', 'ritz' ][][ 'foo', 'bar', 'john', 'ritz' ]
(function(){varlist=['foo','bar','john'];console.log(list.splice(1));console.log(list.splice(1,2));console.log(list);})();
- [ 'bar', 'john' ] [] [ 'foo' ]
- [ 'bar', 'john' ] [] [ 'bar', 'john' ]
- [ 'bar', 'john' ] [ 'bar', 'john' ] [ 'bar', 'john' ]
- [ 'bar', 'john' ] [] []
Answer
- [ 'bar', 'john' ] [] [ 'foo' ]
(function(){vararrayNumb=[2,8,15,16,23,42];arrayNumb.sort();console.log(arrayNumb);})();
- [2, 8, 15, 16, 23, 42]
- [42, 23, 26, 15, 8, 2]
- [ 15, 16, 2, 23, 42, 8 ]
- [ 2, 8, 15, 16, 23, 42 ]
Answer
- [ 15, 16, 2, 23, 42, 8 ]
functionfuncA(){console.log("funcA ",this);(functioninnerFuncA1(){console.log("innerFunc1",this);(functioninnerFunA11(){console.log("innerFunA11",this);})();})();}console.log(funcA());
- funcA Window {...}innerFunc1 Window {...}innerFunA11 Window {...}
- undefined
- Type Error
- ReferenceError: this is not defined
Answer
- funcA Window {...}innerFunc1 Window {...}innerFunA11 Window {...}
varobj={message:"Hello",innerMessage:!(function(){console.log(this.message);})()};console.log(obj.innerMessage);
- ReferenceError: this.message is not defined
- undefined
- Type Error
- undefined true
Answer
- undefined true
varobj={message:"Hello",innerMessage:function(){returnthis.message;}};console.log(obj.innerMessage());
- Hello
- undefined
- Type Error
- ReferenceError: this.message is not defined
Answer
- Hello
varobj={message:'Hello',innerMessage:function(){(function(){console.log(this.message);}());}};console.log(obj.innerMessage());
- Type Error
- Hello
- undefined
- ReferenceError: this.message is not defined
Answer
- undefined
varobj={message:'Hello',innerMessage:function(){varself=this;(function(){console.log(self.message);}());}};console.log(obj.innerMessage());
- Type Error
- 'Hello'
- undefined
- ReferenceError: self.message is not defined
Answer
- 'Hello'
functionmyFunc(){console.log(this.message);}myFunc.message="Hi John";console.log(myFunc());
- Type Error
- 'Hi John'
- undefined
- ReferenceError: this.message is not defined
Answer
- undefined
functionmyFunc(){console.log(myFunc.message);}myFunc.message="Hi John";console.log(myFunc());
- Type Error
- 'Hi John'
- undefined
- ReferenceError: this.message is not defined
Answer
- 'Hi John'
functionmyFunc(){myFunc.message='Hi John';console.log(myFunc.message);}console.log(myFunc());
- Type Error
- 'Hi John'
- undefined
- ReferenceError: this.message is not defined
Answer
- 'Hi John'
functionmyFunc(param1,param2){console.log(myFunc.length);}console.log(myFunc());console.log(myFunc("a","b"));console.log(myFunc("a","b","c","d"));
- 2 2 2
- 0 2 4
- undefined
- ReferenceError
Answer
a) 2 2 2
functionmyFunc(){console.log(arguments.length);}console.log(myFunc());console.log(myFunc("a","b"));console.log(myFunc("a","b","c","d"));
- 2 2 2
- 0 2 4
- undefined
- ReferenceError
Answer
- 0 2 4
functionPerson(name,age){this.name=name||"John";this.age=age||24;this.displayName=function(){console.log(this.name);}}Person.name="John";Person.displayName=function(){console.log(this.name);}varperson1=newPerson('John');person1.displayName();Person.displayName();
- John Person
- John John
- John undefined
- John John
Answer
- John Person
functionpassWordMngr(){varpassword='12345678';this.userName='John';return{pwd:password};}// Block EndvaruserInfo=passWordMngr();console.log(userInfo.pwd);console.log(userInfo.userName);
- 12345678 Window
- 12345678 John
- 12345678 undefined
- undefined undefined
Answer
- 12345678 undefined
varemployeeId='aq123';functionEmployee(){this.employeeId='bq1uy';}console.log(Employee.employeeId);
- Reference Error
- aq123
- bq1uy
- undefined
Answer
- undefined
varemployeeId='aq123';functionEmployee(){this.employeeId='bq1uy';}console.log(newEmployee().employeeId);Employee.prototype.employeeId='kj182';Employee.prototype.JobId='1BJKSJ';console.log(newEmployee().JobId);console.log(newEmployee().employeeId);
- bq1uy 1BJKSJ bq1uy undefined
- bq1uy 1BJKSJ bq1uy
- bq1uy 1BJKSJ kj182
- undefined 1BJKSJ kj182
Answer
- bq1uy 1BJKSJ bq1uy
varemployeeId='aq123';(functionEmployee(){try{throw'foo123';}catch(employeeId){console.log(employeeId);}console.log(employeeId);}());
- foo123 aq123
- foo123 foo123
- aq123 aq123
- foo123 undefined
Answer
- foo123 aq123
(function(){vargreet='Hello World';vartoGreet=[].filter.call(greet,function(element,index){returnindex>5;});console.log(toGreet);}());
- Hello World
- undefined
- World
- [ 'W', 'o', 'r', 'l', 'd' ]
Answer
- [ 'W', 'o', 'r', 'l', 'd' ]
(function(){varfooAccount={name:'John',amount:4000,deductAmount:function(amount){this.amount-=amount;return'Total amount left in account: '+this.amount;}};varbarAccount={name:'John',amount:6000};varwithdrawAmountBy=function(totalAmount){returnfooAccount.deductAmount.bind(barAccount,totalAmount);};console.log(withdrawAmountBy(400)());console.log(withdrawAmountBy(300)());}());
- Total amount left in account: 5600 Total amount left in account: 5300
- undefined undefined
- Total amount left in account: 3600 Total amount left in account: 3300
- Total amount left in account: 5600 Total amount left in account: 5600
Answer
- Total amount left in account: 5600 Total amount left in account: 5300
(function(){varfooAccount={name:'John',amount:4000,deductAmount:function(amount){this.amount-=amount;returnthis.amount;}};varbarAccount={name:'John',amount:6000};varwithdrawAmountBy=function(totalAmount){returnfooAccount.deductAmount.apply(barAccount,[totalAmount]);};console.log(withdrawAmountBy(400));console.log(withdrawAmountBy(300));console.log(withdrawAmountBy(200));}());
- 5600 5300 5100
- 3600 3300 3100
- 5600 3300 5100
- undefined undefined undefined
Answer
- 5600 5300 5100
(function(){varfooAccount={name:'John',amount:6000,deductAmount:function(amount){this.amount-=amount;returnthis.amount;}};varbarAccount={name:'John',amount:4000};varwithdrawAmountBy=function(totalAmount){returnfooAccount.deductAmount.call(barAccount,totalAmount);};console.log(withdrawAmountBy(400));console.log(withdrawAmountBy(300));console.log(withdrawAmountBy(200));}());
- 5600 5300 5100
- 3600 3300 3100
- 5600 3300 5100
- undefined undefined undefined
Answer
- 3600 3300 3100
(functiongreetNewCustomer(){console.log('Hello '+this.name);}.bind({name:'John'})());
- Hello John
- Reference Error
- Window
- undefined
Answer
- Hello John
functiongetDataFromServer(apiUrl){varname="John";return{then :function(fn){fn(name);}}}getDataFromServer('www.google.com').then(function(name){console.log(name);});
- John
- undefined
- Reference Error
- fn is not defined
Answer
- John
(function(){vararrayNumb=[2,8,15,16,23,42];Array.prototype.sort=function(a,b){returna-b;};arrayNumb.sort();console.log(arrayNumb);})();(function(){varnumberArray=[2,8,15,16,23,42];numberArray.sort(function(a,b){if(a==b){return0;}else{returna<b ?-1 :1;}});console.log(numberArray);})();(function(){varnumberArray=[2,8,15,16,23,42];numberArray.sort(function(a,b){returna-b;});console.log(numberArray);})();
- [ 2, 8, 15, 16, 23, 42 ][ 2, 8, 15, 16, 23, 42 ][ 2, 8, 15, 16, 23, 42 ]
- undefined undefined undefined
- [42, 23, 16, 15, 8, 2][42, 23, 16, 15, 8, 2][42, 23, 16, 15, 8, 2]
- Reference Error
Answer
- [ 2, 8, 15, 16, 23, 42 ][ 2, 8, 15, 16, 23, 42 ][ 2, 8, 15, 16, 23, 42 ]
(function(){functionsayHello(){varname="Hi John";return{fullName:name}}console.log(sayHello().fullName);})();
- Hi John
- undefined
- Reference Error
- Uncaught TypeError: Cannot read property 'fullName' of undefined
Answer
- Uncaught TypeError: Cannot read property 'fullName' of undefined
functiongetNumber(){return(2,4,5);}varnumb=getNumber();console.log(numb);
- 5
- undefined
- 2
- (2,4,5)
Answer
- 5
functiongetNumber(){return;}varnumb=getNumber();console.log(numb);
- null
- undefined
- ""
- 0
Answer
- undefined
functionmul(x){returnfunction(y){return[x*y,function(z){returnx*y+z;}];}}console.log(mul(2)(3)[0]);console.log(mul(2)(3)[1](4));
- 6, 10
- undefined undefined
- Reference Error
- 10, 6
Answer
- 6, 10
functionmul(x){returnfunction(y){return{result:x*y,sum:function(z){returnx*y+z;}};};}console.log(mul(2)(3).result);console.log(mul(2)(3).sum(4));
- 6, 10
- undefined undefined
- Reference Error
- 10, 6
Answer
- 6, 10
functionmul(x){returnfunction(y){returnfunction(z){returnfunction(w){returnfunction(p){returnx*y*z*w*p;};};};};}console.log(mul(2)(3)(4)(5)(6));
- 720
- undefined
- Reference Error
- Type Error
Answer
- 720
functiongetName1(){console.log(this.name);}Object.prototype.getName2=()=>{console.log(this.name)}letpersonObj={name:"Tony",print:getName1}personObj.print();personObj.getName2();
- undefined undefined
- Tony undefined
- undefined Tony
- Tony Tony
Answer
- Tony undefined
Explaination:getName1() function works fine because it's being called frompersonObj, so it has access tothis.name property. But when while callinggetnName2 which is defined underObject.prototype doesn't have any proprty namedthis.name. There should bename property under prototype. Following is the code:
functiongetName1(){console.log(this.name);}Object.prototype.getName2=()=>{console.log(Object.getPrototypeOf(this).name);}letpersonObj={name:"Tony",print:getName1}personObj.print();Object.prototype.name="Steve";personObj.getName2();
leta=true;letc=0;setTimeout(()=>{a=false;},2000)while(a){console.log('Hello')}
Answer
The above program will print Hello infinitely. Since, Javascript is a single threaded language the actual execution happens only on the main thread. So, setTimeout will wailt for 2000 milliseconds on a seperate thread as while loop has occupied the main thread. The exit condition for the loop is to set the variable a as fasle. But as the loop continously running on the main thread , it a cannot be set false.letc=0;letid=setInterval(()=>{console.log(c++)},200)setTimeout(()=>{clearInterval(id)},2000)
Answer
The above program will print 0 to 9 sequentially.We always appreciate your feedback on how the book can be improved, and more questions can be added. If you think you have some question then please add that and open a pull request.
This book is released under a Creative Commons Attribution-Noncommercial- No Derivative Works 3.0 United States License.
What this means it that the project is free to read and use, but the license does not permit commercial use of the material (i.e you can freely print out the questions for your own use, but you can't sell it). I'm trying to best to publish all of my books in a free + purchased (if you would like to support these projects) form so I would greatly appreciate it if you would respect these terms.
Copyright Iurii Katkov and Nishant Kumar, 2017.
About
JavaScript interview Questions
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.