diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..1edcd0d
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,29 @@
+BSD 3-Clause License
+
+Copyright (c) 2017, Nishant Kumar
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+* Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/Nishant_resume.js b/Nishant_resume.js
deleted file mode 100644
index 50d65cc..0000000
--- a/Nishant_resume.js
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
- * The Curriculum vitae of Nishant Kumar
- *
- * Hi there, I am Nishant. I am UI Engineering Lead, JavaScript Engineer,
- * Mozila Tech Contributor, CodeMentor Front-end Expert, Writer from India.
- */
-
-(function() {
- 'use strict';
-
- /*
- About Me
- */
- var me = {
- name: 'Nishant Kumar',
- job: 'UI Engineering Lead',
- organization: 'Big Parser',
- status: 'Not availble for Hire full time',
- location: 'India',
- experience: '5 years',
- skills: {
- 'scripting-language' :['javascript']
- 'frameworks': ['angular.js','backbone.js','sails.js'],
- 'library' : ['jQuery']
- 'tools': ['Gulp', 'Grunt', 'bower','yoman','Git'],
- 'testing': ['jasmine', 'protractor'],
- 'backend': ['node.js', 'express.js'],
- 'dataBase': ['mongoDb', 'SQL'],
- 'uncategorized' : ['C','C#','HTML','CSS', 'HTML5','JSON']
- }
- };
-
- /*
- Contact Details
- */
- var me_contact = {
- 'email' : 'nihantanu@gmail.com',
- 'skypeId' : 'mfsi_nishantk',
- 'linkedIn' :'http://in.linkedin.com/in/nishantkumar1'
- 'gitHub' : 'github.com/nishant8BITS'
- 'stackOverFlow' : 'http://stackoverflow.com/users/430803/nishant'
- 'codementor': 'codementor.io/nihantanu'
- }
-
- /*
- Education
- */
- var education = {
- 'post-Graduate': {
- 'college': 'Birla Institute of Technology and Science, Pilani',
- 'Major' : 'Software System',
- 'Year' :'2016'
- },
- 'graduation' : {
- 'college': 'ICFAI University, Dehradun',
- 'Major' : 'Computer Science & Engineering',
- 'Year' :'2011'
- }
- }
-
- /**
- * Nice things people have said about me.
- */
-
- /**
- * Nishant is a very smart and thoughtful person as an engineer. He truly cares
- * about helping others and values the learning experience for young software
- * engineers. He is very patient - a key trait as an engineer. Nishant will help
- * guide you through problems and help you understand software engineering
- * concepts. Hands down I would hire Nishant to be on a team that will not only
- * help a business but help other engineers grow as well.
- * -Gary Tsai, Software Engineer
- */
-
- /**
- * Nishant is a quick learner and he has very deep understanding on UI stack. He
- * also is a good mentor and help other to understand the technology stack. One
- * good thing I observed while working with him is he always focus on insist on
- * highest standard in his code/solution as well as idea. Keep it up.
- * -Apurv Gupta (WDE II at Amazon)
- */
-
- /**
- * Nishant is one of the best person I'm working with. Along with his strong
- * technical understanding of how things work, he also keeps on motivating to team
- * and helps them to participate effectively & maintaining their productivity to
- * better work towards achieving a goal. He always prefers to have full stack
- * knowledge of the product & leads a team with great enthusiasm. He can deliver
- * end to end any product he is working on.
- * -Yash Shah (SRE at Linkedin)
- */
-
- /**
- * I have been working with Nishant since last one year on a cloud-based product,
- * He is one of the vibrant contributor in the team and always been dedicated to
- * his work. He has very good level of knowledge when it comes to overall front-end
- * architecture solutions and specifically on frameworks like backbone & angular.
- * -Mohiuddin Parekh ( Founder & CEO at Decojent)
- */
-
- /**
- * I first met Nishant 3 months ago when I told him I was looking for help with
- * AngularJS and asked him to mentor me. One of the first things I noticed was that
- * he had a great learning attitude, because he told me that he was looking forward
- * to learning from me, something I wasn’t expecting from a mentor! He is fun,
- * sweet, generous and has a great sense of humor. We have quickly become friends
- * and I think we have spent more time hanging out on Telegram (instant messaging)
- * and Skype than we have coding. I had never written my own AngularJS directive
- * before so I asked him if he could write one for me for an autocomplete feature.
- * I was impressed with his work and because of it I was then able to write my own
- * directives. We have spent a lot of time chatting and I think there is so much
- * more he can do that I have not yet seen. I can see he also has a passion for
- * startups.
- * -Jenny Swift (Software Engineer)
- */
-
-})();
diff --git a/README.md b/README.md
index fd68472..3bc019c 100644
--- a/README.md
+++ b/README.md
@@ -1,35 +1,39 @@

-## This Book will be completed by June 1 2016 and available to buy. If you want me to sent early copy of this book then please add your name and email address in google form here [Google Form](http://goo.gl/forms/QSpxVtvsNb).
+# 123-JavaScript-Interview-Questions
-[](https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+This book's goal is to help javascript frontend developers prepare for technical job interviews through a collection of carefully compiled questions.
-## Have question for me ?
-[Ask me @nishant kumar](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+## Want to buy a book in paper form? Want some badass flashcards?
-# 123-JavaScript-Interview-Question
-## 1. Difference between `undefined` and `not defined` in JavaScript
-> In JavaScript if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error `var name is not defined` and the script will stop execute thereafter. But If you use `typeof undeclared_variable` then it will return `undefined`.
+ - 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 this [Google Form](https://goo.gl/forms/c8ubV1tWBBdz6fJP2).
+ - If you don't want to wait, you can buy [Yuri's JavaScript Flashcards](http://flashcardsjs.com), a set of frontend interview questions sorted by popularity among interviewers printed on beautiful poker-size flashcards.
+
+## Question 1. What's the difference between `undefined` and `not defined` in JavaScript
+
+Answer
+
+In JavaScript if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error `var name is not defined` and the script will stop executing thereafter. But If you use `typeof undeclared_variable` then it will return `undefined`.
Before starting further discussion let's understand the difference between declaration and definition.
-`var x` is a declaration because you are not defining what value it holds yet, but you are declaring its existence and the need of memory allocation.
+`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.
```javascript
var x; // declaring x
-console.log(x); //output: undefined
+console.log(x); // output: undefined
```
-`var x = 1` is both declaration and definition (also we can say we are doing initialisation), Here declaration and assignment of value happen inline for variable x, In JavaScript every variable declaration and function declaration brings to the top of its current scope in which it's declared then assignment happen in order this term is called `hoisting`.
+`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 that is declared but not define and when we try to access it, It will result `undefined`.
+A variable can be declared but not defined. When we try to access it, It will result `undefined`.
```javascript
var x; // Declaration
-if(typeof x === 'undefined') // Will return true
+typeof x === 'undefined'; // Will return true
```
-> A variable that neither declared nor defined when we try to reference such variable then It result `not defined`.
+A variable can be neither declared nor defined. When we try to reference such variable then the result will be `not defined`.
```javascript
console.log(y); // Output: ReferenceError: y is not defined
@@ -38,112 +42,102 @@ console.log(y); // Output: ReferenceError: y is not defined
### Ref Link:
[http://stackoverflow.com/questions/20822022/javascript-variable-definition-declaration](http://stackoverflow.com/questions/20822022/javascript-variable-definition-declaration)
-## Have doubt in this question ??
-[Schedule time to discuss with me @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+
+
+## Question 2. For which value of `x` the results of the following statements are not the same?
-## 2. What will be the output of the following code?
```javascript
-var y = 1;
-if (function f() {}) {
- y += typeof f;
-}
-console.log(y);
+if( x <= 100 ) {...}
+if( !(x > 100) ) {...}
```
+Answer
-> Above code would give output `1undefined`. If condition statement evaluate using `eval` so `eval(function f() {})` which return `function f() {}` which is true so inside if statement code execute. `typeof f` return undefined because if statement code execute at run time, so statement inside `if` condition evaluated at run time.
+`NaN <= 100` is `false` and `NaN > 100` is also `false`, so if the
+value of `x` is `NaN`, the statements are not the same.
-```javascript
-var k = 1;
-if (1) {
- eval(function foo() {});
- k += typeof foo;
-}
-console.log(k);
-```
+The same holds true for any value of x that being converted to type Number, returns `NaN`, e.g.: `undefined`, `[1,2,5]`, `{a:22}` , etc.
-Above code will also output `1undefined`.
+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 is `NaN`, is to use the `isNaN()` function.
-```javascript
-var k = 1;
-if (1) {
- function foo() {};
- k += typeof foo;
-}
-console.log(k); // output 1function
-```
+
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+## Question 3. What is the drawback of declaring methods directly in JavaScript objects?
-## 3. What is the drawback of creating true private in JavaScript?
-> One of the drawback of creating a true private method in JavaScript is that they are very memory inefficient because a new copy of the method would be created for each instance.
+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:
```javascript
var Employee = function (name, company, salary) {
- this.name = name || ""; //Public attribute default value is null
- this.company = company || ""; //Public attribute default value is null
- this.salary = salary || 5000; //Public attribute default value is null
-
- // Private method
- var increaseSlary = function () {
- this.salary = this.salary + 1000;
- };
+ this.name = name || "";
+ this.company = company || "";
+ this.salary = salary || 5000;
- // Public method
- this.dispalyIncreasedSalary = function() {
- increaseSlary();
- console.log(this.salary);
+ // We can create a method like this:
+ this.formatSalary = function () {
+ return "$ " + this.salary;
};
};
-// Create Employee class object
-var emp1 = new Employee("John","Pluto",3000);
-// Create Employee class object
-var emp2 = new Employee("Merry","Pluto",2000);
-// Create Employee class object
-var emp3 = new Employee("Ren","Pluto",2500);
+// Alternatively we can add the method to Employee's prototype:
+Employee.prototype.formatSalary2 = function() {
+ return "$ " + this.salary;
+}
+
+//creating objects
+var emp1 = new Employee('Yuri Garagin', 'Company 1', 1000000);
+var emp2 = new Employee('Dinesh Gupta', 'Company 2', 1039999);
+var emp3 = new Employee('Erich Fromm', 'Company 3', 1299483);
```
-Here each instance variable `emp1`, `emp2`, `emp3` has own copy of increaseSalary private method.
+In this case each instance variable `emp1`, `emp2`, `emp3` has its own copy of the`formatSalary` method. However the `formatSalary2` will only be added once to `Employee.prototype`.
+
+
-So as recommendation don't go for a private method unless it's necessary.
+## Question 4. What is “closure” in javascript? Can you provide an example?
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+Answer
-## 4.What is “closure” in javascript? Provide an example?
-> A closure is a function defined inside another function (called parent function) and has access to the variable which is declared and defined in parent function scope.
+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 variable in three scopes:
-- Variable declared in his own scope
-- Variable declared in parent function scope
-- Variable declared in global namespace
+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
```javascript
-var globalVar = "abc";
+var globalVar = "abc"; //Global variable
+
+// Parent self-invoking function
+(function outerFunction (outerArg) { // start of outerFunction's scope
-// Parent self invoking function
-(function outerFunction (outerArg) { // begin of scope outerFunction
- // Variable declared in outerFunction function scope
- var outerFuncVar = 'x';
+ var outerFuncVar = 'x'; // Variable declared in outerFunction's function scope
+
// Closure self-invoking function
- (function innerFunction (innerArg) { // begin of scope innerFunction
- // variable declared in innerFunction function scope
- var innerFuncVar = "y";
+ (function innerFunction (innerArg) { // start of innerFunction's scope
+
+ var innerFuncVar = "y"; // variable declared in innerFunction's function scope
console.log(
"outerArg = " + outerArg + "\n" +
"outerFuncVar = " + outerFuncVar + "\n" +
"innerArg = " + innerArg + "\n" +
"innerFuncVar = " + innerFuncVar + "\n" +
"globalVar = " + globalVar);
- } // end of scope innerFunction)(5); // Pass 5 as parameter
-} // end of scope outerFunction )(7); // Pass 7 as parameter
+
+ // 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 closure which is defined inside `outerFunction` and has access to all variable which is declared and defined in outerFunction scope. In addition to this function defined inside function as closure has access to variable which is declared in `global namespace`.
+`innerFunction` is a closure which is defined inside `outerFunction` and consequently has access to all the variables which have been declared and defined within `outerFunction`'s scope as well as any variables residing in the program's global scope.
-Output of above code would be:
+The output of the code above would be:
```javascript
outerArg = 7
@@ -153,17 +147,15 @@ innerFuncVar = y
globalVar = abc
```
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+
-## 5. Write a mul function which will properly when invoked as below syntax.
+## Question 5. Write a mul function which will work properly when invoked with following syntax.
```javascript
console.log(mul(2)(3)(4)); // output : 24
console.log(mul(4)(3)(4)); // output : 48
```
-
-> Below is code followed by an explanation how it works:
+Answer
```javascript
function mul (x) {
@@ -175,35 +167,40 @@ function mul (x) {
}
```
-Here `mul` function accept the first argument and return anonymous function which take the second parameter and return anonymous function which take the third parameter and return multiplication of arguments which is being passed in successive
+Here the `mul` 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 multiplies `x`, `y` and `z`, 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.
-In Javascript function defined inside has access to outer function variable and function is the first class object so it can be returned by function as well and passed as argument in another function.
- A function is an instance of the Object type
-- A function can have properties and has a link back to its constructor method
-- Function can be stored as variable
-- Function can be pass as a parameter to another function
-- Function can be returned from function
+- 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
+
+
-### 6. How to empty an array in JavaScript?
+## Question 6. How to empty an array in JavaScript?
For instance:
```javascript
var arrayList = ['a', 'b', 'c', 'd', 'e', 'f'];
```
-How can we empty above array?
+How can we empty the array above?
-> 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.
+Answer
-### Method 1
+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.
+
+#### Method 1
```javascript
arrayList = [];
```
-Above code will set the variable `arrayList` to a new empty array. This is recommended if you don't have **references to the original array** `arrayList` 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 variable `arrayList`.
+The code above will set the variable `arrayList` to a new empty array. This is recommended if you don't have **references to the original array** `arrayList` 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 variable `arrayList`.
-For Instance:
+For instance:
```javascript
var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
@@ -212,15 +209,15 @@ arrayList = []; // Empty the array
console.log(anotherArrayList); // Output ['a', 'b', 'c', 'd', 'e', 'f']
```
-### Method 2
+#### Method 2
```javascript
arrayList.length = 0;
```
-Above code will clear the existing array by setting its length to 0. This way of empty the array also update all the reference variable which pointing to the original array. This way of empty the array is useful when you want to update all the another reference variable which pointing to `arrayList`.
+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:
+For instance:
```javascript
var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
@@ -229,7 +226,7 @@ arrayList.length = 0; // Empty the array by setting length to 0
console.log(anotherArrayList); // Output []
```
-### Method 3
+#### Method 3
```javascript
arrayList.splice(0, arrayList.length);
@@ -244,7 +241,7 @@ arrayList.splice(0, arrayList.length); // Empty the array by setting length to 0
console.log(anotherArrayList); // Output []
```
-### Method 4
+#### Method 4
```javascript
while(arrayList.length) {
@@ -254,17 +251,20 @@ while(arrayList.length) {
Above implementation can also empty the array. But not recommended to use often.
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
-### 7. How to check if an object is an array or not?
-> The best way to find whether an object is instance of a particular class or not using `toString` method from `Object.prototype`
+
+
+## Question 7. How to check if an object is an array or not?
+
+Answer
+
+The best way to find whether an object is instance of a particular class or not using `toString` method from `Object.prototype`
```javascript
var arrayList = [1 , 2, 3];
```
-One of the best use cases of type checking of an object is when we do method overloading in JavaScript. For understanding this let say we have a method called `greet` which take one single string and also a list of string, so making our `greet` method workable in both situation we need to know what kind of parameter is being passed, is it single value or list of value?
+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 called `greet` which can take a single string and also a list of strings. To make our `greet` method workable in both situation we need to know what kind of parameter is being passed: is it single value or list of values?
```javascript
function greet(param) {
@@ -276,7 +276,7 @@ function greet(param) {
}
```
-However, in above implementation it might not necessary to check type for array, we can check for single value string and put array logic code in else block, let see below code for the same.
+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.
```javascript
function greet(param) {
@@ -288,9 +288,9 @@ However, in above implementation it might not necessary to check type for array,
}
```
-Now it's fine we can go with above two implementations, but when we have a situation like a parameter can be `single value`, `array`, and `object` type then we will be in trouble.
+Now it's fine we can go with the previous two implementations, but when we have a situation like a parameter can be `single value`, `array`, and `object` type then we will be in trouble.
-Coming back to checking type of object, As we mentioned that we can use `Object.prototype.toString`
+Coming back to checking the type of an object, As we mentioned that we can use `Object.prototype.toString`
```javascript
if(Object.prototype.toString.call(arrayList) === '[object Array]') {
@@ -318,10 +318,10 @@ Array.isArray(arrayList);
`Array.isArray` is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
-#### 8. What will be the output of the following code?
+
+
+## Question 8. What will be the output of the following code?
```javascript
var output = (function(x) {
@@ -331,13 +331,14 @@ var output = (function(x) {
console.log(output);
```
+Answer
+
+The code above will output `0` as output. `delete` operator is used to delete a property from an object. Here `x` is not an object, it's a **local variable**. `delete` operator doesn't affect local variables.
-> Above code will output `0` as output. `delete` operator is used to delete a property from an object. Here `x` is not an object it's **local variable**. `delete` operator doesn't affect local variable.
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+
-#### 9. What will be the output of the following code?
+## Question 9. What will be the output of the following code?
```javascript
var x = 1;
@@ -348,13 +349,14 @@ var output = (function() {
console.log(output);
```
+Answer
-> Above code will output `1` as output. `delete` operator is used to delete property from object. Here `x` is not an object it's **global variable** of type `number`.
+The code above will output `1` as output. `delete` operator is used to delete a property from an object. Here `x` is not an object it's **global variable** of type `number`.
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
-#### 10. What will be the output of the following code?
+
+
+## Question 10. What will be the output of the following code?
```javascript
var x = { foo : 1};
@@ -365,13 +367,14 @@ var output = (function() {
console.log(output);
```
+Answer
+
+The code above will output `undefined` as output. `delete` operator is used to delete a property from an object. Here `x` is an object which has foo as a property and from a self-invoking function, we are deleting the `foo` property of object `x` and after deletion, we are trying to reference deleted property `foo` which result `undefined`.
-> Above code will output `undefined` as output. `delete` operator is used to delete a property from an object. Here `x` is an object which has foo as a property and from self-invoking function we are deleting foo property of object `x` and after deletion we are trying to reference deleted property `foo` which result `undefined`.
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+
-#### 11. What will be the output of the following code?
+## Question 11. What will be the output of the following code?
```javascript
var Employee = {
@@ -382,43 +385,51 @@ delete emp1.company
console.log(emp1.company);
```
-> Above code will output `xyz` as output. Here `emp1` object got company as **prototype** property. delete operator doesn't delete prototype property.
+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 have **company** as its own property. you can test it `console.log(emp1.hasOwnProperty('company')); //output : false` However, we can delete company property directly from `Employee` object using `delete Employee.company` or we can also delete from `emp1` object using `__proto__` property `delete emp1.__proto__.company`.
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
-#### 12. What is `undefined x 1` in JavaScript
+
+
+## Question 12. What is `undefined x 1` in JavaScript
```javascript
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
```
-when you run above code and do `console.log(trees);` in chrome developer console then you will get `["redwood", "bay", "cedar", undefined × 1, "maple"]` and when you run above code in Firefox browser console then you will get `["redwood", "bay", "cedar", undefined, "maple"]` so from these it's cleared that chrome has its own way of displaying uninitialized index in array. But when you check `trees[3] === undefined` in both of the browser you will get similar output as `true`.
+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 check `trees[3] === undefined` in any browser you will get similar output as `true`.
+
+**Note:** Please remember that you need not check for the uninitialized index of the array in `trees[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.
+
-**Note:** Please remember you need not check for uninitialized index of array in `trees[3] === 'undefined × 1'` it will give an error, Because `'undefined × 1'` this is just way of displaying uninitialized index of array in chrome.
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+
-#### 13. What will be the output of the following code?
+## Question 13. What will be the output of the following code?
```javascript
var trees = ["xyz", "xxxx", "test", "ryan", "apple"];
delete trees[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.
-> Above code will output `5` as output. When we used `delete` operator for deleting an array element then, the array length is not affected from this. This holds even if you deleted all the element of 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 index `undefined x 1` in **chrome** and `undefined` is placed at the index. If you do `console.log(trees)` output `["xyz", "xxxx", "test", undefined × 1, "apple"]` in Chrome and in Firefox `["xyz", "xxxx", "test", undefined, "apple"]`.
-So when delete operator removes an array element that deleted element is not longer present in array. In place of value at deleted index `undefined x 1` in **chrome** and `undefined` is placed at the index. If you do `console.log(trees)` output `["xyz", "xxxx", "test", undefined × 1, "apple"]` in Chrome and in Firefox `["xyz", "xxxx", "test", undefined, "apple"]`.
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
-#### 14. What will be the output of the following code?
+
+
+## Question 14. What will be the output of the following code?
```javascript
var bar = true;
@@ -427,38 +438,51 @@ console.log(bar + "xyz");
console.log(bar + true);
console.log(bar + false);
```
+Answer
-> Above code will output `1, "truexyz", 2, 1` as output. General guideline for addition of operator:
+The code above will output `1, "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
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+
-#### 15. What will be the output of the following code?
+
+
+## Question 15. What will be the output of the following code?
```javascript
var z = 1, y = z = typeof y;
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 is `Right to Left` so first `typeof y` will evaluate first which is string `"undefined"` and assigned to `z` and then `y` would be assigned the value of z. The overall sequence will look like that:
-> Above code will output `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 is `Right to Left` so first `typeof y` will evaluate first which is `undefined` and assigned to `z` and then `y` would be assigned the value of z and then `z` would be assign value `1`.
+```javascript
+var z;
+z = 1;
+var y;
+z = typeof y;
+y = z;
+```
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+
-#### 16. What will be the output of the following code?
+## Question 16. What will be the output of the following code?
```javascript
-// NFE (Named Function Expression
+// NFE (Named Function Expression)
var foo = function bar() { return 12; };
typeof bar();
```
-> Above code will output `Reference Error` as output. For making above code work you can re-write above code as follow:
+Answer
+
+The output will be `Reference Error`. To fix the bug we can try to rewrite the code a little bit:
**Sample 1**
@@ -476,100 +500,85 @@ function bar() { return 12; };
typeof bar();
```
-The function definition can have only one reference variable as a function name, In above code **sample 1** bar is reference variable which is pointing to `anonymous function` and in **sample 2** function definition is name function.
+The function definition can have only one reference variable as a function name, In **sample 1** `bar` is reference variable which is pointing to `anonymous function` and in **sample 2** we have function statement and `bar` is the function name.
```javascript
var foo = function bar() {
// foo is visible here
// bar is visible here
- console.log(typeof bar()); // Work here :)
+ console.log(typeof bar()); // Works here :)
};
// foo is visible here
// bar is undefined here
```
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
-
+
-#### 17. What is the difference between declaring a function in below format?
+## Question 17a. What is the difference between declaring a function in the formats listed below?
```javascript
var foo = function() {
// Some code
-};
+}
```
```javascript
-function bar() {
+function bar () {
// Some code
-};
+}
```
+Answer
-The main difference is function `foo` is defined at `run-time` whereas function `bar` is defined at parse time. For understanding It in better way let see below code :
+The main difference is that function `foo` is defined at `run-time` and is called a function expression, whereas function `bar` is defined at `parse time` and is called a function statement. To understand it better, let's take a look at the code below :
```javascript
// Run-Time function declaration
-
```
```javascript
// Parse-Time function declaration
-
+}
```
+
-The another advantage of first-one way of declaration that you can declare function based on certain condition for example:
+## Question 17b. What is the output of the following?
```javascript
-
+bar();
+(function abc(){console.log('something')})();
+function bar(){console.log('bar got called')};
```
+Answer
-But If you try to run similar code in the following format, it would give an error
-
-```javascript
-
+The output will be :
+```
+bar got called
+something
```
+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.
-#### 18. what is function hoisting in JavaScript?
-**Function Expression**
+
+
+## Question 18. In which case the function definition is not hoisted in JavaScript?
+
+Answer
+
+Let's take the following **function expression**
```javascript
var foo = function foo() {
return 12;
- };
+ }
```
-> In JavaScript variable and functions are `hoisted`. Let's take function `hoisting` 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:
+In JavaScript `var`-declared variables and functions are `hoisted`. Let's take function `hoisting` 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:
```javascript
foo(); // Here foo is still undefined
@@ -578,7 +587,7 @@ var foo = function foo() {
};
```
-Above code behind the scene look something like below code:
+The code above behind the scene look something like this:
```javascript
var foo = undefined;
@@ -596,7 +605,9 @@ foo = function foo() {
foo(); // Now foo is defined here
```
-#### 19. What will be the output of the following code?
+
+
+## Question 19. What will be the output of the following code?
```javascript
var salary = "1000$";
@@ -609,8 +620,9 @@ var salary = "1000$";
console.log("My New Salary " + salary);
})();
```
+Answer
-> Above code will output: `undefined, 5000$`. JavaScript has hoisting concept where newbie gets tricked. In above code, you might be expecting `salary` to retain it values from outer scope until the point that `salary` was re-declared in the inner scope. But due to `hoisting` salary value was `undefined` instead. To understand it better have a look of the following code, here `salary` variable is hoisted and declared at the top in function scope and while doing console.log it's result `undefined` and after that it's been redeclared and assigned `5000$`.
+The code above will output: `undefined, 5000$` because of hoisting. In the code presented above, you might be expecting `salary` to retain it values from outer scope until the point that `salary` was re-declared in the inner scope. But due to `hoisting` salary value was `undefined` instead. To understand it better have a look of the following code, here `salary` variable is hoisted and declared at the top in function scope. When we print its value using `console.log` the result is `undefined`. Afterwards the variable is redeclared and the new value `"5000$"` is assigned to it.
```javascript
var salary = "1000$";
@@ -625,18 +637,19 @@ var salary = "1000$";
})();
```
-#### 20. What is the `instanceof` operator in JavaScript? what would be the output of the following code?
+
-```javascript
-function foo() {
- return foo;
-}
-new foo() instanceof foo;
-```
+## Question 20. What’s the difference between `typeof` and `instanceof`?
+
+Answer
+
+`typeof` is an operator that returns a string with the type of whatever you pass.
+
+The `typeof` operator checks if a value belongs to one of the seven basic types: `number`, `string`, `boolean`, `object`, `function`, `undefined` or `Symbol`.
-> `instanceof` operator checks the current object and return true if the object is of the specified type.
+`typeof(null)` will return `object`.
-For Example:
+`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. The `instanceof` operator checks the current object and returns true if the object is of the specified type, for example:
```javascript
var dog = new Animal();
@@ -650,30 +663,12 @@ var name = new String("xyz");
name instanceof String; // Output : true
```
-Here `name instanceof String` is true since `name` inherits from `String.prototype`. Now let's understand the working of the following code
-
-```javascript
-function foo() {
- return foo;
-}
-new foo() instanceof foo;
-```
-
-Here function `foo` is returning `foo` which is again pointer to function `foo`
-
-```javascript
-function foo() {
- return foo;
-}
-var bar = new foo();
-// here bar is pointer to function foo() {return foo}.
-```
-
-So the `new foo() instanceof foo` return `false`;
Ref Link: [http://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript](http://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript)
-#### 21. If we have JavaScript associative array as below code:
+
+
+## Question 21. Calculate the length of the associative array
```javascript
var counterArray = {
@@ -682,20 +677,24 @@ var counterArray = {
};
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.
-#### How we will calculate length of the above associative array `counterArray`
-> There are no built-in function and property available to calculate length of associative array object. However, there are ways by which we can calculate the length of associative array object, In addition to this we can also extend `Object` by adding method or property on prototype for calculating length but extending object might break enumeration in various libraries or might create cross-browser issue, so it's not recommended unless it's necessary. There is various ways by which we can calculate length.
+#### Method 1
-`Object` has `keys` method which can we used to calculate the length of object.
+`Object` has `keys` method which can be used to calculate the length of object.
```javascript
-Object.keys(counterArray).length; // Output 2
+Object.keys(counterArray).length; // Output 3
```
-We can also calculate length of object by iterating through the object and by doing a count of own property of object.
+#### Method 2
+
+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:
```javascript
-function getSize(object) {
+function getLength(object) {
var count = 0;
for(key in object) {
// hasOwnProperty method check own property of object
@@ -705,25 +704,29 @@ function getSize(object) {
}
```
-> We can also add `length` method directly on `Object` see below code.
+#### Method 3
+
+All modern browsers (including IE9+) support the [`getOwnPropertyNames`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames) method, so we can calculate the length using the following code:
```javascript
-Object.length = function() {
- var count = 0;
- for(key in object) {
- // hasOwnProperty method check own property of object
- if(object.hasOwnProperty(key)) count++;
- }
- return count;
-}
-//Get the size of any object using
-console.log(Object.length(counterArray));
+Object.getOwnPropertyNames(counterArray).length; // Output 3
+```
+
+#### Method 4
+
+[Underscore](https://underscorejs.org/#size) and [lodash](https://lodash.com/docs/4.17.10#size) libraries have the method `size` dedicated to calculate the object length. We don't recommend to include one of these libraries just to use the `size` method, but if it's already used in your project - why not?
+
+```javascript
+_.size({one: 1, two: 2, three: 3});
+=> 3
```
-**Bonus**: We can also use `Underscore` (recommended, as it's lightweight) to calculate object length.
+
+
+## Question 22. Difference between `Function`, `Method` and `Constructor` calls in JavaScript.
+
+Answer
-## Question 22
-### Difference between `Function`, `Method` and `Constructor` calls in JavaScript.
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:
@@ -736,7 +739,7 @@ function helloWorld(name) {
helloWorld("JS Geeks"); // "hello world JS Geeks"
```
-Methods in JavaScript are nothing more than object properties that reference to a function.
+Methods in JavaScript are nothing more than object properties that are functions.
```javascript
var obj = {
@@ -773,16 +776,14 @@ emp1.name; // "John Doe"
emp1.age; // 28
```
-Unlike function calls and method calls, a constructor call `new Employee('John Doe', 28)` create a brand new object and passes it as the value of `this`, and implicitly returns the new object as its result.
+Unlike function calls and method calls, a constructor call `new Employee('John Doe', 28)` creates a brand new object and passes it as the value of `this`, and implicitly returns the new object as its result.
The primary role of the constructor function is to initialize the object.
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+
-## Question 23
-### What would be the output of the following code?
+## Question 23. What would be the output of the following code?
```javascript
function User(name) {
@@ -793,66 +794,62 @@ var person = new User("xyz")["location"] = "USA";
console.log(person);
```
-The output of above code would be `USA`. Here `new User("xyz")` creates a brand new object and created property `location` on that and `USA` has been assigned to object property location and that has been referenced by the person.
+Answer
-Let say `new User("xyz")` crated a object called `foo` and returned now `foo["location"]` would be assigned value as `USA` and `person` is referencing to `foo["location"]`.
+The output of above code would be `"USA"`. Here `new User("xyz")` creates a brand new object and created property `location` on that and `USA` has been assigned to object property location and that has been referenced by the person.
-## Question 24
-### Write a mul function which will output when invoked as below syntax.
+Let say `new User("xyz")` created a object called `foo`. The value `"USA"` will be assigned to `foo["location"]`, but according to [ECMAScript Specification](http://www.ecma-international.org/ecma-262/6.0/#sec-assignment-operators-runtime-semantics-evaluation) , 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:
+ ```javascript
+function User(name) {
+ this.name = name || "JsGeeks";
+}
+
+var person;
+var foo = new User("xyz");
+foo["location"] = "USA";
+// the console will show you that the result of this is "USA"
-```javascript
-console.log(mul(2)(3)(4)); // output : 24
-console.log(mul(4)(3)(4)); // output : 48
```
+
+
+
-Below is code followed by an explanation how it works:
+## Question 24. What are Service Workers and when can you use them?
-```javascript
-function mul (x) {
- return function (y) { // anonymous function
- return function (z) { // anonymous function
- return x * y * z;
- };
- };
-}
-```
+Answer
-Here `mul` function accept the first argument and return anonymous function which take the second parameter and return anonymous function which take the third parameter and return multiplication of arguments which is being passed in successive.
+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.
-In Javascript function defined inside has access to outer function variable and function is a first class object so it can be returned by a function as well and passed as the argument in another function.
-- A function is an instance of the Object type
-- A function can have properties and has a link back to its constructor method
-- Function can be stored as variable
-- Function can be pass as a parameter to another function
-- Function can be returned from function
+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.
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+
+## Question 25. What is the difference between a method and a function in javascript?
-## Question 25
-### What is the difference between a method and a function in javascript?
-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).
+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).
```javascript
-// Function definition
+// Function statement
function myFunc() {
// Do some stuff;
}
-// Calling function
+// Calling the function
myFunc();
```
Here myFunc() function call is not associated with object hence not invoked through any object.
-A function can be self-invoking anonymous function or named self-invoking function
+A function can take a form of immediately invoked function expression (IIFE):
```javascript
-// Named Self-invoking Function
-(function myFunc() {
- // Do some stuff;
-})();
// Anonymous Self-invoking Function
(function() {
@@ -860,74 +857,146 @@ A function can be self-invoking anonymous function or named self-invoking functi
})();
```
-In a case of named self-invoking anonymous function or anonymous self-invoking function, there is no need of call function explicitly.
+Finally there are also arrow functions:
+
+```javascript
+const myFunc = 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 this `obj1.myMethod()`, the reference to `obj1` gets assigned (bound) to `this` variable. In other words, the value of `this` will be `obj1` inside `myMethod`.
-A method is a piece of code that is called by name and that is associated with the object. In most respects it is identical to function call except for some key difference:
-- It is implicitly passed for the object for which it was called.
-- It is able to operate on data that is contained within the class (remembering that an object is an instance of a class- the class is the definition, the object is an instance of that)
-- Method call is always associated with object
+Here are some examples of methods:
+##### Example 1
```javascript
-var methodObject = {
+var obj1 = {
attribute: "xyz",
- display: function () { // Method
+ myMethod: function () { // Method
console.log(this.attribute);
}
};
-// Call method
-methodObject.display();
+// Call the method
+obj1.myMethod();
```
-Here methodObject is an object and display is a method which is associated with methodObject.
+Here `obj1` is an object and `myMethod` is a method which is associated with `obj1`.
+
+##### Example 2
+In ES6 we have classes. There the methods will look like this:
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+```javascript
+class MyAwesomeClass {
+ myMethod() {
+ console.log("hi there");
+ }
+}
+const obj1 = new MyAwesomeClass();
+obj1.myMethod();
+```
-## Question 26
-### What is JavaScript Self-Invoking anonymous function or Self-Executing anonymous function.
-A `self-invoking` anonymous function also called `self-executing anonymous function` runs immediately or automatically when we define it and self-invoking anonymous function doesn't have any name at all. Self-Invoking anonymous function syntax:
+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 we **call** a function. Look at that:
```javascript
-(function() {
- console.log("Self-Invoking function code logic ");
-})();
-Output: Self-Invoking function code logic
+var obj1 = {
+ prop1: "buddy"
+};
+var myFunc = 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 obj1
+obj1.myMethod(); // will print "Hi there" following with obj1.
+
```
-We must have to know the fact that JavaScript functions run immediately when we put `()` after their names.
+
+
+## Question 26. What is IIFE (Immediately Invoked Function Expression) and how it can be useful?
+Answer
+
+#### Definition
+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:
```javascript
-function display() {
- console.log("Display me");
-}
-display(); // This will run immediately
+(function() {
+ console.log("Hi, I'm IIFE!");
+})();
+// outputs "Hi, I'm IIFE!"
+```
+#### Explanation
+
+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:
+ ```javascript
+ (function myIIFEFunc() {
+ console.log("Hi, I'm IIFE!");
+ })();
+ // outputs "Hi, I'm IIFE!"
+ ```
+- It can take some parameters:
+ ```javascript
+ (function myIIFEFunc(param1) {
+ console.log("Hi, I'm IIFE, " + param1);
+ })("Yuri");
+ // outputs "Hi, I'm IIFE, Yuri!"
+ ```
+ Here there value `"Yuri"` is passed to the `param1` of the function.
+- It can return a value:
+ ```javascript
+ var result = (function myIIFEFunc(param1) {
+ console.log("Hi, I'm IIFE, " + param1);
+ return 1;
+ })("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.
-Output: "Display me"
-/*
-This will not run immediately as we haven't put () after function
-name, function name is use full when we want to pass it as
-callback to another function or method.
-*/
-display;
+#### Applications and usefulness
-function testCallBack(callback) {
- callback (); // This will be call display method immediately if callback parameter is being set method display
-}
-testCallBack(display); // Here display function is being passed as callback
-```
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+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 ES5
+code, it helps to prevent polluting the global scope and provide the module interface to the outside.
-## Question 27
-### Describe Singleton Pattern In JavaScript?
-The singleton pattern is the most commonly used design pattern and one that you will probably is more than any others. It provides a great 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, there is a different way to achieve singleton object than any other object oriented supported language (Java, C++). 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:
+
+
+## Question 27. Describe Singleton Pattern In JavaScript
+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:
+
+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.
@@ -1022,16 +1091,15 @@ console.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.
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+
+## Question 28. What are the ways of creating objects in JavaScript ?
-## Question 28
-##### What are the way by which we can create object in JavaScript ?
+Answer
-**Method 1:** `Function Based`
+#### Method 1: Function based
-If we want to create several similar `objects`. In below code sample, `Employee` which is called *constructor function*. This is similar to classes in object oriented languages.
+This method is useful if we want to create several similar objects. In the code sample below, we wrote the function `Employee` and used it as a constructor by calling it with the `new` operator.
```javascript
@@ -1044,11 +1112,11 @@ If we want to create several similar `objects`. In below code sample, `Employee`
// Creating multiple object which have similar property but diff value assigned to object property.
var employee1 = new Employee('John', 'Moto', 24, '5000$');
- var employee1 = new Employee('Ryan', 'Jor', 26, '3000$');
- var employee1 = new Employee('Andre', 'Salt', 26, '4000$');
+ var employee2 = new Employee('Ryan', 'Jor', 26, '3000$');
+ var employee3 = new Employee('Andre', 'Salt', 26, '4000$');
```
-**Method 2:** `Object Literal`
+#### Method 2: Object Literal
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.
@@ -1061,7 +1129,7 @@ var employee = {
}
}
```
-Below code sample is Nested Object Literal, Here address is an object inside employee object.
+The code sample below is Nested Object Literal, Here address is an object inside employee object.
```javascript
var employee = {
@@ -1077,9 +1145,9 @@ var employee = {
}
}
```
-**Method 3:** `Using JavaScript new keyword`
+#### Method 3: From `Object` using `new` keyword
-In below code sample object has been created using Object constructor function.
+In the code below, a sample object has been created using `Object`'s constructor function.
```javascript
var employee = new Object(); // Created employee object using new keywords and Object()
@@ -1088,21 +1156,25 @@ employee.getName = function(){
return this.name;
}
```
-**Note:** As a best practices object literal way is used to create object over this method.
-## Question 29
-##### Write a function called deepClone which takes an object and creates a object copy of it.
+#### Method 4:** Using `Object.create`
+
+`Object.create(obj)` will create a new object and set the `obj` 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 use `Object.create(null)` when you don’t want your object to inherit the properties of `Object`.
+
+
+
+## Question 29. Write a function called deepClone which takes an object and creates a object copy of it.
``` javascript
var newObject = deepClone(obj);
```
-Solution:
+Answer
```javascript
function deepClone(object){
var newObject = {};
for(var key in object){
- if(typeof object[key] === 'object'){
+ if(typeof object[key] === 'object' && object[key] !== null ){
newObject[key] = deepClone(object[key]);
}else{
newObject[key] = object[key];
@@ -1129,8 +1201,11 @@ var personalDetail = {
```
So when we do deep clone then we should copy every property (including the nested object).
-## Question 30
-##### Best way to detect `undefined` object property in JavaScript.
+
+
+## Question 30. Best way to detect `undefined` object property in JavaScript.
+
+Answer
> Suppose we have given an object `person`
@@ -1158,8 +1233,9 @@ if(typeof person.salary === 'undefined'){
console.log("salary is undefined here because we haven't declared");
}
```
-## Question 31
-##### Write a function called `Clone` which takes an object and creates a object copy of it but not copy deep property of object.
+
+
+## Question 31. Write a function called `Clone` which takes an object and creates a object copy of it but not copy deep property of object.
```javascript
var objectLit = {foo : 'Bar'};
@@ -1167,7 +1243,7 @@ if(typeof person.salary === 'undefined'){
console.log(cloneObj === Clone(objectLit)); // this should return false
console.log(cloneObj == Clone(objectLit)); // this should return true
```
-**solution:**
+Answer
```javascript
function Clone(object){
@@ -1179,39 +1255,32 @@ function Clone(object){
}
```
-## Question 32
-##### Best way to detect `undefined` object property in JavaScript.
+
-> Suppose we have given an object `person`
+## Question 32. What are promises and how they are useful?
-```javascript
-var person = {
- name: 'Nishant',
- age : 24
-}
-```
-here `person` object has `name` and `age` property. Now we are trying to access **salary** property which we haven't declared on 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.
+Answer
-**Explanation:**
+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` and `rejected`) and works like a state machine.
-We can use `typeof` operator to check undefined
+A promise object has `then` method, where you can specify what to do when the promise is fulfilled or rejected.
-```javascript
-if(typeof someProperty === 'undefined'){
- console.log('something is undefined here');
-}
-```
-Now we are trying to access salary property of person object.
+You can chain `then()` blocks, thus avoiding the callback hell. You can handle errors in the `catch()` block. After a promise is set to fulfilled or rejected state, it becomes immutable.
-```javascript
-if(typeof person.salary === 'undefined'){
- console.log("salary is undefined here because we haven't declared");
-}
-```
-## Question 33
-##### How to check whether a key exist in a JavaScript object or not.
+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, read [one of the articles on a topic](https://opensourceconnections.com/blog/2014/02/16/a-simple-promise-implementation-in-about-20-lines-of-javascript/), and learn the source code of the [simplest promise implementation](https://gist.github.com/softwaredoug/9044640).
+
+
+
->Let say we have `person` object with property **name** and **age**
+## Question 33. How to check whether a key exist in a JavaScript object or not.
+
+Answer
+
+Let say we have `person` object with property **name** and **age**
```javascript
var person = {
@@ -1246,79 +1315,82 @@ console.log(person.hasOwnProperty('name')); // print true
console.log(person.hasOwnProperty('salary')); // print false
```
-## Question 34
-##### Best way to detect `undefined` object property in JavaScript.
-
-> Suppose we have given an object `person`
+
-```javascript
-var person = {
- name: 'Nishant',
- age : 24
-}
-```
-here `person` object has `name` and `age` property. Now we are trying to access **salary** property which we haven't declared on 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.
+## Question 34. What is NaN, why do we need it, and when can it break the page?
-**Explanation:**
+Answer
-We can use `typeof` operator to check undefined
+`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 get `NaN`:
```javascript
-if(typeof someProperty === 'undefined'){
- console.log('something is undefined here');
-}
+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. */
```
-Now we are trying to access salary property of person object.
+
+`NaN` is not equal to any number, it’s not less or more than any number, also it's not equal to itself:
```javascript
-if(typeof person.salary === 'undefined'){
- console.log("salary is undefined here because we haven't declared");
-}
+NaN !== NaN
+NaN < 2 // false
+NaN > 2 // false
+NaN === 2 // false
```
-## Question 35
-##### How to check whether a key exist in a JavaScript object or not.
->Let say we have `person` object with property **name** and **age**
+To check if the current value of the variable is NaN, you have to use the `isNaN` 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](https://ariya.io/2014/05/the-curious-case-of-javascript-nan)
+
+
+
+## Question 35. Fix the bug using ES5 only
```javascript
-var person = {
- name: 'Nishant',
- age: 24
+var arr = [10, 32, 65, 2];
+for (var i = 0; i < arr.length; i++) {
+ setTimeout(function() {
+ console.log('The index of this number is: ' + i);
+ }, 3000);
}
```
-Now we want to check whether `name` property exist in `person` 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.
+Answer
-So how we will check whether property is own property or inherited property.
+For ES6, you can just replace `var i` with `let i`.
-Method 1: We can use `in` operator on objet to check own property or inherited property.
+For ES5, you need to create a function scope like here:
-```javascript
-console.log('name' in person); // checking own property print true
-console.log('salary' in person); // checking undefined property print false
+```javascript
+var arr = [10, 32, 65, 2];
+for (var i = 0; i < arr.length; i++) {
+ setTimeout(function(j) {
+ return function () {
+ console.log('The index of this number is: ' + j)
+ };
+ }(i), 3000);
+}
```
-`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 so `in` operator look into there base property.
-Here
+This can also achieve by forEach (allows you to keep that variable within the forEach’s scope)
-```javascript
-console.log('toString' in person); // Will print true
+```javascript
+var arr = [10, 32, 65, 2];
+arr.forEach(function(ele, i) {
+ setTimeout(function() {
+ console.log('The index of this number is: ' + i);
+ }, 3000);
+})
```
-If we want to test property of object instance not inherited properties then we will use `hasOwnProperty` method of object instance.
-```javascript
-console.log(person.hasOwnProperty('toString')); // print false
-console.log(person.hasOwnProperty('name')); // print true
-console.log(person.hasOwnProperty('salary')); // print false
-```
+
+
+## Question 36. How to check if the value of a variable in an array?
-## Question 36
-##### What is best way to detect an arrays object on JavaScript ?
+Answer
->We always encounter in such situation where we need to know whether value is type of array or not.
+We always encounter in such situation where we need to know whether value is type of array or not.
-For Instance : Below code perform some operation based value type
+For instance : the code below perform some operation based value type
```javascript
function(value){
@@ -1332,9 +1404,21 @@ function(value){
Let's discuss some way to detect an array in JavaScript.
-**Method 1 :**
+**Method 1:**
+
+Juriy Zaytsev (Also known as kangax) proposed an elegant solution to this.
+
+```javascript
+ function isArray(value){
+ return Object.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 test for array type detection
```javascript
// Duck typing arrays
@@ -1353,22 +1437,13 @@ As we can see above isArray method will return true if value object have `sort`
```
Now when you check `isArray(bar)` then it will return true because bar object has sort method, But the fact is bar is not an array.
-So method 1 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.
+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 2:**
-
-Juriy Zaytsev (Also known as kangax) proposed an elegant solution to this.
-
-```javascript
- function isArray(value){
- return Object.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 3:**
->ECMAScript 5 has introduced **Array.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.
+ECMAScript 5 has introduced **Array.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 below code for detecting an value of type array.
+In many JavaScript libraries you may see the code below for detecting an value of type array.
```javascript
function(value){
@@ -1381,24 +1456,48 @@ function(value){
}
```
-## Question 37
-##### Best way to detect reference values of any type in JavaScript ?
+**Method 4:**
-> 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 as **Object**, **Array**, **Function**, **Date**, **null** and **Error**.
-
-Detecting object using `typeof` operator
+You can query the constructor name:
```javascript
-console.log(typeof {}); // object
-console.log(typeof []); // object
-console.log(typeof new Array()); // object
-console.log(typeof null); // object
-console.log(typeof new RegExp()); // object
-console.log(typeof new Date()); // object
+function isArray(value) {
+ return value.constructor.name === "Array";
+}
+
```
-But the downside of using typeof operator to detect an object is that typeof returns `object` for `null` (However this is fact that null is an object in JavaScript).
-The best way to detect an object of specific reference type using `instanceof` operator.
+**Method 5:**
+
+You check if a given value is an `instanceof Array`:
+
+```javascript
+function isArray(value) {
+ return value instanceof Array;
+}
+```
+
+
+
+## Question 37. Best way to detect reference values of any type in JavaScript ?
+
+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 as **Object**, **Array**, **Function**, **Date**, **null** and **Error**.
+
+Detecting object using `typeof` operator
+
+```javascript
+console.log(typeof {}); // object
+console.log(typeof []); // object
+console.log(typeof new Array()); // object
+console.log(typeof null); // object
+console.log(typeof new RegExp()); // object
+console.log(typeof new Date()); // object
+```
+But the downside of using typeof operator to detect an object is that typeof returns `object` for `null` (However this is fact that null is an object in JavaScript).
+
+The best way to detect an object of specific reference type using `instanceof` operator.
>Syntax : **value** instanceof **constructor**
@@ -1424,14 +1523,15 @@ console.log(emp1 instanceof Employee); // true
console.log(emp1 instanceof Object); // true
```
-## Question 38
-##### Describe Object-Based inheritance in JavaScript.
+
+
+## Question 38. How does Object.create method works JavaScript?
-> Object-based inheritance also called prototypal inheritance in which we one object inherit from another object without invoking a constructor function.
+Answer
-The ECMAScript 5 **Object.create()** method is the easiest way for one object to inherit from another.
+The ECMAScript 5 **Object.create()** method is the easiest way for one object to inherit from another, without invoking a constructor function.
-**For Instance:**
+**For instance:**
```javascript
var employee = {
@@ -1445,22 +1545,22 @@ var emp1 = Object.create(employee);
console.log(emp1.displayName()); // output "Nishant"
```
-Above example create a new object `emp1` that inherits from `employee`. Here the inheritance occur as emp1's prototype is set to employee. 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.
+In the example above, we create a new object `emp1` that inherits from `employee`. In other words `emp1`'s prototype is set to `employee`. 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:** Defining displayName() method on emp1 automatically override the employee displayName.
+**For instance:** Defining `displayName()` method on `emp1` will not automatically override the employee `displayName`.
```javascript
emp1.displayName = function() {
console.log('xyz-Anonymous');
};
-employee.displayName();// "xyz-Anonymous"
-emp1.displayName(); // "Nishant"
+employee.displayName(); //Nishant
+emp1.displayName();//xyz-Anonymous
```
-In addition to this **Object.create()** method also allows to specify a second argument which is an object containing additional properties and methods to add to the new object.
+In addition to this **`Object.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**
+**For example**
```javascript
var emp1 = Object.create(employee, {
@@ -1472,14 +1572,15 @@ var emp1 = Object.create(employee, {
emp1.displayName(); // "John"
employee.displayName(); // "Nishant"
```
-In above example, emp1 is created with it's own value for name, so calling **displayName()** method display `"John"` instead of `"Nishant"`.
+In the example above, `emp1` is created with it's own value for name, so calling **displayName()** 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.
+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.
-## Question 39
-##### Describe Type-Based inheritance in JavaScript.
+
->Type-based inheritance works with constructor function instead of object, It means we need to call constructor function of the object from which you want to inherit.
+## Question 39. How to use constructor functions for inheritance in JavaScript?
+
+Answer
Let say we have `Person` class which has name, age, salary properties and **incrementSalary()** method.
@@ -1504,7 +1605,7 @@ function Employee(company){
//Prototypal Inheritance
Employee.prototype = new Person("Nishant", 24,5000);
```
-In above example, **Employee** type inherits from **Person**, which is called super types. It does so by assigning a new instance of Person to Employee prototype. After that, every instance of Employee inherits it's properties and methods from Person.
+In the example above, **Employee** type inherits from **Person**. It does so by assigning a new instance of `Person` to `Employee` prototype. After that, every instance of `Employee` inherits its properties and methods from `Person`.
```javascript
//Prototypal Inheritance
@@ -1538,10 +1639,13 @@ console.log(name in obj); // 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.
-## Question 40
-##### How we can prevent modification of object in JavaScript ?.
+
+
+## Question 40. How we can prevent modification of object in JavaScript ?.
-> 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.
+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:
@@ -1549,7 +1653,7 @@ There are three levels of preventing modification:
No new properties or methods can be added to the object, but one can change the existing properties and method.
-For Example:
+For example:
```javascript
var employee = {
@@ -1567,7 +1671,7 @@ employee.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.
+It is same as prevent extension, in addition to this also prevent existing properties and methods from being deleted.
To seal an object, we use **Object.seal()** method. you can check whether an object is sealed or not using **Object.isSealed();**
@@ -1592,7 +1696,7 @@ when an object is sealed, its existing properties and methods can't be removed.
**3: Freeze :**
->Same as seal, In addition to this prevent existing properties methods from being modified (All properties and methods are read only).
+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();
@@ -1623,7 +1727,7 @@ Frozen objects are considered both non-extensible and sealed.
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:
+For example:
```javascript
"use strict";
@@ -1649,333 +1753,1720 @@ delete employee.name; // fails silently unless it's in strict mode
```
-#Objective Question
+
-## Hoisting
+## Question 41. Write a log function which will add prefix `(your message)` to every message you log using console.log ?
+ For example, If you log `console.log("Some message")` then output should be **(your message) Some message**
-###1. console.log(employeeId);
+ Answer
-1. Some Value
-2. Undefined
-3. Type Error
-4. ReferenceError: employeeId is not defined
+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.
-Answer: 4) ReferenceError: employeeId is not defined
+A general way to do this keep adding your app name in every console.log message like
-###2. What would be the output of following code?
+```javascript
+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
```javascript
-console.log(employeeId);
-var employeeId = '19000';
+function appLog() {
+ var args = 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'
```
-1. Some Value
-2. undefined
-3. Type Error
-4. ReferenceError: employeeId is not defined
+
-Answer: 2) undefined
+## Question 42 . Write a function which will test string as a literal and as an object ?
-###3. What would be the output of following code?
+For example: We can create string using string literal and using String constructor function.
```javascript
-var employeeId = '1234abe';
-(function(){
- console.log(employeeId);
- var employeeId = '122345';
-})();
+ // using string literal
+ var ltrlStr = "Hi I am string literal";
+ // using String constructor function
+ var objStr = new String("Hi I am string object");
```
-1. '122345'
-2. undefined
-3. Type Error
-4. ReferenceError: employeeId is not defined
+Answer
-Answer: 2) undefined
+ We can use typeof operator to test string literal and instanceof operator to test String object.
-## Object
+```javascript
+ function isString(str) {
+ return typeof(str) == 'string' || str instanceof String;
+ }
+
+ var ltrlStr = "Hi I am string literal";
+ var objStr = new String("Hi I am string object");
+ console.log(isString(ltrlStr)); // true
+ console.log(isString(objStr)); // true
+```
+
-###1. What would be the output of following code ?
+## Question 43 . What is typical use case for anonymous function in JavaScript ?
-```javascript
-(function() {
- 'use strict';
+Answer
- var person = {
- name: 'Nishant'
- };
- person.salary = '10000$';
- person['country'] = 'USA';
+ Anonymous functions basically used in following scenario.
- Object.defineProperty(person, 'phoneNo', {
- value: '8888888888',
- enumerable: true
- })
+1. No name is needed if function is only used in one place, then there is no need to add a name to function.
- console.log(Object.keys(person));
-})();
-```
-1. Type Error
-2. undefined
-3. ["name", "salary", "country", "phoneNo"]
-4. ["name", "salary", "country"]
+ Let's take the example of setTimeout function
-Answer: 3) ["name", "salary", "country", "phoneNo"]
+ ```javascript
+ 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.
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+2. 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.
+
+ ```html
+
+ ```
+ Add Event Listener
+
+ ```javascript
+ var btn = document.getElementById('myBtn');
+ btn.addEventListener('click', function () {
+ alert('button clicked');
+ });
+ ```
+
+ Above example shows used of anonymous function as a callback function in event handler.
+
+3. Passing anonymous function as a parameter to calling function.
+
+ Example:
+
+ ```javascript
+ // Function which will execute callback function
+ function processCallback(callback){
+ if(typeof callback === 'function'){
+ callback();
+ }
+ }
+
+ // Call function and pass anonymous function as callback
+ processCallback(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:
-###2. What would be the output of following code ?
+ Will the function which I am going to define, be used anywhere else?
-```javascript
-(function() {
- 'use strict';
+If your answer is yes then go and create named function rather anonymous function.
- var person = {
- name: 'Nishant'
- };
- person.salary = '10000$';
- person['country'] = 'USA';
+**Advantage of using anonymous function:**
- Object.defineProperty(person, 'phoneNo', {
- value: '8888888888',
- enumerable: false
- })
+1. It can reduce a bit of code, particularly in recursive function and in callback function.
+2. Avoid needless global namespace pollutions.
- console.log(Object.keys(person));
-})();
+
+
+## Question 44 . How to set a default parameter value ?
+
+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 :
+
+```python
+// Define sentEmail function
+// configuration : Configuration object
+// provider : Email Service provider, Default would be gmail
+def sentEmail(configuration, provider = 'Gmail'):
+ # Your code logic
```
-1. Type Error
-2. undefined
-3. ["name", "salary", "country", "phoneNo"]
-4. ["name", "salary", "country"]
-
-Answer: 4) ["name", "salary", "country"]
+**In Pre ES6/ES2015**
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+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.
-###3. What would be the output of following code ?
+**Method 1: Setting default parameter value**
```javascript
-(function() {
- var objA = {
- foo: 'foo',
- bar: 'bar'
- };
- var objB = {
- foo: 'foo',
- bar: 'bar'
- };
- console.log(objA == objB);
- console.log(objA === objB);
-}());
+function sentEmail(configuration, provider) {
+ // Set default value if user has not passed value for provider
+ provider = typeof provider !== 'undefined' ? provider : 'Gmail'
+ // Your code logic
+;
+}
+// In this call we are not passing provider parameter value
+sentEmail({
+ from: 'xyz@gmail.com',
+ subject: 'Test Email'
+});
+// Here we are passing Yahoo Mail as a provider value
+sentEmail({
+ from: 'xyz@gmail.com',
+ subject: 'Test Email'
+}, 'Yahoo Mail');
```
-1. false true
-2. false false
-3. true false
-4. true true
-
-Answer: 2) false false
-###4. What would be the output of following code ?
+**Method 2: Setting default parameter value**
```javascript
-(function() {
- var objA = new Object({foo: "foo"});
- var objB = new Object({foo: "foo"});
- console.log(objA == objB);
- console.log(objA === objB);
-}());
+function sentEmail(configuration, provider) {
+ // Set default value if user has not passed value for provider
+ provider = provider || 'Gmail'
+ // Your code logic
+;
+}
+// In this call we are not passing provider parameter value
+sentEmail({
+ from: 'xyz@gmail.com',
+ subject: 'Test Email'
+});
+// Here we are passing Yahoo Mail as a provider value
+sentEmail({
+ from: 'xyz@gmail.com',
+ subject: 'Test Email'
+}, 'Yahoo Mail');
```
-1. false true
-2. false false
-3. true false
-4. true true
-
-Answer: 2) false false
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+**Method 3: Setting default parameter value in ES6**
+```javascript
+function sendEmail(configuration, provider = "Gmail") {
+ // Set default value if user has not passed value for provider
+
+ // Value of provider can be accessed directly
+ console.log(`Provider: ${provider}`);
+}
+// In this call we are not passing provider parameter value
+sentEmail({
+ from: 'xyz@gmail.com',
+ subject: 'Test Email'
+});
+// Here we are passing Yahoo Mail as a provider value
+sentEmail({
+ from: 'xyz@gmail.com',
+ subject: 'Test Email'
+}, 'Yahoo Mail');
+```
-## Array
+
-###1. What would be the output of following code?
+## Question 45. Write code for merge two JavaScript Object dynamically.
+Let say you have two objects
```javascript
-(function() {
- var array = new Array('100');
- console.log(array);
- console.log(array.length);
-}());
-```
+var person = {
+ name : 'John',
+ age : 24
+}
-1. undefined undefined
-2. [undefined × 100] 100
-3. ["100"] 1
-4. ReferenceError: array is not defined
+var address = {
+ 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: 3) ["100"] 1
+Answer
-###2. What would be the output of following code?
+```javascript
+merge(person , address);
+
+/* Now person should have 5 properties
+name , age , addressLine1 , addressLine2 , city */
+```
+**Method 1: Using ES6, Object.assign method**
```javascript
-(function() {
- var array1 = [];
- var array2 = new Array(100);
- var array3 = new Array(['1',2,'3',4,5.6]);
- console.log(array1);
- console.log(array2);
- console.log(array3);
- console.log(array3.length);
-}());
+const merge = (toObj, fromObj) => Object.assign(toObj, fromObj);
```
+
+**Method 2: Without using built-in function**
-1. [] [] [Array[5]] 1
-2. [] [undefined × 100] Array[5] 5
-3. [] [] ['1',2,'3',4,5.6] 5
-4. [] [] [Array[5]] 5
+```javascript
+function merge(toObj, fromObj) {
+ // Make sure both of the parameter is an object
+ if (typeof toObj === 'object' && typeof fromObj === 'object') {
+ for (var pro in fromObj) {
+ // Assign only own properties not inherited properties
+ if (fromObj.hasOwnProperty(pro)) {
+ // Assign property and value
+ toObj[pro] = fromObj[pro];
+ }
+ }
+ }else{
+ throw "Merge function can apply only on object";
+ }
+}
+```
+
-Answer: 1) [] [] [Array[5]] 1
+## Question 46. What is non-enumerable property in JavaScript and how you can create one?
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+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.
-###3. What would be the output of following code?
+Let say we have following object
```javascript
-(function () {
- var array = new Array('a', 'b', 'c', 'd', 'e');
- array[10] = 'f';
- delete array[10];
- console.log(array.length);
-}());
+var person = {
+ name: 'John'
+};
+person.salary = '10000$';
+person['country'] = 'USA';
+
+console.log(Object.keys(person)); // ['name', 'salary', 'country']
```
+As we know that person object properties `name`, `salary` ,`country` are enumerable hence it's shown up when we called Object.keys(person).
-1. 11
-2. 5
-3. 6
-4. undefined
+To create a non-enumerable property we have to use **Object.defineProperty()**. This is a special method for creating non-enumerable property in JavaScript.
+
+```javascript
+var person = {
+ name: 'John'
+};
+person.salary = '10000$';
+person['country'] = 'USA';
-Answer: 1) 11
+// Create non-enumerable property
+Object.defineProperty(person, 'phoneNo',{
+ value : '8888888888',
+ enumerable: false
+})
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+Object.keys(person); // ['name', 'salary', 'country']
+```
+In the example above `phoneNo` property didn't show up because we made it non-enumerable by setting **enumerable:false**
+**Bonus**
-###4. What would be the output of following code?
+Now let's try to change value of `phoneNo`
```javascript
-(function(){
- var animal = ['cow','horse'];
- animal.push('cat');
- animal.push('dog','rat','goat');
- console.log(animal.length);
-})();
+person.phoneNo = '7777777777';
```
-1. 4
-2. 5
-3. 6
-4. undefined
-
-Answer: 3) 6
+**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 has **writable** property, which is `false` 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.
-## Function:
+
-###1. What would be the output of following code ?
+## Question 47. What is Function binding ?
-```javascript
-function funcA(){
- console.log("funcA ", this);
- (function innerFuncA1(){
- console.log("innerFunc1", this);
- (function innerFunA11(){
- console.log("innerFunA11", this);
- })();
- })();
-}
-
-console.log(funcA());
-```
+Answer
-1. funcA Window {...}
- innerFunc1 Window {...}
- innerFunA11 Window {...}
-2. undefined
-3. Type Error
-4. ReferenceError: this is not defined
-
-Answer: 1)
+ 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.
-###2. What would be the output of following code ?
+Let's consider the following example:
```javascript
-var obj = {
- message: "Hello",
- innerMessage: !(function() {
+var clickHandler = {
+ message: 'click event handler',
+ handleClick: function(event) {
console.log(this.message);
- })()
+ }
};
-
-console.log(obj.innerMessage);
+
+var btn = document.getElementById('myBtn');
+// Add click event to btn
+btn.addEventListener('click', clickHandler.handleClick);
```
-1. ReferenceError: this.message is not defined
-2. undefined
-3. Type Error
-4. undefined true
-
-Answer: 4) undefined true
+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 the `click event handler` message but it actually log `undefined`.
-###3. What would the output of following code ?
+The problem of displaying `undefined` is because of the execution context of clickHandler.handleClick method is not being saved hence `this` pointing to button `btn` object. We can fix this issue using bind method.
```javascript
-var obj = {
- message: "Hello",
- innerMessage: function() {
+var clickHandler = {
+ message: 'click event handler',
+ handleClick: function(event) {
console.log(this.message);
}
};
-
-console.log(obj.innerMessage());
+
+var btn = document.getElementById('myBtn');
+// Add click event to btn and bind the clickHandler object
+btn.addEventListener('click', clickHandler.handleClick.bind(clickHandler));
```
-1. Hello
-2. undefined
-3. Type Error
-4. ReferenceError: this.message is not defined
-
-Answer: 1) Hello
+`bind` method is available to all the function similar to call and apply method which take argument value of `this`.
-###4. What would the output of following code ?
+
-```javascript
-var obj = {
- message: 'Hello',
- innerMessage: function () {
- (function () {
- console.log(this.message);
- }());
+### 48. How to replace callbackhell with Promise or Async/Await with examples ?
+
+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.
+
+```js
+const addTen = (num, callback) =>
+ {return callback(num+10, false)}
+```
+
+```js
+const subFive = (num, callback) =>
+ {return callback(num-5, false)}
+```
+
+```js
+const mulTwo = (num, callback) =>
+ {return callback(num*2, false)}
+```
+
+- Now lets call these one by one in nested way.
+- The result of previous will serve as input for next callback.
+
+```js
+const ans = addTen(5, (addRes, addErr) => { // addRess = 15
+ if(!addErr)
+ {
+ return subFive(addRes , (subRes, subErr) => { //subRes = 10
+ if(!subErr){
+ return mulTwo(subRes, (mulRes, mulErr) => {
+ if(!mulErr)
+ {
+ return mulRes; //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.
+
+```js
+const addTen = (num) => {return num+10}
+```
+
+```js
+const subFive = (num) => {return num-5}
+```
+
+```js
+const mulTwo = (num) => {return num*2}
+```
+
+- Creating a promise.
+
+```js
+const promise = new Promise((resolve, reject) => {
+ if(true)
+ resolve(5)
+ else
+ reject("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.
+
+```js
+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.
+
+```js
+const addTen = ( num ) => {
+ return new Promise( ( resolve, reject ) => {
+ resolve( num+10)
+ } )
+}
+```
+
+```js
+const subFive = ( num ) => {
+ return new Promise( ( resolve, reject ) => {
+ resolve( num-5)
+ } )
+}
+```
+
+```js
+const mulTwo = ( num ) => {
+ return new Promise( ( 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.
+
+```js
+const ans = async (num) => {
+ try {
+ var addRes = await addTen(num);
+ var subRes = await subFive(addRes);
+ var mulRes = await mulTwo(subRes);
+ console.log(mulRes)
+ } catch (err) {
+ console.log(err)
+ }
+}
+ans(5)
+```
+
+
+
+# Coding Questions
+
+## Passing values by reference vs by value
+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 reference
+while strings, booleans and numbers are passed by value.
+
+### 1. What would be the output of following code?
+
+```javascript
+var strA = "hi there";
+var strB = strA;
+strB="bye there!";
+console.log (strA)
+```
+
+Answer
+
+The output will be `'hi there'` because we're dealing with strings here. Strings are
+passed by value, that is, copied.
+
+
+
+### 2. What would be the output of following code?
+```javascript
+var objA = {prop1: 42};
+var objB = objA;
+objB.prop1 = 90;
+console.log(objA)
+```
+
+Answer
+
+The output will be `{prop1: 90}` because we're dealing with objects here. Objects are
+passed by reference, that is, `objA` and `objB` point to the same object in memory.
+
+
+
+### 3. What would be the output of following code?
+
+```javascript
+var objA = {prop1: 42};
+var objB = objA;
+objB = {};
+console.log(objA)
+```
+
+
+Answer
+
+The output will be `{prop1: 42}`.
+
+When we assign `objA` to `objB`, the `objB` variable will point
+to the same object as the `objB` variable.
+
+However, when we reassign `objB` to an empty object, we simply change where `objB` variable references to.
+This doesn't affect where `objA` variable references to.
+
+
+
+### 4. What would be the output of following code?
+
+```javascript
+var arrA = [0,1,2,3,4,5];
+var arrB = 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 why
+both `arrA` and `arrB` point to the same array `[0,1,2,3,4,5]`. That's why changing the first
+element of the `arrB` will also modify `arrA`: it's the same array in the memory.
+
+
+
+### 5. What would be the output of following code?
+```javascript
+var arrA = [0,1,2,3,4,5];
+var arrB = arrA.slice();
+arrB[0]=42;
+console.log(arrA)
+```
+
+
+Answer
+
+The output will be `[0,1,2,3,4,5]`.
+
+The `slice` function copies all the elements of the array returning the new array. That's why
+`arrA` and `arrB` reference two completely different arrays.
+
+
+
+### 6. What would be the output of following code?
+
+```javascript
+var arrA = [{prop1: "value of array A!!"}, {someProp: "also value of array A!"}, 3,4,5];
+var arrB = 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. Changing
+`arrB[0]` is the same as changing `arrA[0]`
+
+
+
+### 7. What would be the output of following code?
+
+```javascript
+var arrA = [{prop1: "value of array A!!"}, {someProp: "also value of array A!"},3,4,5];
+var arrB = 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]`.
+
+The `slice` 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:
+
+ ```javascript
+function slice(arr) {
+ var result = [];
+ for (i = 0; i< arr.length; i++) {
+ result.push(arr[i]);
+ }
+ return result;
+}
+```
+
+Look at the line with `result.push(arr[i])`. If `arr[i]` happens to be a number or string,
+it will be passed by value, in other words, copied. If `arr[i]` is an object, it will be passed by reference.
+
+In case of our array `arr[0]` is an object `{prop1: "value of array A!!"}`. Only the reference
+to this object will be copied. This effectively means that arrays arrA and arrB share first
+two elements.
+
+This is why changing the property of `arrB[0]` in `arrB` will also change the `arrA[0]`.
+
+
+
+## Hoisting
+
+### 1. console.log(employeeId);
+
+1. Some Value
+2. Undefined
+3. Type Error
+4. ReferenceError: employeeId is not defined
+
+Answer
+
+ 4) ReferenceError: employeeId is not defined
+
+
+
+### 2. What would be the output of following code?
+
+```javascript
+console.log(employeeId);
+var employeeId = '19000';
+```
+
+1. Some Value
+2. undefined
+3. Type Error
+4. ReferenceError: employeeId is not defined
+
+Answer
+
+ 2) undefined
+
+
+
+### 3. What would be the output of following code?
+
+```javascript
+var employeeId = '1234abe';
+(function(){
+ console.log(employeeId);
+ var employeeId = '122345';
+})();
+```
+
+1. '122345'
+2. undefined
+3. Type Error
+4. ReferenceError: employeeId is not defined
+
+Answer
+
+ 2) undefined
+
+
+
+### 4. What would be the output of following code?
+
+```javascript
+var employeeId = '1234abe';
+(function() {
+ console.log(employeeId);
+ var employeeId = '122345';
+ (function() {
+ var employeeId = 'abc1234';
+ }());
+}());
+```
+
+1. '122345'
+2. undefined
+3. '1234abe'
+4. ReferenceError: employeeId is not defined
+
+Answer
+
+ 2) undefined
+
+
+
+### 5. What would be the output of following code?
+
+```javascript
+(function() {
+ console.log(typeof displayFunc);
+ var displayFunc = function(){
+ console.log("Hi I am inside displayFunc");
+ }
+}());
+```
+
+1. undefined
+2. function
+3. 'Hi I am inside displayFunc'
+4. ReferenceError: displayFunc is not defined
+
+Answer
+
+ 1) undefined
+
+
+
+### 6. What would be the output of following code?
+
+```javascript
+var employeeId = 'abc123';
+function foo(){
+ employeeId = '123bcd';
+ return;
+}
+foo();
+console.log(employeeId);
+```
+
+1. undefined
+2. '123bcd'
+3. 'abc123'
+4. ReferenceError: employeeId is not defined
+
+Answer
+
+ 2) '123bcd'
+
+
+
+### 7. What would be the output of following code?
+
+```javascript
+var employeeId = 'abc123';
+
+function foo() {
+ employeeId = '123bcd';
+ return;
+
+ function employeeId() {}
+}
+foo();
+console.log(employeeId);
+```
+
+1. undefined
+2. '123bcd'
+3. 'abc123'
+4. ReferenceError: employeeId is not defined
+
+Answer
+
+ 3) 'abc123'
+
+
+
+### 8. What would be the output of following code?
+
+```javascript
+var employeeId = 'abc123';
+
+function foo() {
+ employeeId();
+ return;
+
+ function employeeId() {
+ console.log(typeof employeeId);
+ }
+}
+foo();
+```
+
+1. undefined
+2. function
+3. string
+4. ReferenceError: employeeId is not defined
+
+Answer
+
+ 2) 'function'
+
+
+
+### 9. What would be the output of following code?
+
+```javascript
+function foo() {
+ employeeId();
+ var product = 'Car';
+ return;
+
+ function employeeId() {
+ console.log(product);
+ }
+}
+foo();
+```
+
+1. undefined
+2. Type Error
+3. 'Car'
+4. ReferenceError: product is not defined
+
+Answer
+
+ 1) undefined
+
+
+
+### 10. What would be the output of following code?
+
+```javascript
+(function foo() {
+ bar();
+
+ function bar() {
+ abc();
+ console.log(typeof abc);
+ }
+
+ function abc() {
+ console.log(typeof bar);
+ }
+}());
+```
+
+1. undefined undefined
+2. Type Error
+3. function function
+4. ReferenceError: bar is not defined
+
+Answer
+
+ 3) function function
+
+
+
+## Objects
+
+### 1. What would be the output of following code ?
+
+```javascript
+(function() {
+ 'use strict';
+
+ var person = {
+ name: 'John'
+ };
+ person.salary = '10000$';
+ person['country'] = 'USA';
+
+ Object.defineProperty(person, 'phoneNo', {
+ value: '8888888888',
+ enumerable: true
+ })
+
+ console.log(Object.keys(person));
+})();
+```
+1. Type Error
+2. undefined
+3. ["name", "salary", "country", "phoneNo"]
+4. ["name", "salary", "country"]
+
+Answer
+
+ 3) ["name", "salary", "country", "phoneNo"]
+
+
+
+### 2. What would be the output of following code ?
+
+```javascript
+(function() {
+ 'use strict';
+
+ var person = {
+ name: 'John'
+ };
+ person.salary = '10000$';
+ person['country'] = 'USA';
+
+ Object.defineProperty(person, 'phoneNo', {
+ value: '8888888888',
+ enumerable: false
+ })
+
+ console.log(Object.keys(person));
+})();
+```
+1. Type Error
+2. undefined
+3. ["name", "salary", "country", "phoneNo"]
+4. ["name", "salary", "country"]
+
+Answer
+
+ 4) ["name", "salary", "country"]
+
+
+
+### 3. What would be the output of following code ?
+
+```javascript
+(function() {
+ var objA = {
+ foo: 'foo',
+ bar: 'bar'
+ };
+ var objB = {
+ foo: 'foo',
+ bar: 'bar'
+ };
+ console.log(objA == objB);
+ console.log(objA === objB);
+}());
+```
+1. false true
+2. false false
+3. true false
+4. true true
+
+Answer
+
+ 2) false false
+
+
+
+### 4. What would be the output of following code ?
+
+```javascript
+(function() {
+ var objA = new Object({foo: "foo"});
+ var objB = new Object({foo: "foo"});
+ console.log(objA == objB);
+ console.log(objA === objB);
+}());
+```
+1. false true
+2. false false
+3. true false
+4. true true
+
+Answer
+
+ 2) false false
+
+
+
+### 5. What would be the output of following code ?
+
+```javascript
+(function() {
+ var objA = Object.create({
+ foo: 'foo'
+ });
+ var objB = Object.create({
+ foo: 'foo'
+ });
+ console.log(objA == objB);
+ console.log(objA === objB);
+}());
+```
+1. false true
+2. false false
+3. true false
+4. true true
+
+Answer
+
+ 2) false false
+
+
+
+### 6. What would be the output of following code ?
+
+```javascript
+(function() {
+ var objA = Object.create({
+ foo: 'foo'
+ });
+ var objB = Object.create(objA);
+ console.log(objA == objB);
+ console.log(objA === objB);
+}());
+```
+1. false true
+2. false false
+3. true false
+4. true true
+
+Answer
+
+ 2) false false
+
+
+
+### 7. What would be the output of following code ?
+
+```javascript
+(function() {
+ var objA = Object.create({
+ foo: 'foo'
+ });
+ var objB = Object.create(objA);
+ console.log(objA.toString() == objB.toString());
+ console.log(objA.toString() === objB.toString());
+}());
+```
+1. false true
+2. false false
+3. true false
+4. true true
+
+Answer
+
+ 4) true true
+
+
+
+### 8. What would be the output of following code ?
+
+```javascript
+(function() {
+ var objA = Object.create({
+ foo: 'foo'
+ });
+ var objB = objA;
+ console.log(objA == objB);
+ console.log(objA === objB);
+ console.log(objA.toString() == objB.toString());
+ console.log(objA.toString() === objB.toString());
+}());
+```
+1. true true true false
+2. true false true true
+3. true true true true
+4. true true false false
+
+Answer
+
+ 3) true true true true
+
+
+
+### 9. What would be the output of following code ?
+
+```javascript
+(function() {
+ var objA = Object.create({
+ foo: 'foo'
+ });
+ var objB = objA;
+ objB.foo = 'bar';
+ console.log(objA.foo);
+ console.log(objB.foo);
+}());
+```
+1. foo bar
+2. bar bar
+3. foo foo
+4. bar foo
+
+Answer
+
+ 2) bar bar
+
+
+
+### 10. What would be the output of following code ?
+
+```javascript
+(function() {
+ var objA = Object.create({
+ foo: 'foo'
+ });
+ var objB = objA;
+ objB.foo = 'bar';
+
+ delete objA.foo;
+ console.log(objA.foo);
+ console.log(objB.foo);
+}());
+```
+1. foo bar
+2. bar bar
+3. foo foo
+4. bar foo
+
+Answer
+
+ 3) foo foo
+
+
+
+### 11. What would be the output of following code ?
+
+```javascript
+(function() {
+ var objA = {
+ foo: 'foo'
+ };
+ var objB = objA;
+ objB.foo = 'bar';
+
+ delete objA.foo;
+ console.log(objA.foo);
+ console.log(objB.foo);
+}());
+```
+1. foo bar
+2. undefined undefined
+3. foo foo
+4. undefined bar
+
+Answer
+
+ 2) undefined undefined
+
+
+
+## Arrays
+
+### 1. What would be the output of following code?
+
+```javascript
+(function() {
+ var array = new Array('100');
+ console.log(array);
+ console.log(array.length);
+}());
+```
+
+1. undefined undefined
+2. [undefined × 100] 100
+3. ["100"] 1
+4. ReferenceError: array is not defined
+
+Answer
+
+ 3) ["100"] 1
+
+
+
+### 2. What would be the output of following code?
+
+```javascript
+(function() {
+ var array1 = [];
+ var array2 = new Array(100);
+ var array3 = new Array(['1',2,'3',4,5.6]);
+ console.log(array1);
+ console.log(array2);
+ console.log(array3);
+ console.log(array3.length);
+}());
+```
+
+1. [] [] [Array[5]] 1
+2. [] [undefined × 100] Array[5] 1
+3. [] [] ['1',2,'3',4,5.6] 5
+4. [] [] [Array[5]] 5
+
+Answer
+
+ 1) [] [] [Array[5]] 1
+
+
+
+### 3. What would be the output of following code?
+
+```javascript
+(function () {
+ var array = new Array('a', 'b', 'c', 'd', 'e');
+ array[10] = 'f';
+ delete array[10];
+ console.log(array.length);
+}());
+```
+
+1. 11
+2. 5
+3. 6
+4. undefined
+
+Answer
+
+ 1) 11
+
+
+
+### 4. What would be the output of following code?
+
+```javascript
+(function(){
+ var animal = ['cow','horse'];
+ animal.push('cat');
+ animal.push('dog','rat','goat');
+ console.log(animal.length);
+})();
+```
+
+1. 4
+2. 5
+3. 6
+4. undefined
+
+Answer
+
+ 3) 6
+
+
+
+### 5. What would be the output of following code?
+
+```javascript
+(function(){
+ var animal = ['cow','horse'];
+ animal.push('cat');
+ animal.unshift('dog','rat','goat');
+ console.log(animal);
+})();
+```
+
+1. [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ]
+2. [ 'cow', 'horse', 'cat', 'dog', 'rat', 'goat' ]
+3. Type Error
+4. undefined
+
+Answer
+
+ 1) [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ]
+
+
+
+### 6. What would be the output of following code?
+
+```javascript
+(function(){
+ var array = [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 -1 4
+2. 1 0 -1 4
+3. 1 -1 -1 -1
+4. 1 undefined -1 4
+
+Answer
+
+ 1) 1 -1 -1 4
+
+
+
+### 7. What would be the output of following code?
+
+```javascript
+(function(){
+ var array = [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
+2. 1 6 -1
+3. 1 1 -1
+4. 1 undefined undefined
+
+Answer
+
+ 2) 1 6 -1
+
+
+
+### 8. What would be the output of following code?
+
+```javascript
+(function(){
+ var numbers = [2,3,4,8,9,11,13,12,16];
+ var even = numbers.filter(function(element, index){
+ return element % 2 === 0;
+ });
+ console.log(even);
+
+ var containsDivisibleby3 = numbers.some(function(element, index){
+ return element % 3 === 0;
+ });
+
+ console.log(containsDivisibleby3);
+})();
+```
+
+1. [ 2, 4, 8, 12, 16 ] [ 0, 3, 0, 0, 9, 0, 12]
+2. [ 2, 4, 8, 12, 16 ] [ 3, 9, 12]
+3. [ 2, 4, 8, 12, 16 ] true
+4. [ 2, 4, 8, 12, 16 ] false
+
+Answer
+
+ 3) [ 2, 4, 8, 12, 16 ] true
+
+
+
+### 9. What would be the output of following code?
+
+```javascript
+(function(){
+ var containers = [2,0,false,"", '12', true];
+ var containers = containers.filter(Boolean);
+ console.log(containers);
+ var containers = containers.filter(Number);
+ console.log(containers);
+ var containers = containers.filter(String);
+ console.log(containers);
+ var containers = containers.filter(Object);
+ console.log(containers);
+})();
+```
+
+1. [ 2, '12', true ]
+ [ 2, '12', true ]
+ [ 2, '12', true ]
+ [ 2, '12', true ]
+2. [false, true]
+ [ 2 ]
+ ['12']
+ [ ]
+3. [2,0,false,"", '12', true]
+ [2,0,false,"", '12', true]
+ [2,0,false,"", '12', true]
+ [2,0,false,"", '12', true]
+4. [ 2, '12', true ]
+ [ 2, '12', true, false ]
+ [ 2, '12', true,false ]
+ [ 2, '12', true,false]
+
+
+Answer
+
+ 1) [ 2, '12', true ]
+ [ 2, '12', true ]
+ [ 2, '12', true ]
+ [ 2, '12', true ]
+
+
+
+### 10. What would be the output of following code?
+
+```javascript
+(function(){
+ var list = ['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);
+})();
+```
+
+1. [ 'bar', 'john', 'ritz' ]
+ [ 'bar', 'john' ]
+ [ 'foo', 'bar', 'john', 'ritz' ]
+ []
+ [ 'foo', 'bar', 'john', 'ritz' ]
+2. [ 'bar', 'john', 'ritz' ]
+ [ 'bar', 'john','ritz ]
+ [ 'foo', 'bar', 'john', 'ritz' ]
+ []
+ [ 'foo', 'bar', 'john', 'ritz' ]
+3. [ 'john', 'ritz' ]
+ [ 'bar', 'john' ]
+ [ 'foo', 'bar', 'john', 'ritz' ]
+ []
+ [ 'foo', 'bar', 'john', 'ritz' ]
+4. [ 'foo' ]
+ [ 'bar', 'john' ]
+ [ 'foo', 'bar', 'john', 'ritz' ]
+ []
+ [ 'foo', 'bar', 'john', 'ritz' ]
+
+Answer
+
+ 1) [ 'bar', 'john', 'ritz' ]
+ [ 'bar', 'john' ]
+ [ 'foo', 'bar', 'john', 'ritz' ]
+ []
+ [ 'foo', 'bar', 'john', 'ritz' ]
+
+
+
+### 11. What would be the output of following code?
+
+```javascript
+(function(){
+ var list = ['foo','bar','john'];
+ console.log(list.splice(1));
+ console.log(list.splice(1,2));
+ console.log(list);
+})();
+```
+
+1. [ 'bar', 'john' ] [] [ 'foo' ]
+2. [ 'bar', 'john' ] [] [ 'bar', 'john' ]
+3. [ 'bar', 'john' ] [ 'bar', 'john' ] [ 'bar', 'john' ]
+4. [ 'bar', 'john' ] [] []
+
+Answer
+
+ 1. [ 'bar', 'john' ] [] [ 'foo' ]
+
+
+
+### 12. What would be the output of following code?
+
+```javascript
+(function(){
+ var arrayNumb = [2, 8, 15, 16, 23, 42];
+ arrayNumb.sort();
+ console.log(arrayNumb);
+})();
+```
+
+1. [2, 8, 15, 16, 23, 42]
+2. [42, 23, 26, 15, 8, 2]
+3. [ 15, 16, 2, 23, 42, 8 ]
+4. [ 2, 8, 15, 16, 23, 42 ]
+
+Answer
+
+ 3. [ 15, 16, 2, 23, 42, 8 ]
+
+
+
+## Functions
+
+### 1. What would be the output of following code ?
+
+```javascript
+function funcA(){
+ console.log("funcA ", this);
+ (function innerFuncA1(){
+ console.log("innerFunc1", this);
+ (function innerFunA11(){
+ console.log("innerFunA11", this);
+ })();
+ })();
+}
+
+console.log(funcA());
+```
+
+1. funcA Window {...}
+ innerFunc1 Window {...}
+ innerFunA11 Window {...}
+2. undefined
+3. Type Error
+4. ReferenceError: this is not defined
+
+Answer
+
+ 1) funcA Window {...}
+ innerFunc1 Window {...}
+ innerFunA11 Window {...}
+
+
+
+### 2. What would be the output of following code ?
+
+```javascript
+var obj = {
+ message: "Hello",
+ innerMessage: !(function() {
+ console.log(this.message);
+ })()
+};
+
+console.log(obj.innerMessage);
+```
+
+1. ReferenceError: this.message is not defined
+2. undefined
+3. Type Error
+4. undefined true
+
+Answer
+
+ 4) undefined true
+
+
+
+### 3. What would be the output of following code ?
+
+```javascript
+var obj = {
+ message: "Hello",
+ innerMessage: function() {
+ return this.message;
+ }
+};
+
+console.log(obj.innerMessage());
+```
+
+1. Hello
+2. undefined
+3. Type Error
+4. ReferenceError: this.message is not defined
+
+Answer
+
+ 1) Hello
+
+
+
+### 4. What would be the output of following code ?
+
+```javascript
+var obj = {
+ message: 'Hello',
+ innerMessage: function () {
+ (function () {
+ console.log(this.message);
+ }());
+ }
+};
+console.log(obj.innerMessage());
+```
+
+1. Type Error
+2. Hello
+3. undefined
+4. ReferenceError: this.message is not defined
+
+Answer
+
+ 3) undefined
+
+
+
+### 5. What would be the output of following code ?
+
+```javascript
+var obj = {
+ message: 'Hello',
+ innerMessage: function () {
+ var self = this;
+ (function () {
+ console.log(self.message);
+ }());
}
};
console.log(obj.innerMessage());
```
-1. Type Error
-2. Hello
+1. Type Error
+2. 'Hello'
+3. undefined
+4. ReferenceError: self.message is not defined
+
+Answer
+
+ 2) 'Hello'
+
+
+
+### 6. What would be the output of following code ?
+
+```javascript
+function myFunc(){
+ console.log(this.message);
+}
+myFunc.message = "Hi John";
+
+console.log(myFunc());
+```
+
+1. Type Error
+2. 'Hi John'
+3. undefined
+4. ReferenceError: this.message is not defined
+
+Answer
+
+ 3) undefined
+
+
+
+### 7. What would be the output of following code ?
+
+```javascript
+function myFunc(){
+ console.log(myFunc.message);
+}
+myFunc.message = "Hi John";
+
+console.log(myFunc());
+```
+
+1. Type Error
+2. 'Hi John'
+3. undefined
+4. ReferenceError: this.message is not defined
+
+Answer
+
+ 2) 'Hi John'
+
+
+
+### 8. What would be the output of following code ?
+
+```javascript
+function myFunc() {
+ myFunc.message = 'Hi John';
+ console.log(myFunc.message);
+}
+console.log(myFunc());
+```
+
+1. Type Error
+2. 'Hi John'
+3. undefined
+4. ReferenceError: this.message is not defined
+
+Answer
+
+ 2) 'Hi John'
+
+
+
+### 9. What would be the output of following code ?
+
+```javascript
+function myFunc(param1,param2) {
+ console.log(myFunc.length);
+}
+console.log(myFunc());
+console.log(myFunc("a","b"));
+console.log(myFunc("a","b","c","d"));
+```
+
+1. 2 2 2
+2. 0 2 4
3. undefined
-4. ReferenceError: this.message is not defined
+4. ReferenceError
+
+Answer
+
+ a) 2 2 2
+
+
+
+### 10. What would be the output of following code ?
+
+```javascript
+function myFunc() {
+ console.log(arguments.length);
+}
+console.log(myFunc());
+console.log(myFunc("a","b"));
+console.log(myFunc("a","b","c","d"));
+```
+
+1. 2 2 2
+2. 0 2 4
+3. undefined
+4. ReferenceError
-Answer: 3) undefined
+Answer
+
+ 2) 0 2 4
+
+
## Object Oriented
-###1. What would the output of following code ?
+### 1. What would be the output of following code ?
```javascript
function Person(name, age){
@@ -1991,37 +3482,610 @@ Person.displayName = function(){
console.log(this.name);
}
-var person1 = new Person('Nishant');
+var person1 = new Person('John');
person1.displayName();
Person.displayName();
```
-1. Nishant Person
-2. Nishant John
-3. Nishant undefined
+1. John Person
+2. John John
+3. John undefined
4. John John
-Answer: 1) Nishant Person
+Answer
+
+ 1) John Person
+
+
+
+## Scopes
+
+### 1. What would be the output of following code ?
+
+```javascript
+function passWordMngr() {
+ var password = '12345678';
+ this.userName = 'John';
+ return {
+ pwd: password
+ };
+}
+// Block End
+var userInfo = passWordMngr();
+console.log(userInfo.pwd);
+console.log(userInfo.userName);
+```
+
+1. 12345678 Window
+2. 12345678 John
+3. 12345678 undefined
+4. undefined undefined
+
+Answer
+
+ 3) 12345678 undefined
+
+
+
+### 2. What would be the output of following code ?
+
+```javascript
+var employeeId = 'aq123';
+function Employee() {
+ this.employeeId = 'bq1uy';
+}
+console.log(Employee.employeeId);
+```
+
+1. Reference Error
+2. aq123
+3. bq1uy
+4. undefined
+
+Answer
+
+ 4) undefined
+
+
+
+### 3. What would be the output of following code ?
+
+```javascript
+var employeeId = 'aq123';
+
+function Employee() {
+ this.employeeId = 'bq1uy';
+}
+console.log(new Employee().employeeId);
+Employee.prototype.employeeId = 'kj182';
+Employee.prototype.JobId = '1BJKSJ';
+console.log(new Employee().JobId);
+console.log(new Employee().employeeId);
+```
+
+1. bq1uy 1BJKSJ bq1uy undefined
+2. bq1uy 1BJKSJ bq1uy
+3. bq1uy 1BJKSJ kj182
+4. undefined 1BJKSJ kj182
+
+Answer
+
+ 2) bq1uy 1BJKSJ bq1uy
+
+
+
+### 4. What would be the output of following code ?
+
+```javascript
+var employeeId = 'aq123';
+(function Employee() {
+ try {
+ throw 'foo123';
+ } catch (employeeId) {
+ console.log(employeeId);
+ }
+ console.log(employeeId);
+}());
+```
+
+1. foo123 aq123
+2. foo123 foo123
+3. aq123 aq123
+4. foo123 undefined
+
+Answer
+
+ 1) foo123 aq123
+
+
+
+## Call, Apply, Bind
+
+### 1. What would be the output of following code ?
+
+```javascript
+(function() {
+ var greet = 'Hello World';
+ var toGreet = [].filter.call(greet, function(element, index) {
+ return index > 5;
+ });
+ console.log(toGreet);
+}());
+```
+
+1. Hello World
+2. undefined
+3. World
+4. [ 'W', 'o', 'r', 'l', 'd' ]
+
+Answer
+
+ 4) [ 'W', 'o', 'r', 'l', 'd' ]
+
+
+
+### 2. What would be the output of following code ?
+
+```javascript
+(function() {
+ var fooAccount = {
+ name: 'John',
+ amount: 4000,
+ deductAmount: function(amount) {
+ this.amount -= amount;
+ return 'Total amount left in account: ' + this.amount;
+ }
+ };
+ var barAccount = {
+ name: 'John',
+ amount: 6000
+ };
+ var withdrawAmountBy = function(totalAmount) {
+ return fooAccount.deductAmount.bind(barAccount, totalAmount);
+ };
+ console.log(withdrawAmountBy(400)());
+ console.log(withdrawAmountBy(300)());
+}());
+```
+
+1. Total amount left in account: 5600 Total amount left in account: 5300
+2. undefined undefined
+3. Total amount left in account: 3600 Total amount left in account: 3300
+4. Total amount left in account: 5600 Total amount left in account: 5600
+
+Answer
+
+ 1) Total amount left in account: 5600 Total amount left in account: 5300
+
+
+
+### 3. What would be the output of following code ?
+
+```javascript
+(function() {
+ var fooAccount = {
+ name: 'John',
+ amount: 4000,
+ deductAmount: function(amount) {
+ this.amount -= amount;
+ return this.amount;
+ }
+ };
+ var barAccount = {
+ name: 'John',
+ amount: 6000
+ };
+ var withdrawAmountBy = function(totalAmount) {
+ return fooAccount.deductAmount.apply(barAccount, [totalAmount]);
+ };
+ console.log(withdrawAmountBy(400));
+ console.log(withdrawAmountBy(300));
+ console.log(withdrawAmountBy(200));
+}());
+```
+
+1. 5600 5300 5100
+2. 3600 3300 3100
+3. 5600 3300 5100
+4. undefined undefined undefined
+
+Answer
+
+ 1) 5600 5300 5100
+
+
+
+### 4. What would be the output of following code ?
+
+```javascript
+(function() {
+ var fooAccount = {
+ name: 'John',
+ amount: 6000,
+ deductAmount: function(amount) {
+ this.amount -= amount;
+ return this.amount;
+ }
+ };
+ var barAccount = {
+ name: 'John',
+ amount: 4000
+ };
+ var withdrawAmountBy = function(totalAmount) {
+ return fooAccount.deductAmount.call(barAccount, totalAmount);
+ };
+ console.log(withdrawAmountBy(400));
+ console.log(withdrawAmountBy(300));
+ console.log(withdrawAmountBy(200));
+}());
+```
+
+1. 5600 5300 5100
+2. 3600 3300 3100
+3. 5600 3300 5100
+4. undefined undefined undefined
+
+Answer
+
+ 2) 3600 3300 3100
+
+
+
+### 5. What would be the output of following code ?
+
+```javascript
+(function greetNewCustomer() {
+ console.log('Hello ' + this.name);
+}.bind({
+ name: 'John'
+})());
+```
+
+1. Hello John
+2. Reference Error
+3. Window
+4. undefined
+
+Answer
+
+ 1) Hello John
+
+
+
+### 6. Suggest your question!
+
+
+## Callback Functions
+
+### 1. What would be the output of following code ?
+
+```javascript
+function getDataFromServer(apiUrl){
+ var name = "John";
+ return {
+ then : function(fn){
+ fn(name);
+ }
+ }
+}
+
+getDataFromServer('www.google.com').then(function(name){
+ console.log(name);
+});
+
+```
+
+1. John
+2. undefined
+3. Reference Error
+4. fn is not defined
+
+Answer
+
+ 1) John
+
+
+
+### 2. What would be the output of following code ?
+
+```javascript
+(function(){
+ var arrayNumb = [2, 8, 15, 16, 23, 42];
+ Array.prototype.sort = function(a,b){
+ return a - b;
+ };
+ arrayNumb.sort();
+ console.log(arrayNumb);
+})();
+
+(function(){
+ var numberArray = [2, 8, 15, 16, 23, 42];
+ numberArray.sort(function(a,b){
+ if(a == b){
+ return 0;
+ }else{
+ return a < b ? -1 : 1;
+ }
+ });
+ console.log(numberArray);
+})();
+
+(function(){
+ var numberArray = [2, 8, 15, 16, 23, 42];
+ numberArray.sort(function(a,b){
+ return a-b;
+ });
+ console.log(numberArray);
+})();
+```
+
+1. [ 2, 8, 15, 16, 23, 42 ]
+ [ 2, 8, 15, 16, 23, 42 ]
+ [ 2, 8, 15, 16, 23, 42 ]
+2. undefined undefined undefined
+3. [42, 23, 16, 15, 8, 2]
+ [42, 23, 16, 15, 8, 2]
+ [42, 23, 16, 15, 8, 2]
+4. Reference Error
+
+Answer
+
+ 1) [ 2, 8, 15, 16, 23, 42 ]
+ [ 2, 8, 15, 16, 23, 42 ]
+ [ 2, 8, 15, 16, 23, 42 ]
+
+
+
+## Return Statement
+
+### 1. What would be the output of following code ?
+
+```javascript
+(function(){
+ function sayHello(){
+ var name = "Hi John";
+ return
+ {
+ fullName: name
+ }
+ }
+ console.log(sayHello().fullName);
+})();
+```
+
+1. Hi John
+2. undefined
+3. Reference Error
+4. Uncaught TypeError: Cannot read property 'fullName' of undefined
+
+Answer
+
+ 4) Uncaught TypeError: Cannot read property 'fullName' of undefined
+
+
+
+### 2. What would be the output of following code ?
+
+```javascript
+function getNumber(){
+ return (2,4,5);
+}
+
+var numb = getNumber();
+console.log(numb);
+```
+
+1. 5
+2. undefined
+3. 2
+4. (2,4,5)
+
+Answer
+
+ 1) 5
+
+
+
+### 3. What would be the output of following code ?
+
+```javascript
+function getNumber(){
+ return;
+}
+
+var numb = getNumber();
+console.log(numb);
+```
+
+1. null
+2. undefined
+3. ""
+4. 0
+
+Answer
+
+ 2) undefined
+
+
+
+### 4. What would be the output of following code ?
+
+```javascript
+function mul(x){
+ return function(y){
+ return [x*y, function(z){
+ return x*y + z;
+ }];
+ }
+}
+
+console.log(mul(2)(3)[0]);
+console.log(mul(2)(3)[1](4));
+```
+
+1. 6, 10
+2. undefined undefined
+3. Reference Error
+4. 10, 6
+
+Answer
+
+ 1) 6, 10
+
+
+
+### 5. What would be the output of following code ?
+
+```javascript
+function mul(x) {
+ return function(y) {
+ return {
+ result: x * y,
+ sum: function(z) {
+ return x * y + z;
+ }
+ };
+ };
+}
+console.log(mul(2)(3).result);
+console.log(mul(2)(3).sum(4));
+```
+
+1. 6, 10
+2. undefined undefined
+3. Reference Error
+4. 10, 6
+
+Answer
+
+ 1) 6, 10
+
+
+
+### 6. What would be the output of following code ?
+
+```javascript
+function mul(x) {
+ return function(y) {
+ return function(z) {
+ return function(w) {
+ return function(p) {
+ return x * y * z * w * p;
+ };
+ };
+ };
+ };
+}
+console.log(mul(2)(3)(4)(5)(6));
+```
+
+1. 720
+2. undefined
+3. Reference Error
+4. Type Error
+
+Answer
+
+ 1) 720
+
+
+
+### 7. What would be the output of following code ?
+
+```javascript
+function getName1(){
+ console.log(this.name);
+}
+
+Object.prototype.getName2 = () =>{
+ console.log(this.name)
+}
+
+let personObj = {
+ name:"Tony",
+ print:getName1
+}
+
+personObj.print();
+personObj.getName2();
+```
+
+1. undefined undefined
+2. Tony undefined
+3. undefined Tony
+4. Tony Tony
+
+Answer
+
+ 2) Tony undefined
+
+Explaination: **getName1()** function works fine because it's being called from ***personObj***, so it has access to *this.name* property. But when while calling **getnName2** which is defined under *Object.prototype* doesn't have any proprty named *this.name*. There should be *name* property under prototype. Following is the code:
+
+```javascript
+function getName1(){
+ console.log(this.name);
+}
-## Have doubt in this question ??
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+Object.prototype.getName2 = () =>{
+ console.log(Object.getPrototypeOf(this).name);
+}
+
+let personObj = {
+ name:"Tony",
+ print:getName1
+}
+
+personObj.print();
+Object.prototype.name="Steve";
+personObj.getName2();
+```
+
+
+
+### 8 . What would be the output of the following code ?
+```javascript
+let a = true;
+let c = 0;
-## This Book will be completed by June 1 2016 and available to buy. If you want me to sent early copy of this book then please add your name and email address in google form here [Google Form](http://goo.gl/forms/QSpxVtvsNb).
+setTimeout(() => {
+ a = false;
+},2000)
-##Contributing
+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.
+
+
+### 9 . What would be the output of the following code ?
+```javascript
+
+let c=0;
+
+let id = setInterval(() => {
+ console.log(c++)
+},200)
+
+setTimeout(() => {
+ clearInterval(id)
+},2000)
+```
-I'm always welcome to 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.
+Answer
+The above program will print 0 to 9 sequentially.
+
-####Note: All contributor to this book will be added as contributor in Book Last page by default, So if you have contributed and don't wanted to be included then please write an email to me at nihantanu@gmail.com
+## Contributing
-##For any other query:
-[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion)
+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.
-##License
+## License
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 Nishant Kumar, 2016.
+Copyright Iurii Katkov and Nishant Kumar, 2017.