From 1564ccd0d41dcd78bc6401dffb132e19864d1d06 Mon Sep 17 00:00:00 2001 From: ironmaniiith Date: Fri, 11 Nov 2016 09:04:40 +0530 Subject: [PATCH 001/112] Minor typos fix --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fd68472..d5f08f3 100644 --- a/README.md +++ b/README.md @@ -86,13 +86,13 @@ var Employee = function (name, company, salary) { this.salary = salary || 5000; //Public attribute default value is null // Private method - var increaseSlary = function () { + var increaseSalary = function () { this.salary = this.salary + 1000; }; // Public method this.dispalyIncreasedSalary = function() { - increaseSlary(); + increaseSalary(); console.log(this.salary); }; }; From bac96cf43b28d205bfdc4ad401baae75e177a589 Mon Sep 17 00:00:00 2001 From: ironmaniiith Date: Fri, 11 Nov 2016 17:02:47 +0530 Subject: [PATCH 002/112] Corrected minor mistake in section 4 removing the actual code out of comments --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fd68472..7512c15 100644 --- a/README.md +++ b/README.md @@ -137,8 +137,10 @@ var globalVar = "abc"; "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 scope innerFunction + })(5); // Pass 5 as parameter +// end of scope outerFunction +})(7); // Pass 7 as parameter ``` `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`. From 8cb5e8af74d7875d31347cbf7dbd3bfd0f03a840 Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Fri, 5 May 2017 10:17:42 +0530 Subject: [PATCH 003/112] Update Nishant_resume.js --- Nishant_resume.js | 96 +++++++++++++++++++++++++++++++++++++---------- 1 file changed, 77 insertions(+), 19 deletions(-) diff --git a/Nishant_resume.js b/Nishant_resume.js index 50d65cc..113a5e5 100644 --- a/Nishant_resume.js +++ b/Nishant_resume.js @@ -1,8 +1,17 @@ /** * 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. + * Hi there, I am Nishant. I am Software Architect @GetMyParking, + * Mozila Tech Contributor, Teacher at CodeInstitute (Dublin), CodeMentor Front-end Expert, + * JavaScript Interview Question Author from India. + * + * I love to pair program and ship quality code that's solidly tested. + * Skills that I'm proficient in and continue to learn with: Object Oriented JavaScript, + * JavaScript Design Pattern, MVC, Client Side Performance Optimization, Node.js, Angular.js, + * Backbone.js, Vue.js, HTML5 and Tools: Git jasmine Test Framework, Grunt, webpack, bower, yoman. + * + * Domain: Cloud Computing, Distributed Systems, Big Data, SOA, Data mining, Hadoop, NoSQL and Graph Database. + * */ (function() { @@ -11,29 +20,76 @@ /* About Me */ - var me = { + const me = { name: 'Nishant Kumar', - job: 'UI Engineering Lead', - organization: 'Big Parser', - status: 'Not availble for Hire full time', - location: 'India', - experience: '5 years', + job: 'Software Architect', + organization: 'GetMyParking', + status: 'Not availble for hire', + location: 'Noida, India', + experience: '5+ years', skills: { - 'scripting-language' :['javascript'] - 'frameworks': ['angular.js','backbone.js','sails.js'], + 'scripting-language' :['JavaScript','ECMAScript 6'] + 'frameworks': ['angular.js','React','Vue','Vuex','backbone.js','IONIC','sails.js'], 'library' : ['jQuery'] - 'tools': ['Gulp', 'Grunt', 'bower','yoman','Git'], - 'testing': ['jasmine', 'protractor'], - 'backend': ['node.js', 'express.js'], + 'tools': ['Webpack','Gulp', 'Grunt', 'bower','yoman','Git'], + 'testing': ['Jasmine', 'Protractor'], + 'backend': ['Node.js', 'Express.js','Python'], 'dataBase': ['mongoDb', 'SQL'], 'uncategorized' : ['C','C#','HTML','CSS', 'HTML5','JSON'] - } + }, + work_experience:[{ + 'company' : 'GetMyParking', + 'position': 'Software Architect', + 'duration': 'Jan 2017 - April 2017', + 'location': 'New Delhi', + 'job_type': 'Contract', + 'responsibility': { + "1": 'Responsible for designing and implementing development infrastructure', + "2": 'Manage risk identification and risk mitigation strategies associated with the architecture', + "3": 'Plan for new technology insertion', + "4": 'Make sure the right modeling is being done, to know that qualities like performance are going to be met', + "5": 'Commitment to following dev "best practices", with code-reviews, unit tests, etc.', + "6": 'Migrating monolithic base code to microservice based architecture to support million transaction per day', + "7": 'Creating and ensuring best practices properly followed for Node JS, and React JS based app.' + },{ + 'company' : 'Engineering Lead', + 'position' : 'BigParser.com', + 'duration' : 'Aug 2014 - Dec 2016', + 'location' : 'Pilani, New Delhi', + 'job_type': 'Contract, Hourly,Remotely', + 'responsibility': { + "1": 'Understanding Product Feature and Functionality Requirements of the Platform', + "2": 'Working with the Design and Architecture teams on design and framework issues.', + "3": 'Working interactions on all platforms including mobile devices', + "4": 'Developing client side MVC frameworks and Creating UI Libraries and using Angular/React JS', + "5": 'Optimize Performance through improved design', + "6": 'Working with the Back End teams on Server side integration of the Platform.', + "7": 'Providing Level 2 and Level 3, support of the UI and Partner Products in Testing, Stage and Client facing Production Environments.', + "8": 'Vertical Specific Customization of Cloud Platform including interfaces to Gmail, Dropbox, Box.Net' + },{ + 'company' : 'Sr. Software Engineering', + 'position' : 'Mindfire Solutions', + 'duration' : 'June 2011 - July 2014', + 'location' : 'Bhubaneswar, New Delhi', + 'job_type': 'Full Time', + 'responsibility': { + "1": 'Analyzed the business requirement with the project manager for different clients', + "2": 'Developed the Technical and functional specifications.', + "3": 'Developed the web based solutions and windows based solutions for various clients.', + "4": 'Perform monthly performance review of the application ', + "5": 'Developed a custom GUI for the ease of users', + "6": 'Developed discussion forum for internal use of knowledge flow within the organization.', + "7": 'Providing Level 2 and Level 3, support of the UI and Partner Products in Testing, Stage and Client facing Production Environments.', + "8": 'Trained the intern coming from various collages' + } + }], + 'notes': 'For project details & more work exp details please refer my linkedIn profile.' }; /* Contact Details */ - var me_contact = { + const me_contact = { 'email' : 'nihantanu@gmail.com', 'skypeId' : 'mfsi_nishantk', 'linkedIn' :'http://in.linkedin.com/in/nishantkumar1' @@ -45,18 +101,20 @@ /* Education */ - var education = { + const education = { 'post-Graduate': { 'college': 'Birla Institute of Technology and Science, Pilani', 'Major' : 'Software System', - 'Year' :'2016' + 'Year' :'2014-2016', + 'type': 'Regular, Pilani Campus' }, 'graduation' : { 'college': 'ICFAI University, Dehradun', 'Major' : 'Computer Science & Engineering', - 'Year' :'2011' + 'Year' :'2007-2011', + 'type': 'Regular' } - } + }, /** * Nice things people have said about me. From e11dded2d1b227a8cb04058d4c59dc828677a4f3 Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Fri, 5 May 2017 10:19:20 +0530 Subject: [PATCH 004/112] Update Nishant_resume.js --- Nishant_resume.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Nishant_resume.js b/Nishant_resume.js index 113a5e5..fdabaa4 100644 --- a/Nishant_resume.js +++ b/Nishant_resume.js @@ -34,7 +34,7 @@ 'tools': ['Webpack','Gulp', 'Grunt', 'bower','yoman','Git'], 'testing': ['Jasmine', 'Protractor'], 'backend': ['Node.js', 'Express.js','Python'], - 'dataBase': ['mongoDb', 'SQL'], + 'dataBase': ['mongoDb', 'MYSQL'], 'uncategorized' : ['C','C#','HTML','CSS', 'HTML5','JSON'] }, work_experience:[{ From 3651071b9adb81b9a75419bdcc02ed0742243cfb Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Mon, 15 May 2017 22:39:33 +0530 Subject: [PATCH 005/112] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3dde5de..f750866 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ ![](coverPage.png) -## 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). +## This Book will be completed by Aug 1 2017 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). [![Join the chat at https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question](https://badges.gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question.svg)](https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) @@ -2008,7 +2008,7 @@ Answer: 1) Nishant Person ## Have doubt in this question ?? [Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) -## 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). +## This Book will be completed by Aug 1 2017 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). ##Contributing From 7e6c41ce3dc7c1bd68454bf2ec436e5745e5f5fe Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Tue, 30 May 2017 21:03:58 +0530 Subject: [PATCH 006/112] Added Some more exciting questions --- README.md | 1424 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 1377 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index f750866..d2f3b18 100644 --- a/README.md +++ b/README.md @@ -1651,6 +1651,319 @@ delete employee.name; // fails silently unless it's in strict mode ``` +## Question 44 +##### 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** + +Logging error message or some informative message is always required when you dealing with client side JavaScript using console.log method. Some time you want to add some prefix to identify message generated log from your application hence you would like to prefix your app name in every console.log. + +A general way to do this keep adding your app name in every console.log message like + +```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 +function appLog() { + var args = Array.prototype.slice.call(argument); + args.unshift('your app name'); + console.log.apply(console, args); +} + +console.log(appLog("Some error message")); +//output of above console: 'your app name Some error message' +``` + +## Question 45 +##### Write a function which will test string as a literal and as an object ? + +For example: We can create string using string literal and using String constructor function. + +```javascript + // using string literal + var ltrlStr = "Hi I am string literal"; + // using String constructor function + var objStr = new String("Hi I am string object"); +``` +> We can use typeof operator to test string literal and instanceof operator to test String 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 +``` +## Question 46 +##### What is typical use case for anonymous function in JavaScript ? + +> Anonymous functions basically used in following scenario. + +1. No name is needed if function is only used in one place, then there is no need to add a name to function. + + Let's take the example of setTimeout function + + ```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. + +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 take decision for using anonymous function is to asked. + +> Will the function which I am going to define will use anywhere else. + +If your answer is yes then go and create named function rather anonymous function. + +**Advantage of using anonymous function:** + +1. It can reduce a bit of code, particularly in recursive function and in callback function. +2. Avoid needless global namespace pollutions. + +## Question 47 +##### How to set a default parameter value ? + +> 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 +``` +**In Pre ES6/ES2015** + +There are a lot of ways by which you can achieve this in pre ES2015. + +Let's understand below code by which we achieved setting default parameter value. + +**Method 1: Setting default parameter value** + +```javascript +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'); +``` + +**Method 2: Setting default parameter value** + +```javascript +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'); +``` + +## Question 48 +##### Write code for merge two JavaScript Object dynamically. +> Let say you have two object + +```javascript +var person = { + name : 'John', + age : 24 +} + +var location = { + 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. + +```javascript +merge(person , location); + +/* Now person should have 5 properties +name , age , addressLine1 , addressLine2 , city */ +``` +**Method 1: Using ES6, Object assign method** + +```javascript +function merge(toObj,fromObj){ + return Object.assign(person,location); +} +``` + +**Method 2: Without using in-built function** + +```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"; + } +} +``` +## Question 49 +##### What is non-enumerable property in JavaScript and how can create ? + +>Object can have properties that don't show up when you iterate through object using for...in loop or using Object.keys() to get an array of property names. This properties is know as non-enumerable properties. + +Let say we have following object + +```javascript +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). + +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'; + +// Create non-enumerable property +Object.defineProperty(person, 'phoneNo',{ + value : '8888888888', + enumerable: false +}) + +Object.keys(person); // ['name', 'salary', 'country'] +``` +In above example `phoneNo` property didn't show up because we made it non-enumerable by setting **enumerable:false** + +Now let's try to change value of `phoneNo` + +```javascript +person.phoneNo = '7777777777'; +``` +Changing non-enumerable 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. + +**Bonus** + +**Object.defineProperty()** is also let you create read-only properties as we saw above, we are not able to modify phoneNo value of a person object. + +## Question 50 +##### What is Function binding ? + +> Function binding falls in advance JavaScript category and this is very popular technique to use in conjunction with event handler and callback function to preserve code execution context while passing function as a parameter. + +Let's consider the following example: + +```javascript +var clickHandler = { + message: 'click event handler', + handleClick: function(event) { + console.log(this.message); + } +}; + +var btn = document.getElementById('myBtn'); +// Add click event to btn +btn.addEventListener('click', clickHandler.handleClick); +``` + +Here in this example clickHandler object is created which contain message properties and handleClick method. + +We have assigned handleClick method to a DOM button, which will be executed in response of click. When the button is clicked, then handleClick method is being called and console message. Here console.log should log the `click event handler` message but it actually log `undefined`. + +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 clickHandler = { + message: 'click event handler', + handleClick: function(event) { + console.log(this.message); + } +}; + +var btn = document.getElementById('myBtn'); +// Add click event to btn and bind the clickHandler object +btn.addEventListener('click', clickHandler.handleClick.bind(clickHandler)); +``` + +`bind` method is available to all the function similar to call and apply method which take argument value of `this`. + + #Objective Question ## Hoisting @@ -1695,6 +2008,154 @@ var employeeId = '1234abe'; 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 + ## Object ###1. What would be the output of following code ? @@ -1704,7 +2165,7 @@ Answer: 2) undefined 'use strict'; var person = { - name: 'Nishant' + name: 'John' }; person.salary = '10000$'; person['country'] = 'USA'; @@ -1724,10 +2185,6 @@ Answer: 2) undefined Answer: 3) ["name", "salary", "country", "phoneNo"] -## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) - - ###2. What would be the output of following code ? ```javascript @@ -1735,7 +2192,7 @@ Answer: 3) ["name", "salary", "country", "phoneNo"] 'use strict'; var person = { - name: 'Nishant' + name: 'John' }; person.salary = '10000$'; person['country'] = 'USA'; @@ -1755,10 +2212,6 @@ Answer: 3) ["name", "salary", "country", "phoneNo"] Answer: 4) ["name", "salary", "country"] -## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) - - ###3. What would be the output of following code ? ```javascript @@ -1799,43 +2252,183 @@ Answer: 2) false false 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) - - -## Array - -###1. What would be the output of following code? +###5. What would be the output of following code ? ```javascript (function() { - var array = new Array('100'); - console.log(array); - console.log(array.length); + 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 -1. undefined undefined -2. [undefined × 100] 100 -3. ["100"] 1 -4. ReferenceError: array is not defined +###6. What would be the output of following code ? -Answer: 3) ["100"] 1 +```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 -###2. What would be the output of following code? +###7. 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); + 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 + +## Array + +###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] 5 3. [] [] ['1',2,'3',4,5.6] 5 @@ -1843,10 +2436,6 @@ Answer: 3) ["100"] 1 Answer: 1) [] [] [Array[5]] 1 -## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) - - ###3. What would be the output of following code? ```javascript @@ -1865,10 +2454,6 @@ Answer: 1) [] [] [Array[5]] 1 Answer: 1) 11 -## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) - - ###4. What would be the output of following code? ```javascript @@ -1887,6 +2472,200 @@ Answer: 1) 11 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 ] + ## Function: ###1. What would be the output of following code ? @@ -1974,6 +2753,117 @@ console.log(obj.innerMessage()); 4. ReferenceError: this.message is not defined Answer: 3) undefined + +###5. What would 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' +3. undefined +4. ReferenceError: self.message is not defined + +Answer: 2) 'Hello' + +###6. What would 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 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 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 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 + +Answer: a) 2 2 2 + +###10. What would 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: 2) 0 2 4 ## Object Oriented @@ -1993,17 +2883,457 @@ 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 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 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 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 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 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 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 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 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 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. What would 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 + +## Callback Function + +###1. What would 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 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 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 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 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 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 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 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 + + ## Have doubt in this question ?? [Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) From 707ab8790d301c7e8cdf40ef3bb143fcd1b84074 Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Tue, 30 May 2017 21:10:07 +0530 Subject: [PATCH 007/112] Update README.md --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index d2f3b18..8dd9a0e 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,14 @@ [![Join the chat at https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question](https://badges.gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question.svg)](https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +##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, 2017. + ## Have question for me ? [Ask me @nishant kumar](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) From 3f1cb5a25392993cfcc4b2698f284a1d8197701c Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Sat, 15 Jul 2017 15:38:25 +0530 Subject: [PATCH 008/112] Added BSD 3-Clause License --- LICENSE | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 LICENSE 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. From 3ab3160ac1128406942dbcc8a7c7d957d8ce8790 Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Mon, 31 Jul 2017 21:40:03 +0530 Subject: [PATCH 009/112] Added Codementor Link --- README.md | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 8dd9a0e..ac5ab66 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ What this means it that the project is free to read and use, but the license doe Copyright Nishant Kumar, 2017. ## Have question for me ? -[Ask me @nishant kumar](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) +[Ask me @nishant kumar](https://www.codementor.io/nihantanu/) # 123-JavaScript-Interview-Question ## 1. Difference between `undefined` and `not defined` in JavaScript @@ -47,7 +47,7 @@ console.log(y); // Output: ReferenceError: y is not defined [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) +[Schedule time to discuss with me @nishantk](https://www.codementor.io/nihantanu/) ## 2. What will be the output of the following code? @@ -82,7 +82,7 @@ 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) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ## 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. @@ -118,7 +118,7 @@ Here each instance variable `emp1`, `emp2`, `emp3` has own copy of increaseSalar So as recommendation don't go for a private method unless it's necessary. ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ## 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. @@ -164,7 +164,7 @@ 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) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ## 5. Write a mul function which will properly when invoked as below syntax. @@ -265,7 +265,7 @@ 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) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ### 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` @@ -329,7 +329,7 @@ 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) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) #### 8. What will be the output of the following code? @@ -345,7 +345,7 @@ console.log(output); > 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) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) #### 9. What will be the output of the following code? @@ -362,7 +362,7 @@ console.log(output); > 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`. ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) #### 10. What will be the output of the following code? @@ -379,7 +379,7 @@ console.log(output); > 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) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) #### 11. What will be the output of the following code? @@ -397,7 +397,7 @@ console.log(emp1.company); `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) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) #### 12. What is `undefined x 1` in JavaScript @@ -411,7 +411,7 @@ when you run above code and do `console.log(trees);` in chrome developer console **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) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) #### 13. What will be the output of the following code? @@ -426,7 +426,7 @@ console.log(trees.length); 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) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) #### 14. What will be the output of the following code? @@ -446,7 +446,7 @@ console.log(bar + false); - 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) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) #### 15. What will be the output of the following code? @@ -458,7 +458,7 @@ console.log(y); > 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`. ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) #### 16. What will be the output of the following code? @@ -499,7 +499,7 @@ var foo = function bar() { ``` ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) #### 17. What is the difference between declaring a function in below format? @@ -788,7 +788,7 @@ Unlike function calls and method calls, a constructor call `new Employee('John D 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) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ## Question 23 @@ -837,7 +837,7 @@ In Javascript function defined inside has access to outer function variable and - Function can be returned from function ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ## Question 25 @@ -892,7 +892,7 @@ methodObject.display(); Here methodObject is an object and display is a method which is associated with methodObject. ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ## Question 26 @@ -928,7 +928,7 @@ function testCallBack(callback) { 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) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ## Question 27 ### Describe Singleton Pattern In JavaScript? @@ -1033,7 +1033,7 @@ 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) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ## Question 28 @@ -3344,7 +3344,7 @@ Answer: 1) 720 ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ## This Book will be completed by Aug 1 2017 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). @@ -3355,7 +3355,7 @@ I'm always welcome to feedback on how the book can be improved, and more questio ####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 ##For any other query: -[Schedule 15 min discussion with me for free @nishantk](http://www.canumeet.com/nishantk/javascript-interview-query-discussion) +[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ##License From f1110f4579cd26435f9a12dfe67a22da6f8b10d4 Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Wed, 2 Aug 2017 09:25:30 +0530 Subject: [PATCH 010/112] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ac5ab66..d3f625b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ ![](coverPage.png) -## This Book will be completed by Aug 1 2017 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). +## This Book will be completed by Sept 1 2017 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). [![Join the chat at https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question](https://badges.gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question.svg)](https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) @@ -3346,7 +3346,7 @@ Answer: 1) 720 ## Have doubt in this question ?? [Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) -## This Book will be completed by Aug 1 2017 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). +## This Book will be completed by Sep 1 2017 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). ##Contributing From be66923551c7294c74031923856f7d31ccc6d51f Mon Sep 17 00:00:00 2001 From: ashishyadav311 Date: Sat, 28 Oct 2017 01:02:40 +0530 Subject: [PATCH 011/112] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d3f625b..25f1c98 100644 --- a/README.md +++ b/README.md @@ -1676,7 +1676,7 @@ There are some best way we can achieve this ```javascript function appLog() { - var args = Array.prototype.slice.call(argument); + var args = Array.prototype.slice.call(arguments); args.unshift('your app name'); console.log.apply(console, args); } From 0260e4fe292351dbb1a8d414f4bc6acd941958fa Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Mon, 30 Oct 2017 20:24:53 +0530 Subject: [PATCH 012/112] Update README.md --- README.md | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/README.md b/README.md index d3f625b..0226074 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,6 @@ What this means it that the project is free to read and use, but the license doe Copyright Nishant Kumar, 2017. ## Have question for me ? -[Ask me @nishant kumar](https://www.codementor.io/nihantanu/) # 123-JavaScript-Interview-Question ## 1. Difference between `undefined` and `not defined` in JavaScript @@ -47,7 +46,6 @@ console.log(y); // Output: ReferenceError: y is not defined [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](https://www.codementor.io/nihantanu/) ## 2. What will be the output of the following code? @@ -82,7 +80,6 @@ console.log(k); // output 1function ``` ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ## 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. @@ -118,7 +115,6 @@ Here each instance variable `emp1`, `emp2`, `emp3` has own copy of increaseSalar So as recommendation don't go for a private method unless it's necessary. ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ## 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. @@ -164,7 +160,6 @@ globalVar = abc ``` ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) ## 5. Write a mul function which will properly when invoked as below syntax. @@ -265,7 +260,6 @@ 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](https://www.codementor.io/nihantanu/) ### 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` @@ -329,7 +323,6 @@ 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](https://www.codementor.io/nihantanu/) #### 8. What will be the output of the following code? @@ -345,7 +338,6 @@ console.log(output); > 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](https://www.codementor.io/nihantanu/) #### 9. What will be the output of the following code? @@ -362,7 +354,6 @@ console.log(output); > 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`. ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) #### 10. What will be the output of the following code? @@ -379,7 +370,6 @@ console.log(output); > 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](https://www.codementor.io/nihantanu/) #### 11. What will be the output of the following code? @@ -397,7 +387,6 @@ console.log(emp1.company); `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](https://www.codementor.io/nihantanu/) #### 12. What is `undefined x 1` in JavaScript @@ -411,7 +400,6 @@ when you run above code and do `console.log(trees);` in chrome developer console **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](https://www.codementor.io/nihantanu/) #### 13. What will be the output of the following code? @@ -426,7 +414,6 @@ console.log(trees.length); 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](https://www.codementor.io/nihantanu/) #### 14. What will be the output of the following code? @@ -446,7 +433,6 @@ console.log(bar + false); - String + String -> Concatenation ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) #### 15. What will be the output of the following code? @@ -458,7 +444,6 @@ console.log(y); > 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`. ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) #### 16. What will be the output of the following code? From baa7f54cbadbb70dcddebbcdb46a1da3e3b2eefd Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Mon, 30 Oct 2017 20:26:02 +0530 Subject: [PATCH 013/112] Update README.md --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 0226074..4595f8a 100644 --- a/README.md +++ b/README.md @@ -484,7 +484,7 @@ var foo = function bar() { ``` ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) + #### 17. What is the difference between declaring a function in below format? @@ -773,7 +773,7 @@ Unlike function calls and method calls, a constructor call `new Employee('John D 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](https://www.codementor.io/nihantanu/) + ## Question 23 @@ -822,7 +822,7 @@ In Javascript function defined inside has access to outer function variable and - Function can be returned from function ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) + ## Question 25 @@ -877,7 +877,7 @@ methodObject.display(); Here methodObject is an object and display is a method which is associated with methodObject. ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) + ## Question 26 @@ -913,7 +913,7 @@ function testCallBack(callback) { testCallBack(display); // Here display function is being passed as callback ``` ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) + ## Question 27 ### Describe Singleton Pattern In JavaScript? @@ -1018,7 +1018,7 @@ 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](https://www.codementor.io/nihantanu/) + ## Question 28 @@ -3329,7 +3329,7 @@ Answer: 1) 720 ## Have doubt in this question ?? -[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) + ## This Book will be completed by Sep 1 2017 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). @@ -3340,7 +3340,7 @@ I'm always welcome to feedback on how the book can be improved, and more questio ####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 ##For any other query: -[Schedule 15 min discussion with me for free @nishantk](https://www.codementor.io/nihantanu/) + ##License From ace0c49fbc3f4a26070625d0f0257466741a4327 Mon Sep 17 00:00:00 2001 From: Omar El Gabry Date: Sun, 19 Nov 2017 16:44:06 +0530 Subject: [PATCH 014/112] Update Length of counterArray It outputs 3 since you added `counterArray["C"] = 1;` --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4595f8a..14e37c7 100644 --- a/README.md +++ b/README.md @@ -684,7 +684,7 @@ counterArray["C"] = 1; `Object` has `keys` method which can we 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. From c0d00b7e26efe8ae081b22a2371c6b988e0d7024 Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Mon, 4 Dec 2017 20:36:55 +0530 Subject: [PATCH 015/112] Deleted Nishant Resume --- Nishant_resume.js | 175 ---------------------------------------------- 1 file changed, 175 deletions(-) delete mode 100644 Nishant_resume.js diff --git a/Nishant_resume.js b/Nishant_resume.js deleted file mode 100644 index fdabaa4..0000000 --- a/Nishant_resume.js +++ /dev/null @@ -1,175 +0,0 @@ -/** - * The Curriculum vitae of Nishant Kumar - * - * Hi there, I am Nishant. I am Software Architect @GetMyParking, - * Mozila Tech Contributor, Teacher at CodeInstitute (Dublin), CodeMentor Front-end Expert, - * JavaScript Interview Question Author from India. - * - * I love to pair program and ship quality code that's solidly tested. - * Skills that I'm proficient in and continue to learn with: Object Oriented JavaScript, - * JavaScript Design Pattern, MVC, Client Side Performance Optimization, Node.js, Angular.js, - * Backbone.js, Vue.js, HTML5 and Tools: Git jasmine Test Framework, Grunt, webpack, bower, yoman. - * - * Domain: Cloud Computing, Distributed Systems, Big Data, SOA, Data mining, Hadoop, NoSQL and Graph Database. - * - */ - -(function() { - 'use strict'; - - /* - About Me - */ - const me = { - name: 'Nishant Kumar', - job: 'Software Architect', - organization: 'GetMyParking', - status: 'Not availble for hire', - location: 'Noida, India', - experience: '5+ years', - skills: { - 'scripting-language' :['JavaScript','ECMAScript 6'] - 'frameworks': ['angular.js','React','Vue','Vuex','backbone.js','IONIC','sails.js'], - 'library' : ['jQuery'] - 'tools': ['Webpack','Gulp', 'Grunt', 'bower','yoman','Git'], - 'testing': ['Jasmine', 'Protractor'], - 'backend': ['Node.js', 'Express.js','Python'], - 'dataBase': ['mongoDb', 'MYSQL'], - 'uncategorized' : ['C','C#','HTML','CSS', 'HTML5','JSON'] - }, - work_experience:[{ - 'company' : 'GetMyParking', - 'position': 'Software Architect', - 'duration': 'Jan 2017 - April 2017', - 'location': 'New Delhi', - 'job_type': 'Contract', - 'responsibility': { - "1": 'Responsible for designing and implementing development infrastructure', - "2": 'Manage risk identification and risk mitigation strategies associated with the architecture', - "3": 'Plan for new technology insertion', - "4": 'Make sure the right modeling is being done, to know that qualities like performance are going to be met', - "5": 'Commitment to following dev "best practices", with code-reviews, unit tests, etc.', - "6": 'Migrating monolithic base code to microservice based architecture to support million transaction per day', - "7": 'Creating and ensuring best practices properly followed for Node JS, and React JS based app.' - },{ - 'company' : 'Engineering Lead', - 'position' : 'BigParser.com', - 'duration' : 'Aug 2014 - Dec 2016', - 'location' : 'Pilani, New Delhi', - 'job_type': 'Contract, Hourly,Remotely', - 'responsibility': { - "1": 'Understanding Product Feature and Functionality Requirements of the Platform', - "2": 'Working with the Design and Architecture teams on design and framework issues.', - "3": 'Working interactions on all platforms including mobile devices', - "4": 'Developing client side MVC frameworks and Creating UI Libraries and using Angular/React JS', - "5": 'Optimize Performance through improved design', - "6": 'Working with the Back End teams on Server side integration of the Platform.', - "7": 'Providing Level 2 and Level 3, support of the UI and Partner Products in Testing, Stage and Client facing Production Environments.', - "8": 'Vertical Specific Customization of Cloud Platform including interfaces to Gmail, Dropbox, Box.Net' - },{ - 'company' : 'Sr. Software Engineering', - 'position' : 'Mindfire Solutions', - 'duration' : 'June 2011 - July 2014', - 'location' : 'Bhubaneswar, New Delhi', - 'job_type': 'Full Time', - 'responsibility': { - "1": 'Analyzed the business requirement with the project manager for different clients', - "2": 'Developed the Technical and functional specifications.', - "3": 'Developed the web based solutions and windows based solutions for various clients.', - "4": 'Perform monthly performance review of the application ', - "5": 'Developed a custom GUI for the ease of users', - "6": 'Developed discussion forum for internal use of knowledge flow within the organization.', - "7": 'Providing Level 2 and Level 3, support of the UI and Partner Products in Testing, Stage and Client facing Production Environments.', - "8": 'Trained the intern coming from various collages' - } - }], - 'notes': 'For project details & more work exp details please refer my linkedIn profile.' - }; - - /* - Contact Details - */ - const 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 - */ - const education = { - 'post-Graduate': { - 'college': 'Birla Institute of Technology and Science, Pilani', - 'Major' : 'Software System', - 'Year' :'2014-2016', - 'type': 'Regular, Pilani Campus' - }, - 'graduation' : { - 'college': 'ICFAI University, Dehradun', - 'Major' : 'Computer Science & Engineering', - 'Year' :'2007-2011', - 'type': 'Regular' - } - }, - - /** - * 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) - */ - -})(); From 5488c36db880fccb5243e2bd448ab512ff7707b2 Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Mon, 4 Dec 2017 20:38:44 +0530 Subject: [PATCH 016/112] Added Iurii in copyright info --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4595f8a..43c5cbb 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ This book is released under a Creative Commons Attribution-Noncommercial- No Der 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, 2017. +Copyright Iurii Katkov and Nishant Kumar, 2017. ## Have question for me ? @@ -3349,4 +3349,4 @@ This book is released under a Creative Commons Attribution-Noncommercial- No Der 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. From 411bfd1e86f1f57d08cd90d931a8c7721e2ce999 Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Mon, 4 Dec 2017 20:41:07 +0530 Subject: [PATCH 017/112] Removed Form --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 43c5cbb..520e425 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ ![](coverPage.png) -## This Book will be completed by Sept 1 2017 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). + [![Join the chat at https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question](https://badges.gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question.svg)](https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) @@ -3331,8 +3331,6 @@ Answer: 1) 720 ## Have doubt in this question ?? -## This Book will be completed by Sep 1 2017 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). - ##Contributing 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. From f62b6a2cf439af6b2754f656b0bec009ed5b4714 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Thu, 7 Dec 2017 10:04:39 +0100 Subject: [PATCH 018/112] Update README.md Message about the new contributor and flashcards.js --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 520e425..788c503 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ ![](coverPage.png) - +##Great news! +Even though the book is yet to be published, you can get something physical with carefully chosen interview questions. (https://flashcardsjs.com?utm_media=github)[Flashcards.js] is a deck of learning cards that will help you to ace you job interview. Yuri Katkov will work on enriching the book with the qustions from his flashcards collection and to create an unbeatable guide to pass any interview. [![Join the chat at https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question](https://badges.gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question.svg)](https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) From abcba65300d59902b2d1660ebfe4868fcdda7145 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Thu, 7 Dec 2017 10:08:19 +0100 Subject: [PATCH 019/112] Update README.md Typo in markup --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 788c503..979eda2 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ ![](coverPage.png) ##Great news! -Even though the book is yet to be published, you can get something physical with carefully chosen interview questions. (https://flashcardsjs.com?utm_media=github)[Flashcards.js] is a deck of learning cards that will help you to ace you job interview. Yuri Katkov will work on enriching the book with the qustions from his flashcards collection and to create an unbeatable guide to pass any interview. + +Even though the book is yet to be published, you can get something physical with carefully chosen interview questions. [Flashcards.js](https://flashcardsjs.com?utm_media=github) is a deck of learning cards that will help you to ace you job interview. Yuri Katkov will work on enriching the book with the qustions from his flashcards collection and to create an unbeatable guide to pass any interview. [![Join the chat at https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question](https://badges.gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question.svg)](https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) From d72f87c478f3cc88544d919dc448b1ebad7a11fb Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Thu, 7 Dec 2017 10:10:06 +0100 Subject: [PATCH 020/112] Update README.md Fixed link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 979eda2..86e2ea4 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ##Great news! -Even though the book is yet to be published, you can get something physical with carefully chosen interview questions. [Flashcards.js](https://flashcardsjs.com?utm_media=github) is a deck of learning cards that will help you to ace you job interview. Yuri Katkov will work on enriching the book with the qustions from his flashcards collection and to create an unbeatable guide to pass any interview. +Even though the book is yet to be published, you can get something physical with carefully chosen interview questions. [Flashcards.js](https://flashcardsjs.com) is a deck of learning cards that will help you to ace you job interview. Yuri Katkov will work on enriching the book with the qustions from his flashcards collection and to create an unbeatable guide to pass any interview. [![Join the chat at https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question](https://badges.gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question.svg)](https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) From 533e2f13f294deabb44469a1c55d4b81c5e22100 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Thu, 7 Dec 2017 10:11:37 +0100 Subject: [PATCH 021/112] Update README.md Http instead of https --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 86e2ea4..41b588c 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ##Great news! -Even though the book is yet to be published, you can get something physical with carefully chosen interview questions. [Flashcards.js](https://flashcardsjs.com) is a deck of learning cards that will help you to ace you job interview. Yuri Katkov will work on enriching the book with the qustions from his flashcards collection and to create an unbeatable guide to pass any interview. +Even though the book is yet to be published, you can get something physical with carefully chosen interview questions. [Flashcards.js](http://flashcardsjs.com) is a deck of learning cards that will help you to ace you job interview. Yuri Katkov will work on enriching the book with the qustions from his flashcards collection and to create an unbeatable guide to pass any interview. [![Join the chat at https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question](https://badges.gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question.svg)](https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) From 1363f0b2793a98ac48232d25eceb56c6c57227d8 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 10 Dec 2017 14:36:26 +0100 Subject: [PATCH 022/112] Update README.md trying to fix the markup --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 5f29fe0..53f476b 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,11 @@ ![](coverPage.png) -##Great news! +#Great news! Even though the book is yet to be published, you can get something physical with carefully chosen interview questions. [Flashcards.js](http://flashcardsjs.com) is a deck of learning cards that will help you to ace you job interview. Yuri Katkov will work on enriching the book with the qustions from his flashcards collection and to create an unbeatable guide to pass any interview. -[![Join the chat at https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question](https://badges.gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question.svg)](https://gitter.im/nishant8BITS/123-Essential-JavaScript-Interview-Question?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -##License +#License This book is released under a Creative Commons Attribution-Noncommercial- No Derivative Works 3.0 United States License. @@ -14,7 +13,6 @@ What this means it that the project is free to read and use, but the license doe Copyright Iurii Katkov and Nishant Kumar, 2017. -## Have question for me ? # 123-JavaScript-Interview-Question ## 1. Difference between `undefined` and `not defined` in JavaScript From 6fc553f069fe1a52719c5d3cc1cf7f2cd9378056 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 10 Dec 2017 15:06:44 +0100 Subject: [PATCH 023/112] Update README.md fixing markdown errors --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 53f476b..4437889 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,13 @@ ![](coverPage.png) -#Great news! +# 123-JavaScript-Interview-Question + +##Great news! Even though the book is yet to be published, you can get something physical with carefully chosen interview questions. [Flashcards.js](http://flashcardsjs.com) is a deck of learning cards that will help you to ace you job interview. Yuri Katkov will work on enriching the book with the qustions from his flashcards collection and to create an unbeatable guide to pass any interview. -#License +##License This book is released under a Creative Commons Attribution-Noncommercial- No Derivative Works 3.0 United States License. @@ -14,7 +16,6 @@ What this means it that the project is free to read and use, but the license doe Copyright Iurii Katkov and Nishant Kumar, 2017. -# 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`. From c2a7163d29722d3533fe89e856fc87977d181f9e Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 10 Dec 2017 15:07:27 +0100 Subject: [PATCH 024/112] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4437889..105d757 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,12 @@ # 123-JavaScript-Interview-Question -##Great news! +## Great news! Even though the book is yet to be published, you can get something physical with carefully chosen interview questions. [Flashcards.js](http://flashcardsjs.com) is a deck of learning cards that will help you to ace you job interview. Yuri Katkov will work on enriching the book with the qustions from his flashcards collection and to create an unbeatable guide to pass any interview. -##License +## License This book is released under a Creative Commons Attribution-Noncommercial- No Derivative Works 3.0 United States License. From dac0ffc97457d701774e27de6c04361de20701e5 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 10 Dec 2017 20:52:59 +0100 Subject: [PATCH 025/112] Update README.md --- README.md | 48 +++++++++++++----------------------------------- 1 file changed, 13 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 105d757..f986eac 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,10 @@ ![](coverPage.png) -# 123-JavaScript-Interview-Question +# 123-JavaScript-Interview-Questions ## Great news! -Even though the book is yet to be published, you can get something physical with carefully chosen interview questions. [Flashcards.js](http://flashcardsjs.com) is a deck of learning cards that will help you to ace you job interview. Yuri Katkov will work on enriching the book with the qustions from his flashcards collection and to create an unbeatable guide to pass any interview. - - -## 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 Iurii Katkov and Nishant Kumar, 2017. - +Yuri Katkov from [Flashcards.js](http://flashcardsjs.com) became a co-author and the rights holder of the book. He will improve the questions and add some more from his collections of flashcards and will make sure to produce an unbeatable guide for frontend inteviews. ## 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`. @@ -46,7 +36,6 @@ 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 ?? ## 2. What will be the output of the following code? @@ -80,7 +69,6 @@ if (1) { console.log(k); // output 1function ``` -## Have doubt in this question ?? ## 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. @@ -115,8 +103,6 @@ Here each instance variable `emp1`, `emp2`, `emp3` has own copy of increaseSalar So as recommendation don't go for a private method unless it's necessary. -## Have doubt in this question ?? - ## 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. @@ -160,8 +146,6 @@ innerFuncVar = y globalVar = abc ``` -## Have doubt in this question ?? - ## 5. Write a mul function which will properly when invoked as below syntax. ```javascript @@ -260,7 +244,6 @@ while(arrayList.length) { Above implementation can also empty the array. But not recommended to use often. -## Have doubt in this question ?? ### 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` @@ -323,7 +306,6 @@ 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 ?? #### 8. What will be the output of the following code? @@ -338,7 +320,6 @@ console.log(output); > 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 ?? #### 9. What will be the output of the following code? @@ -354,7 +335,6 @@ console.log(output); > 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`. -## Have doubt in this question ?? #### 10. What will be the output of the following code? @@ -370,7 +350,6 @@ console.log(output); > 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 ?? #### 11. What will be the output of the following code? @@ -387,7 +366,6 @@ console.log(emp1.company); `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 ?? #### 12. What is `undefined x 1` in JavaScript @@ -400,7 +378,7 @@ when you run above code and do `console.log(trees);` in chrome developer console **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 ?? + #### 13. What will be the output of the following code? @@ -414,7 +392,7 @@ console.log(trees.length); 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 ?? + #### 14. What will be the output of the following code? @@ -433,7 +411,7 @@ console.log(bar + false); - String + Boolean -> Concatenation - String + String -> Concatenation -## Have doubt in this question ?? + #### 15. What will be the output of the following code? @@ -444,7 +422,7 @@ console.log(y); > 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`. -## Have doubt in this question ?? + #### 16. What will be the output of the following code? @@ -484,7 +462,7 @@ var foo = function bar() { // bar is undefined here ``` -## Have doubt in this question ?? + @@ -773,7 +751,7 @@ Unlike function calls and method calls, a constructor call `new Employee('John D The primary role of the constructor function is to initialize the object. -## Have doubt in this question ?? + @@ -822,7 +800,7 @@ In Javascript function defined inside has access to outer function variable and - Function can be pass as a parameter to another function - Function can be returned from function -## Have doubt in this question ?? + @@ -877,7 +855,7 @@ methodObject.display(); Here methodObject is an object and display is a method which is associated with methodObject. -## Have doubt in this question ?? + @@ -913,7 +891,7 @@ function testCallBack(callback) { } testCallBack(display); // Here display function is being passed as callback ``` -## Have doubt in this question ?? + ## Question 27 @@ -1018,7 +996,7 @@ 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 ?? + @@ -3329,7 +3307,7 @@ Answer: 1) 720 -## Have doubt in this question ?? + ##Contributing From 1ab8a654f5233f7ad7c192564fa72de0b657525c Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 10 Dec 2017 21:13:33 +0100 Subject: [PATCH 026/112] Update README.md formatting --- README.md | 261 +++++++++++++++++++++++------------------------------- 1 file changed, 113 insertions(+), 148 deletions(-) diff --git a/README.md b/README.md index f986eac..6f279f0 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Yuri Katkov from [Flashcards.js](http://flashcardsjs.com) became a co-author and the rights holder of the book. He will improve the questions and add some more from his collections of flashcards and will make sure to produce an unbeatable guide for frontend inteviews. -## 1. Difference between `undefined` and `not defined` in JavaScript +## 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`. Before starting further discussion let's understand the difference between declaration and definition. @@ -37,7 +37,7 @@ console.log(y); // Output: ReferenceError: y is not defined [http://stackoverflow.com/questions/20822022/javascript-variable-definition-declaration](http://stackoverflow.com/questions/20822022/javascript-variable-definition-declaration) -## 2. What will be the output of the following code? +## Question 2. What will be the output of the following code? ```javascript var y = 1; @@ -70,7 +70,7 @@ console.log(k); // output 1function ``` -## 3. What is the drawback of creating true private in JavaScript? +## Question 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. ```javascript @@ -103,7 +103,7 @@ Here each instance variable `emp1`, `emp2`, `emp3` has own copy of increaseSalar So as recommendation don't go for a private method unless it's necessary. -## 4.What is “closure” in javascript? Provide an example? +## Question 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. The closure has access to variable in three scopes: @@ -146,7 +146,7 @@ innerFuncVar = y globalVar = abc ``` -## 5. Write a mul function which will properly when invoked as below syntax. +## Question 5. Write a mul function which will properly when invoked as below syntax. ```javascript console.log(mul(2)(3)(4)); // output : 24 @@ -174,7 +174,7 @@ In Javascript function defined inside has access to outer function variable and - Function can be pass as a parameter to another function - Function can be returned from function -### 6. How to empty an array in JavaScript? +## Question 6. How to empty an array in JavaScript? For instance: ```javascript @@ -245,7 +245,7 @@ while(arrayList.length) { Above implementation can also empty the array. But not recommended to use often. -### 7. How to check if an object is an array or not? +## Question 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` ```javascript @@ -307,7 +307,7 @@ Array.isArray(arrayList); `Array.isArray` is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5 -#### 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) { @@ -321,7 +321,7 @@ console.log(output); > 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. -#### 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; @@ -336,7 +336,7 @@ console.log(output); > 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`. -#### 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}; @@ -351,7 +351,7 @@ console.log(output); > 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`. -#### 11. What will be the output of the following code? +## Question 11. What will be the output of the following code? ```javascript var Employee = { @@ -367,7 +367,7 @@ console.log(emp1.company); `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`. -#### 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"]; @@ -380,7 +380,7 @@ when you run above code and do `console.log(trees);` in chrome developer console -#### 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"]; @@ -394,7 +394,7 @@ So when delete operator removes an array element that deleted element is not lon -#### 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; @@ -412,8 +412,7 @@ console.log(bar + false); - String + String -> Concatenation - -#### 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; @@ -424,7 +423,7 @@ console.log(y); -#### 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 @@ -466,7 +465,7 @@ var foo = function bar() { -#### 17. What is the difference between declaring a function in below format? +## Question 17. What is the difference between declaring a function in below format? ```javascript var foo = function() { @@ -534,7 +533,7 @@ if(testCondition) {// If testCondition is true then ``` -#### 18. what is function hoisting in JavaScript? +## Question 18. what is function hoisting in JavaScript? **Function Expression** ```javascript @@ -570,7 +569,7 @@ 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$"; @@ -599,7 +598,7 @@ var salary = "1000$"; })(); ``` -#### 20. What is the `instanceof` operator in JavaScript? what would be the output of the following code? +## Question 20. What is the `instanceof` operator in JavaScript? what would be the output of the following code? ```javascript function foo() { @@ -647,7 +646,7 @@ 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. If we have JavaScript associative array as below code: ```javascript var counterArray = { @@ -696,8 +695,7 @@ console.log(Object.length(counterArray)); **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. +## 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: @@ -752,11 +750,7 @@ Unlike function calls and method calls, a constructor call `new Employee('John D The primary role of the constructor function is to initialize the object. - - - -## 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) { @@ -771,8 +765,7 @@ The output of above code would be `USA`. Here `new User("xyz")` creates a brand 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"]`. -## Question 24 -### Write a mul function which will output when invoked as below syntax. +## Question 24. Write a mul function which will output when invoked as below syntax. ```javascript console.log(mul(2)(3)(4)); // output : 24 @@ -804,8 +797,7 @@ In Javascript function defined inside has access to outer function variable and -## 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). ```javascript @@ -859,8 +851,7 @@ Here methodObject is an object and display is a method which is associated with -## Question 26 -### What is JavaScript Self-Invoking anonymous function or Self-Executing anonymous function. +## 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: ```javascript @@ -894,8 +885,7 @@ testCallBack(display); // Here display function is being passed as callback -## Question 27 -### Describe Singleton Pattern In JavaScript? +## 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: @@ -1000,8 +990,7 @@ The singleton implemented above is easy to understand. The singleton class maint -## Question 28 -##### What are the way by which we can create object in JavaScript ? +## Question 28. What are the way by which we can create object in JavaScript ? **Method 1:** `Function Based` @@ -1064,8 +1053,7 @@ employee.getName = function(){ ``` **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. +## Question 29. Write a function called deepClone which takes an object and creates a object copy of it. ``` javascript var newObject = deepClone(obj); @@ -1103,8 +1091,7 @@ 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. > Suppose we have given an object `person` @@ -1132,8 +1119,7 @@ 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'}; @@ -1153,8 +1139,7 @@ function Clone(object){ } ``` -## Question 32 -##### Best way to detect `undefined` object property in JavaScript. +## Question 32. Best way to detect `undefined` object property in JavaScript. > Suppose we have given an object `person` @@ -1182,8 +1167,7 @@ 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. +## Question 33. How to check whether a key exist in a JavaScript object or not. >Let say we have `person` object with property **name** and **age** @@ -1220,8 +1204,7 @@ 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. +## Question 34. Best way to detect `undefined` object property in JavaScript. > Suppose we have given an object `person` @@ -1249,8 +1232,7 @@ if(typeof person.salary === 'undefined'){ console.log("salary is undefined here because we haven't declared"); } ``` -## Question 35 -##### How to check whether a key exist in a JavaScript object or not. +## 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** @@ -1287,8 +1269,7 @@ console.log(person.hasOwnProperty('name')); // print true console.log(person.hasOwnProperty('salary')); // print false ``` -## Question 36 -##### What is best way to detect an arrays object on JavaScript ? +## Question 36. What is best way to detect an arrays object on JavaScript ? >We always encounter in such situation where we need to know whether value is type of array or not. @@ -1355,8 +1336,7 @@ function(value){ } ``` -## Question 37 -##### Best way to detect reference values of any type in JavaScript ? +## Question 37. Best way to detect reference values of any type in JavaScript ? > 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**. @@ -1398,8 +1378,7 @@ console.log(emp1 instanceof Employee); // true console.log(emp1 instanceof Object); // true ``` -## Question 38 -##### Describe Object-Based inheritance in JavaScript. +## Question 38. Describe Object-Based inheritance in JavaScript. > Object-based inheritance also called prototypal inheritance in which we one object inherit from another object without invoking a constructor function. @@ -1450,8 +1429,7 @@ In above example, emp1 is created with it's own value for name, so calling **dis >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. +## 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. @@ -1512,8 +1490,7 @@ 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. @@ -1623,8 +1600,7 @@ delete employee.name; // fails silently unless it's in strict mode ``` -## Question 44 -##### Write a log function which will add prefix `(your message)` to every message you log using console.log ? +## Question 44. 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** 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. @@ -1649,8 +1625,7 @@ console.log(appLog("Some error message")); //output of above console: 'your app name Some error message' ``` -## Question 45 -##### Write a function which will test string as a literal and as an object ? +## Question 45 . Write a function which will test string as a literal and as an object ? For example: We can create string using string literal and using String constructor function. @@ -1672,8 +1647,7 @@ For example: We can create string using string literal and using String construc console.log(isString(ltrlStr)); // true console.log(isString(objStr)); // true ``` -## Question 46 -##### What is typical use case for anonymous function in JavaScript ? +## Question 46 . What is typical use case for anonymous function in JavaScript ? > Anonymous functions basically used in following scenario. @@ -1736,8 +1710,7 @@ If your answer is yes then go and create named function rather anonymous functio 1. It can reduce a bit of code, particularly in recursive function and in callback function. 2. Avoid needless global namespace pollutions. -## Question 47 -##### How to set a default parameter value ? +## Question 47 . How to set a default parameter value ? > 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 : @@ -1796,8 +1769,7 @@ sentEmail({ }, 'Yahoo Mail'); ``` -## Question 48 -##### Write code for merge two JavaScript Object dynamically. +## Question 48. Write code for merge two JavaScript Object dynamically. > Let say you have two object ```javascript @@ -1846,8 +1818,7 @@ function merge(toObj, fromObj) { } } ``` -## Question 49 -##### What is non-enumerable property in JavaScript and how can create ? +## Question 49. What is non-enumerable property in JavaScript and how can create ? >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. @@ -1894,8 +1865,7 @@ Changing non-enumerable property value will return error in `strict mode`. In no **Object.defineProperty()** is also let you create read-only properties as we saw above, we are not able to modify phoneNo value of a person object. -## Question 50 -##### What is Function binding ? +## Question 50. What is Function binding ? > 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. @@ -1936,11 +1906,11 @@ btn.addEventListener('click', clickHandler.handleClick.bind(clickHandler)); `bind` method is available to all the function similar to call and apply method which take argument value of `this`. -#Objective Question +# Coding Questions ## Hoisting -###1. console.log(employeeId); +### 1. console.log(employeeId); 1. Some Value 2. Undefined @@ -1949,7 +1919,7 @@ btn.addEventListener('click', clickHandler.handleClick.bind(clickHandler)); Answer: 4) ReferenceError: employeeId is not defined -###2. What would be the output of following code? +### 2. What would be the output of following code? ```javascript console.log(employeeId); @@ -1963,7 +1933,7 @@ var employeeId = '19000'; Answer: 2) undefined -###3. What would be the output of following code? +### 3. What would be the output of following code? ```javascript var employeeId = '1234abe'; @@ -1980,7 +1950,7 @@ var employeeId = '1234abe'; Answer: 2) undefined -###4. What would be the output of following code? +### 4. What would be the output of following code? ```javascript var employeeId = '1234abe'; @@ -2000,7 +1970,7 @@ var employeeId = '1234abe'; Answer: 2) undefined -###5. What would be the output of following code? +### 5. What would be the output of following code? ```javascript (function() { @@ -2018,7 +1988,7 @@ Answer: 2) undefined Answer: 1) undefined -###6. What would be the output of following code? +### 6. What would be the output of following code? ```javascript var employeeId = 'abc123'; @@ -2037,7 +2007,7 @@ console.log(employeeId); Answer: 2) '123bcd' -###7. What would be the output of following code? +### 7. What would be the output of following code? ```javascript var employeeId = 'abc123'; @@ -2059,7 +2029,7 @@ console.log(employeeId); Answer: 3) 'abc123' -###8. What would be the output of following code? +### 8. What would be the output of following code? ```javascript var employeeId = 'abc123'; @@ -2082,7 +2052,7 @@ foo(); Answer: 2) 'function' -###9. What would be the output of following code? +### 9. What would be the output of following code? ```javascript function foo() { @@ -2104,7 +2074,7 @@ foo(); Answer: 1) undefined -###10. What would be the output of following code? +### 10. What would be the output of following code? ```javascript (function foo() { @@ -2130,7 +2100,7 @@ Answer: 3) function function ## Object -###1. What would be the output of following code ? +### 1. What would be the output of following code ? ```javascript (function() { @@ -2157,7 +2127,7 @@ Answer: 3) function function Answer: 3) ["name", "salary", "country", "phoneNo"] -###2. What would be the output of following code ? +### 2. What would be the output of following code ? ```javascript (function() { @@ -2184,7 +2154,7 @@ Answer: 3) ["name", "salary", "country", "phoneNo"] Answer: 4) ["name", "salary", "country"] -###3. What would be the output of following code ? +### 3. What would be the output of following code ? ```javascript (function() { @@ -2207,7 +2177,7 @@ Answer: 4) ["name", "salary", "country"] Answer: 2) false false -###4. What would be the output of following code ? +### 4. What would be the output of following code ? ```javascript (function() { @@ -2224,7 +2194,7 @@ Answer: 2) false false Answer: 2) false false -###5. What would be the output of following code ? +### 5. What would be the output of following code ? ```javascript (function() { @@ -2245,7 +2215,7 @@ Answer: 2) false false Answer: 2) false false -###6. What would be the output of following code ? +### 6. What would be the output of following code ? ```javascript (function() { @@ -2264,7 +2234,7 @@ Answer: 2) false false Answer: 2) false false -###7. What would be the output of following code ? +### 7. What would be the output of following code ? ```javascript (function() { @@ -2283,7 +2253,7 @@ Answer: 2) false false Answer: 4) true true -###8. What would be the output of following code ? +### 8. What would be the output of following code ? ```javascript (function() { @@ -2304,7 +2274,7 @@ Answer: 4) true true Answer: 3) true true true true -###9. What would be the output of following code ? +### 9. What would be the output of following code ? ```javascript (function() { @@ -2324,7 +2294,7 @@ Answer: 3) true true true true Answer: 2) bar bar -###10. What would be the output of following code ? +### 10. What would be the output of following code ? ```javascript (function() { @@ -2346,7 +2316,7 @@ Answer: 2) bar bar Answer: 3) foo foo -###11. What would be the output of following code ? +### 11. What would be the output of following code ? ```javascript (function() { @@ -2370,7 +2340,7 @@ Answer: 2) undefined undefined ## Array -###1. What would be the output of following code? +### 1. What would be the output of following code? ```javascript (function() { @@ -2387,7 +2357,7 @@ Answer: 2) undefined undefined Answer: 3) ["100"] 1 -###2. What would be the output of following code? +### 2. What would be the output of following code? ```javascript (function() { @@ -2408,7 +2378,7 @@ Answer: 3) ["100"] 1 Answer: 1) [] [] [Array[5]] 1 -###3. What would be the output of following code? +### 3. What would be the output of following code? ```javascript (function () { @@ -2426,7 +2396,7 @@ Answer: 1) [] [] [Array[5]] 1 Answer: 1) 11 -###4. What would be the output of following code? +### 4. What would be the output of following code? ```javascript (function(){ @@ -2444,7 +2414,7 @@ Answer: 1) 11 Answer: 3) 6 -###5. What would be the output of following code? +### 5. What would be the output of following code? ```javascript (function(){ @@ -2462,7 +2432,7 @@ Answer: 3) 6 Answer: 1) [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ] -###6. What would be the output of following code? +### 6. What would be the output of following code? ```javascript (function(){ @@ -2481,7 +2451,7 @@ Answer: 1) [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ] Answer: 1) 1 -1 -1 4 -###7. What would be the output of following code? +### 7. What would be the output of following code? ```javascript (function(){ @@ -2499,7 +2469,7 @@ Answer: 1) 1 -1 -1 4 Answer: 2) 1 6 -1 -###8. What would be the output of following code? +### 8. What would be the output of following code? ```javascript (function(){ @@ -2524,7 +2494,7 @@ Answer: 2) 1 6 -1 Answer: 3) [ 2, 4, 8, 12, 16 ] true -###9. What would be the output of following code? +### 9. What would be the output of following code? ```javascript (function(){ @@ -2563,7 +2533,7 @@ Answer: 1) [ 2, '12', true ] [ 2, '12', true ] [ 2, '12', true ] -###10. What would be the output of following code? +### 10. What would be the output of following code? ```javascript (function(){ @@ -2603,7 +2573,7 @@ Answer: 1) [ 'bar', 'john', 'ritz' ] [] [ 'foo', 'bar', 'john', 'ritz' ] -###11. What would be the output of following code? +### 11. What would be the output of following code? ```javascript (function(){ @@ -2621,7 +2591,7 @@ Answer: 1) [ 'bar', 'john', 'ritz' ] Answer: 1. [ 'bar', 'john' ] [] [ 'foo' ] -###12. What would be the output of following code? +### 12. What would be the output of following code? ```javascript (function(){ @@ -2640,7 +2610,7 @@ Answer: 3. [ 15, 16, 2, 23, 42, 8 ] ## Function: -###1. What would be the output of following code ? +### 1. What would be the output of following code ? ```javascript function funcA(){ @@ -2665,7 +2635,7 @@ console.log(funcA()); Answer: 1) -###2. What would be the output of following code ? +### 2. What would be the output of following code ? ```javascript var obj = { @@ -2685,7 +2655,7 @@ console.log(obj.innerMessage); Answer: 4) undefined true -###3. What would the output of following code ? +### 3. What would the output of following code ? ```javascript var obj = { @@ -2705,7 +2675,7 @@ console.log(obj.innerMessage()); Answer: 1) Hello -###4. What would the output of following code ? +### 4. What would the output of following code ? ```javascript var obj = { @@ -2726,7 +2696,7 @@ console.log(obj.innerMessage()); Answer: 3) undefined -###5. What would the output of following code ? +### 5. What would the output of following code ? ```javascript var obj = { @@ -2748,7 +2718,7 @@ console.log(obj.innerMessage()); Answer: 2) 'Hello' -###6. What would the output of following code ? +### 6. What would the output of following code ? ```javascript function myFunc(){ @@ -2766,7 +2736,7 @@ console.log(myFunc()); Answer: 3) undefined -###7. What would the output of following code ? +### 7. What would the output of following code ? ```javascript function myFunc(){ @@ -2784,7 +2754,7 @@ console.log(myFunc()); Answer: 2) 'Hi John' -###8. What would the output of following code ? +### 8. What would the output of following code ? ```javascript function myFunc() { @@ -2801,7 +2771,7 @@ console.log(myFunc()); Answer: 2) 'Hi John' -###9. What would the output of following code ? +### 9. What would the output of following code ? ```javascript function myFunc(param1,param2) { @@ -2819,7 +2789,7 @@ console.log(myFunc("a","b","c","d")); Answer: a) 2 2 2 -###10. What would the output of following code ? +### 10. What would the output of following code ? ```javascript function myFunc() { @@ -2839,7 +2809,7 @@ Answer: 2) 0 2 4 ## Object Oriented -###1. What would the output of following code ? +### 1. What would the output of following code ? ```javascript function Person(name, age){ @@ -2869,7 +2839,7 @@ Answer: 1) John Person ## Scopes -###1. What would the output of following code ? +### 1. What would the output of following code ? ```javascript function passWordMngr() { @@ -2892,7 +2862,7 @@ console.log(userInfo.userName); Answer: 3) 12345678 undefined -###2. What would the output of following code ? +### 2. What would the output of following code ? ```javascript var employeeId = 'aq123'; @@ -2909,7 +2879,7 @@ console.log(Employee.employeeId); Answer: 4) undefined -###3. What would the output of following code ? +### 3. What would the output of following code ? ```javascript var employeeId = 'aq123'; @@ -2931,7 +2901,7 @@ console.log(new Employee().employeeId); Answer: 2) bq1uy 1BJKSJ bq1uy -###4. What would the output of following code ? +### 4. What would the output of following code ? ```javascript var employeeId = 'aq123'; @@ -2954,7 +2924,7 @@ Answer: 1) foo123 aq123 ## Call, Apply, Bind -###1. What would the output of following code ? +### 1. What would the output of following code ? ```javascript (function() { @@ -2973,7 +2943,7 @@ Answer: 1) foo123 aq123 Answer: 4) [ 'W', 'o', 'r', 'l', 'd' ] -###2. What would the output of following code ? +### 2. What would the output of following code ? ```javascript (function() { @@ -3004,7 +2974,7 @@ Answer: 4) [ 'W', 'o', 'r', 'l', 'd' ] Answer: 1) Total amount left in account: 5600 Total amount left in account: 5300 -###3. What would the output of following code ? +### 3. What would the output of following code ? ```javascript (function() { @@ -3036,7 +3006,7 @@ Answer: 1) Total amount left in account: 5600 Total amount left in account: 5300 Answer: 1) 5600 5300 5100 -###4. What would the output of following code ? +### 4. What would the output of following code ? ```javascript (function() { @@ -3068,7 +3038,7 @@ Answer: 1) 5600 5300 5100 Answer: 2) 3600 3300 3100 -###5. What would the output of following code ? +### 5. What would the output of following code ? ```javascript (function greetNewCustomer() { @@ -3085,7 +3055,7 @@ Answer: 2) 3600 3300 3100 Answer: 1) Hello John -###6. What would the output of following code ? +### 6. What would the output of following code ? ```javascript (function greetNewCustomer() { @@ -3104,7 +3074,7 @@ Answer: 1) Hello John ## Callback Function -###1. What would the output of following code ? +### 1. What would the output of following code ? ```javascript function getDataFromServer(apiUrl){ @@ -3129,7 +3099,7 @@ getDataFromServer('www.google.com').then(function(name){ Answer: 1) John -###2. What would the output of following code ? +### 2. What would the output of following code ? ```javascript (function(){ @@ -3177,7 +3147,7 @@ Answer: 1) [ 2, 8, 15, 16, 23, 42 ] ## Return Statement -###1. What would the output of following code ? +### 1. What would the output of following code ? ```javascript (function(){ @@ -3199,7 +3169,7 @@ Answer: 1) [ 2, 8, 15, 16, 23, 42 ] Answer: 4) Uncaught TypeError: Cannot read property 'fullName' of undefined -###2. What would the output of following code ? +### 2. What would the output of following code ? ```javascript function getNumber(){ @@ -3217,7 +3187,7 @@ console.log(numb); Answer: 1) 5 -###3. What would the output of following code ? +### 3. What would the output of following code ? ```javascript function getNumber(){ @@ -3235,7 +3205,7 @@ console.log(numb); Answer: 2) undefined -###4**. What would the output of following code ? +### 4**. What would the output of following code ? ```javascript function mul(x){ @@ -3257,7 +3227,7 @@ console.log(mul(2)(3)[1](4)); Answer: 1) 6, 10 -###5**. What would the output of following code ? +### 5**. What would the output of following code ? ```javascript function mul(x) { @@ -3281,7 +3251,7 @@ console.log(mul(2)(3).sum(4)); Answer: 1) 6, 10 -###6. What would the output of following code ? +### 6. What would the output of following code ? ```javascript function mul(x) { @@ -3310,17 +3280,12 @@ Answer: 1) 720 -##Contributing - -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. - -####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 - -##For any other query: +## Contributing +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. From 9942571a35797e7c975cabae5f70e320ea3c548e Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Thu, 28 Dec 2017 01:15:06 +0100 Subject: [PATCH 027/112] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 6f279f0..6e80e5f 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,9 @@ # 123-JavaScript-Interview-Questions +This Book will be completed by June 2018 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](https://goo.gl/forms/c8ubV1tWBBdz6fJP2). + + ## Great news! Yuri Katkov from [Flashcards.js](http://flashcardsjs.com) became a co-author and the rights holder of the book. He will improve the questions and add some more from his collections of flashcards and will make sure to produce an unbeatable guide for frontend inteviews. From 9ea8fbe5c7293fefca33e38d0f25db800c9ebe1c Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 30 Dec 2017 15:33:26 +0100 Subject: [PATCH 028/112] Update README.md replaced duplicated questions with a stub --- README.md | 96 ++----------------------------------------------------- 1 file changed, 3 insertions(+), 93 deletions(-) diff --git a/README.md b/README.md index 6e80e5f..034efdf 100644 --- a/README.md +++ b/README.md @@ -768,35 +768,7 @@ The output of above code would be `USA`. Here `new User("xyz")` creates a brand 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"]`. -## Question 24. Write a mul function which will output when invoked as below 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: - -```javascript -function mul (x) { - return function (y) { // anonymous function - return function (z) { // anonymous function - return x * y * z; - }; - }; -} -``` - -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. - -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 - - +## Question 24. Suggest your question! @@ -1207,70 +1179,8 @@ 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. - -**Explanation:** - -We can use `typeof` operator to check undefined - -```javascript -if(typeof someProperty === 'undefined'){ - console.log('something is undefined here'); -} -``` -Now we are trying to access salary property of person object. - -```javascript -if(typeof person.salary === 'undefined'){ - console.log("salary is undefined here because we haven't declared"); -} -``` -## 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** - -```javascript -var person = { - name: 'Nishant', - age: 24 -} -``` -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. - -So how we will check whether property is own property or inherited property. - -Method 1: We can use `in` operator on objet to check own property or inherited property. - -```javascript -console.log('name' in person); // checking own property print true -console.log('salary' in person); // checking undefined property print false -``` -`in` operator also look into inherited property if it doesn't find property defined as own property. For instance If I check existence of toString property as we know that we haven't declared this property on person object so `in` operator look into there base property. - -Here - -```javascript -console.log('toString' in person); // Will print true -``` -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 34. Suggest your question! +## Question 35. Suggest your question! ## Question 36. What is best way to detect an arrays object on JavaScript ? From 95ec9847b3840a54a8dcb7e1dba1a991123473e5 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 30 Dec 2017 15:36:30 +0100 Subject: [PATCH 029/112] Update README.md #13 fixed typo --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 034efdf..238004a 100644 --- a/README.md +++ b/README.md @@ -1320,8 +1320,8 @@ 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. From 721e62d7739cf05c04699c53275690bb8db70f32 Mon Sep 17 00:00:00 2001 From: Volodymyr Date: Sun, 22 Apr 2018 18:59:04 +0300 Subject: [PATCH 030/112] Fixed 15 question Based on the associativity property of operator `,`, the code going to be executed from left to right. `z` will equal to `undefined` after code execution. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fa9f5ad..e24c939 100644 --- a/README.md +++ b/README.md @@ -422,7 +422,7 @@ var z = 1, y = z = typeof y; console.log(y); ``` -> 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`. +> 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. From a9ce6744634a981bd2e157660320725050374673 Mon Sep 17 00:00:00 2001 From: Mark Kuba Date: Wed, 16 May 2018 09:58:48 -0700 Subject: [PATCH 031/112] Remove Question #32 (duplicate of #30) --- README.md | 27 +-------------------------- 1 file changed, 1 insertion(+), 26 deletions(-) diff --git a/README.md b/README.md index fa9f5ad..335edca 100644 --- a/README.md +++ b/README.md @@ -1114,34 +1114,9 @@ function Clone(object){ } ``` -## Question 32. Best way to detect `undefined` object property in JavaScript. +## Question 32. Suggest your question! -> 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. - -**Explanation:** - -We can use `typeof` operator to check undefined -```javascript -if(typeof someProperty === 'undefined'){ - console.log('something is undefined here'); -} -``` -Now we are trying to access salary property of person object. - -```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. >Let say we have `person` object with property **name** and **age** From 56edd8e7d0991302eb3225851f719015b67a5eed Mon Sep 17 00:00:00 2001 From: Mark Kuba Date: Wed, 30 May 2018 10:01:05 -0700 Subject: [PATCH 032/112] FIX: removed duplicate question Call, Apply, Bind question #6 identical to question #5 --- README.md | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) diff --git a/README.md b/README.md index bf7d9c5..af8eb31 100644 --- a/README.md +++ b/README.md @@ -2943,22 +2943,7 @@ Answer: 2) 3600 3300 3100 Answer: 1) Hello John -### 6. What would 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 Function From d3fee43fa6b3c9c28e0a18ff5bb91ae85f420810 Mon Sep 17 00:00:00 2001 From: mdsaleemj Date: Wed, 6 Jun 2018 15:21:27 +0530 Subject: [PATCH 033/112] changing the logic of Object.length method allowing to take parameter which the input object whose size/length to be found --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index af8eb31..d8d6577 100644 --- a/README.md +++ b/README.md @@ -684,11 +684,11 @@ function getSize(object) { > We can also add `length` method directly on `Object` see below code. ```javascript -Object.length = function() { +Object.size = function(obj) { var count = 0; - for(key in object) { + for(key in obj) { // hasOwnProperty method check own property of object - if(object.hasOwnProperty(key)) count++; + if(obj.hasOwnProperty(key)) count++; } return count; } From ebb1197c1c03852c8a3a576f7352f32a142510f4 Mon Sep 17 00:00:00 2001 From: Artem Date: Wed, 13 Jun 2018 00:51:46 +0300 Subject: [PATCH 034/112] Question 15 fix Since typeof operator returns string representation of its operand, its worth noticing, that eventual value would be "undefined", not undefiend --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index af8eb31..11e50ec 100644 --- a/README.md +++ b/README.md @@ -422,7 +422,7 @@ var z = 1, y = z = typeof y; console.log(y); ``` -> 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. +> Above code will output 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. From bcefd0d97c953c11ea18d7f828bb092bbec5de83 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Wed, 13 Jun 2018 10:03:05 +0200 Subject: [PATCH 035/112] Update README.md fix from @melvinwallerjr --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 11e50ec..5ea4018 100644 --- a/README.md +++ b/README.md @@ -1683,9 +1683,7 @@ name , age , addressLine1 , addressLine2 , city */ **Method 1: Using ES6, Object assign method** ```javascript -function merge(toObj,fromObj){ - return Object.assign(person,location); -} +const merge = (toObj, fromObj) => Object.assign(toObj, fromObj); ``` **Method 2: Without using in-built function** From a9bbe8035c188132b9f10cb49d0622c8015b25fe Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Thu, 14 Jun 2018 19:02:23 +0200 Subject: [PATCH 036/112] Update README.md typo fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5ea4018..10f6a8f 100644 --- a/README.md +++ b/README.md @@ -861,7 +861,7 @@ testCallBack(display); // Here display function is being passed as callback ## 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. +The singleton pattern is the most commonly used JavaScript design pattern and one that you will probably be aware of 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: - There should be only one instance allowed for a class and From cc3637dc0caad772a3a677bc800d2ca6d575bb23 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Thu, 14 Jun 2018 19:18:00 +0200 Subject: [PATCH 037/112] Update README.md typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f4501e7..fd48314 100644 --- a/README.md +++ b/README.md @@ -1288,7 +1288,7 @@ 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. -**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() { From e3b7873bf38098df4e807e2fe60952ecb8557480 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Fri, 22 Jun 2018 11:25:59 +0200 Subject: [PATCH 038/112] Q48 location -> address Thanks to @persevereC who proposed this changin in issue #40 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fd48314..462ae0e 100644 --- a/README.md +++ b/README.md @@ -1666,7 +1666,7 @@ var person = { age : 24 } -var location = { +var address = { addressLine1 : 'Some Location x', addressLine2 : 'Some Location y', city : 'NewYork' @@ -1675,7 +1675,7 @@ var location = { Write merge function which will take two object and add all the own property of second object into first object. ```javascript -merge(person , location); +merge(person , address); /* Now person should have 5 properties name , age , addressLine1 , addressLine2 , city */ From 796d1c6d44d16c44baf5bcccb24238f31f01f14c Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Fri, 22 Jun 2018 23:01:13 +0200 Subject: [PATCH 039/112] Q3 fix thanks to @chief10 in #28 --- README.md | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 462ae0e..74edea7 100644 --- a/README.md +++ b/README.md @@ -73,36 +73,35 @@ console.log(k); // output 1function ``` -## Question 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. +## Question 3. What is the drawback of having private methods in JavaScript object? +> One of the drawback of creating a private method in JavaScript is that they are very memory inefficient because a new copy of the method would be created for each instance. ```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 + this.name = name || ""; + this.company = company || ""; + this.salary = salary || 5000; // Private method var increaseSalary = function () { this.salary = this.salary + 1000; }; - // Public method - this.dispalyIncreasedSalary = function() { - increaseSalary(); - console.log(this.salary); - }; }; -// Create Employee class object +// adding the method to Employee's prototype +Employee.prototype.displayIncreasedSalary = function() { + increaseSalary(); + console.log(this.salary); +}; + +// Creating three Employee objects 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); ``` -Here each instance variable `emp1`, `emp2`, `emp3` has own copy of increaseSalary private method. +Here each instance variable `emp1`, `emp2`, `emp3` has own copy of increaseSalary private method. However the `displayIncreasedSalary` will only be added once to an object `Employee.prototype`. So as recommendation don't go for a private method unless it's necessary. From a4a95c48616fb6a647c0174753ce4bfaabf7582d Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 23 Jun 2018 00:46:10 +0200 Subject: [PATCH 040/112] Q15 explanation made clearer thanks to @fengshuo in #29 --- README.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 74edea7..00bf9ba 100644 --- a/README.md +++ b/README.md @@ -421,9 +421,15 @@ var z = 1, y = z = typeof y; console.log(y); ``` -> Above code will output 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. - +> Above code will output 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: +```javascript +var z; +z = 1; +var y; +z = typeof y; +y = z; +``` ## Question 16. What will be the output of the following code? From ee7b83d6d12c7236367fa30568df80a78729e121 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 23 Jun 2018 01:08:01 +0200 Subject: [PATCH 041/112] Q23 is improved thanks to @viktmv in #23 --- README.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 00bf9ba..7085691 100644 --- a/README.md +++ b/README.md @@ -771,8 +771,23 @@ 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. -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"]`. +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 = User("xyz"); +foo["location"] = "USA"; +// the console will show you that the result of this is "USA" + +``` + + ## Question 24. Suggest your question! From a31239f2e3799385a9e471e75c5eb3202c0ba2a0 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 23 Jun 2018 15:29:09 +0200 Subject: [PATCH 042/112] Q32 new question about promises --- README.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7085691..b3cbddb 100644 --- a/README.md +++ b/README.md @@ -1134,7 +1134,19 @@ function Clone(object){ } ``` -## Question 32. Suggest your question! +## Question 32. Suggest your question! What are promises and how they are useful? + +We use promises for handling asynchronous interactions in a sequential manner. The promise represents the future value. It has an internal state (`pending`, `fulfilled` and `rejected`) and works like a state machine. + +A promise object has `then` method, where you can specify what to do when the promise is fulfilled or rejected. + +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. + +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). ## Question 33. How to check whether a key exist in a JavaScript object or not. From b9f2b3f864c8ca7d291833cf2df1372fd2a8fa52 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 23 Jun 2018 15:31:55 +0200 Subject: [PATCH 043/112] Q32 addition --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b3cbddb..f425e31 100644 --- a/README.md +++ b/README.md @@ -1136,7 +1136,7 @@ function Clone(object){ ## Question 32. Suggest your question! What are promises and how they are useful? -We use promises for handling asynchronous interactions in a sequential manner. The promise represents the future value. It has an internal state (`pending`, `fulfilled` and `rejected`) and works like a state machine. +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. A promise object has `then` method, where you can specify what to do when the promise is fulfilled or rejected. From a7350a1aa44dd08fb63cfaa403a632fe7abf6956 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 23 Jun 2018 15:38:10 +0200 Subject: [PATCH 044/112] Q38 markup --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f425e31..fb48b92 100644 --- a/README.md +++ b/README.md @@ -1318,7 +1318,7 @@ 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. +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. **For Instance:** Defining `displayName()` method on `emp1` will not automatically override the employee `displayName`. @@ -1331,7 +1331,7 @@ 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** @@ -1345,7 +1345,7 @@ 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 above example, `emp1` is created with it's own value for name, so calling **displayName()** method 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. From b81851d7ca5073c75409f6db6bfe1b576cc367b9 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 23 Jun 2018 15:48:27 +0200 Subject: [PATCH 045/112] Q2 fixed thanks to @stevemao in #5 --- README.md | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index fb48b92..18d462c 100644 --- a/README.md +++ b/README.md @@ -50,28 +50,17 @@ if (function f() {}) { console.log(y); ``` -> 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. - +> Above code would give output `1undefined`. inside `if` statement we have `function f(){}`. Here's it's a function expression, not function statement, which is why f is not a variable. +> As a reminder, function expression is something like this: ```javascript -var k = 1; -if (1) { - eval(function foo() {}); - k += typeof foo; -} -console.log(k); +var myFunc1 = new function() {} +var myFunc2 = new function whatever() {} // whatever is not a variable here ``` - -Above code will also output `1undefined`. - +> A function statement is something like this: ```javascript -var k = 1; -if (1) { - function foo() {}; - k += typeof foo; -} -console.log(k); // output 1function +function myFunc3() {} ``` - +You can read about [function expressions](https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function) and [function statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function) on MDN. ## Question 3. What is the drawback of having private methods in JavaScript object? > One of the drawback of creating a private method in JavaScript is that they are very memory inefficient because a new copy of the method would be created for each instance. From 3665176abdbdcd985faf3cb2152c638ed5d65ded Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 23 Jun 2018 17:24:54 +0200 Subject: [PATCH 046/112] couln't finishi it by June... :( --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 18d462c..f195e92 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ # 123-JavaScript-Interview-Questions -This Book will be completed by June 2018 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](https://goo.gl/forms/c8ubV1tWBBdz6fJP2). +This Book will be completed by September 2018 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](https://goo.gl/forms/c8ubV1tWBBdz6fJP2). ## Great news! From 2fbb4e8efd2ab3d4b2ebf3615201cbe9b27a4341 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 23 Jun 2018 17:26:36 +0200 Subject: [PATCH 047/112] promises question fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f195e92..87e6a50 100644 --- a/README.md +++ b/README.md @@ -1123,7 +1123,7 @@ function Clone(object){ } ``` -## Question 32. Suggest your question! What are promises and how they are useful? +## Question 32. What are promises and how they are useful? 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. From 7ab444906fbece7ffa81b0d2ee44e19b562b78fe Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 23 Jun 2018 17:29:46 +0200 Subject: [PATCH 048/112] question 24 added --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 87e6a50..723f16f 100644 --- a/README.md +++ b/README.md @@ -777,9 +777,13 @@ foo["location"] = "USA"; ``` -## Question 24. Suggest your question! +## Question 24. What are Service Workers and when can you use them? +It’s a technology that allows your web application to use cached resources first, and provide default experience offline, before getting more data from the network later. This principle is commonly known as Offline First. +Service Workers actively use promises. A Service Worker has to be installed,activated and then it can react on fetch, push and sync events. + +As of 2017, Service Workers are not supported in IE and Safari. ## 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). From 1d282e080be3ae326a28987ef381fbbc26e3e8e3 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 23 Jun 2018 17:36:13 +0200 Subject: [PATCH 049/112] question 34 added --- README.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 723f16f..443e3be 100644 --- a/README.md +++ b/README.md @@ -1179,7 +1179,25 @@ console.log(person.hasOwnProperty('name')); // print true console.log(person.hasOwnProperty('salary')); // print false ``` -## Question 34. Suggest your question! +## Question 34. What is NaN, why do we need it, and when can it break the page? +`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 +Math.sqrt(-5); +Math.log(-1); +parseFloat("foo"); /* this is common: you get JSON from the server, convert some strings from JSON to a number and end up with NaN in your UI. */ +``` + +`NaN` is not equal to any number, it’s not less or more than any number, also it's not equal to itself: + +```javascript +NaN !== NaN +NaN < 2 // false +NaN > 2 // false +NaN === 2 // false +``` + +To check if the current value of the variable is NaN, you have to use the `isNaN` function. ## Question 35. Suggest your question! ## Question 36. What is best way to detect an arrays object on JavaScript ? From ff3e09c750c54c2031125e6611816a156234d294 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 24 Jun 2018 00:50:14 +0200 Subject: [PATCH 050/112] question 35 added --- README.md | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 443e3be..e8f70c1 100644 --- a/README.md +++ b/README.md @@ -1197,8 +1197,34 @@ NaN > 2 // false NaN === 2 // false ``` -To check if the current value of the variable is NaN, you have to use the `isNaN` function. -## Question 35. Suggest your question! +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. + +## Question 35. Fix the bug using ES5 only + +```javascript +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); +} +``` +For ES6, you can just replace `var i` with `let i`. + +For ES5, you need to create a function scope like here: + +```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); +} +``` + + ## Question 36. What is best way to detect an arrays object on JavaScript ? From 9192b88b0cc24f0af6f2e8df5d7115fecae05276 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 24 Jun 2018 01:03:44 +0200 Subject: [PATCH 051/112] Q1-Q15 typos and grammar fix --- README.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index e8f70c1..1e2f442 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Yuri Katkov from [Flashcards.js](http://flashcardsjs.com) became a co-author and 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 you are not defining what value it holds yet, but you are declaring its existence and the need for memory allocation. ```javascript var x; // declaring x @@ -62,7 +62,7 @@ function myFunc3() {} ``` You can read about [function expressions](https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function) and [function statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function) on MDN. -## Question 3. What is the drawback of having private methods in JavaScript object? +## Question 3. What is the drawback of having private methods in a JavaScript object? > One of the drawback of creating a private method in JavaScript is that they are very memory inefficient because a new copy of the method would be created for each instance. ```javascript @@ -97,10 +97,10 @@ So as recommendation don't go for a private method unless it's necessary. ## Question 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. -The closure has access to variable in three scopes: +The closure has access to the variable in three scopes: - Variable declared in his own scope - Variable declared in parent function scope -- Variable declared in global namespace +- Variable declared in the global namespace ```javascript var globalVar = "abc"; @@ -125,7 +125,7 @@ var globalVar = "abc"; })(7); // Pass 7 as parameter ``` -`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 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 the function as closure has access to the variable which is declared in `global namespace`. Output of above code would be: @@ -156,14 +156,14 @@ 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 the anonymous function which takes the second parameter and returns the anonymous function which takes the third parameter and returns the multiplication of arguments which is being passed in successive -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. +In Javascript function defined inside has access to outer function variable and function is the first class object so it can be returned by the function as well and passed as an 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 be stored as variable +- A function can be pass as a parameter to another function +- A function can be returned from another function ## Question 6. How to empty an array in JavaScript? For instance: @@ -199,7 +199,7 @@ console.log(anotherArrayList); // Output ['a', 'b', 'c', 'd', 'e', 'f'] 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`. +Above code 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: @@ -255,7 +255,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 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) { @@ -269,7 +269,7 @@ 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. -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]') { @@ -324,7 +324,7 @@ var output = (function() { console.log(output); ``` -> 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`. +> Above code 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`. ## Question 10. What will be the output of the following code? @@ -339,7 +339,7 @@ var output = (function() { console.log(output); ``` -> 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`. +> 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 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`. ## Question 11. What will be the output of the following code? @@ -367,7 +367,7 @@ 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`. -**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. +**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. @@ -379,7 +379,7 @@ delete trees[3]; console.log(trees.length); ``` -> 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. +> Above code will output `5` as output. When we used `delete` operator for deleting an array element then, the array length is not affected by this. This holds even if you deleted all elements of an array using `delete` operator. So when delete operator removes an array element that deleted element is 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"]`. From 0e4ab312cd7ec3cb9dd84e4fd9f459f9c88a879e Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 24 Jun 2018 01:05:55 +0200 Subject: [PATCH 052/112] q17 grammar --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1e2f442..c213107 100644 --- a/README.md +++ b/README.md @@ -462,7 +462,7 @@ var foo = function bar() { -## Question 17. What is the difference between declaring a function in below format? +## Question 17. What is the difference between declaring a function in the formats listed below? ```javascript var foo = function() { From 614f0786de8ec8a554391997b9b4b2e1f5c6b6d3 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 24 Jun 2018 01:08:52 +0200 Subject: [PATCH 053/112] grammar --- README.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index c213107..224f9ee 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ if (function f() {}) { console.log(y); ``` -> Above code would give output `1undefined`. inside `if` statement we have `function f(){}`. Here's it's a function expression, not function statement, which is why f is not a variable. +> The code above would give output `1undefined`. inside `if` statement we have `function f(){}`. Here's it's a function expression, not function statement, which is why f is not a variable. > As a reminder, function expression is something like this: ```javascript var myFunc1 = new function() {} @@ -182,7 +182,7 @@ How can we empty above array? 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: @@ -199,7 +199,7 @@ console.log(anotherArrayList); // Output ['a', 'b', 'c', 'd', 'e', 'f'] arrayList.length = 0; ``` -Above code 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. +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: @@ -309,7 +309,7 @@ var output = (function(x) { console.log(output); ``` -> 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. +> 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 **local variable**. `delete` operator doesn't affect local variable. ## Question 9. What will be the output of the following code? @@ -324,7 +324,7 @@ var output = (function() { console.log(output); ``` -> Above code 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`. +> 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`. ## Question 10. What will be the output of the following code? @@ -339,7 +339,7 @@ var output = (function() { console.log(output); ``` -> 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 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`. +> 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`. ## Question 11. What will be the output of the following code? @@ -353,7 +353,7 @@ 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. +> 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`. @@ -379,7 +379,7 @@ delete trees[3]; console.log(trees.length); ``` -> Above code 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. +> The code above will output `5` as output. When we used `delete` operator for deleting an array element then, the array length is not affected by this. This holds even if you deleted all elements of an array using `delete` operator. So when delete operator removes an array element that deleted element is 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"]`. @@ -395,7 +395,7 @@ console.log(bar + true); console.log(bar + false); ``` -> 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. General guideline for addition of operator: - Number + Number -> Addition - Boolean + Number -> Addition - Number + String -> Concatenation @@ -410,7 +410,7 @@ var z = 1, y = z = typeof y; console.log(y); ``` -> Above code will output 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: +> The code above will output 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: ```javascript var z; @@ -428,7 +428,7 @@ 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: +> The code above will output `Reference Error` as output. For making above code work you can re-write above code as follow: **Sample 1** @@ -548,7 +548,7 @@ var foo = function foo() { }; ``` -Above code behind the scene look something like below code: +The code above behind the scene look something like below code: ```javascript var foo = undefined; @@ -580,7 +580,7 @@ var salary = "1000$"; })(); ``` -> 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$`. 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$`. ```javascript var salary = "1000$"; From 57face1b4bc1582d2fc97b150ad91dbac30f69d4 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 24 Jun 2018 01:18:19 +0200 Subject: [PATCH 054/112] Q25 addition --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 224f9ee..ff6ea8f 100644 --- a/README.md +++ b/README.md @@ -786,6 +786,7 @@ Service Workers actively use promises. A Service Worker has to be installed,acti As of 2017, Service Workers are not supported in IE and Safari. ## 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). ```javascript @@ -816,7 +817,7 @@ 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. -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: +A method is a piece of code that is called by name and that is associated with the object. Methods are funtions. 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 From f856666bd9afb09baf4ee6ac9e8d110808fdd4bf Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 24 Jun 2018 01:26:54 +0200 Subject: [PATCH 055/112] q1-7 formatting and grammar --- README.md | 58 ++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 36 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index ff6ea8f..3654ddd 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,11 @@ This Book will be completed by September 2018 and available to buy. If you want Yuri Katkov from [Flashcards.js](http://flashcardsjs.com) became a co-author and the rights holder of the book. He will improve the questions and add some more from his collections of flashcards and will make sure to produce an unbeatable guide for frontend inteviews. -## 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`. +## 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 execute 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. @@ -23,14 +26,14 @@ 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`. -> 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 ``` -> 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 @@ -49,21 +52,27 @@ if (function f() {}) { } console.log(y); ``` +### Answer -> The code above would give output `1undefined`. inside `if` statement we have `function f(){}`. Here's it's a function expression, not function statement, which is why f is not a variable. -> As a reminder, function expression is something like this: +The code above would give the output `1undefined`. inside `if` statement we have `function f(){}`. Here's it's a function expression, not function statement, which is why f is not a variable. + +As a reminder, function expression is something like this: ```javascript var myFunc1 = new function() {} var myFunc2 = new function whatever() {} // whatever is not a variable here ``` -> A function statement is something like this: + +A function statement is something like this: ```javascript function myFunc3() {} ``` You can read about [function expressions](https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function) and [function statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function) on MDN. ## Question 3. What is the drawback of having private methods in a JavaScript object? -> One of the drawback of creating a 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 drawback of creating a private method in JavaScript is that they are very memory inefficient because a new copy of the method would be created for each instance. ```javascript var Employee = function (name, company, salary) { @@ -94,8 +103,11 @@ Here each instance variable `emp1`, `emp2`, `emp3` has own copy of increaseSalar So as recommendation don't go for a private method unless it's necessary. -## Question 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. +## Question 4. What is “closure” in javascript? Can you provide an example? + +### Answer + +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. The closure has access to the variable in three scopes: - Variable declared in his own scope @@ -143,8 +155,9 @@ globalVar = abc console.log(mul(2)(3)(4)); // output : 24 console.log(mul(4)(3)(4)); // output : 48 ``` +### Answer -> Below is code followed by an explanation how it works: +Below is the code followed by the explanation of how it works: ```javascript function mul (x) { @@ -172,11 +185,13 @@ For instance: 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 = []; @@ -193,7 +208,7 @@ arrayList = []; // Empty the array console.log(anotherArrayList); // Output ['a', 'b', 'c', 'd', 'e', 'f'] ``` -### Method 2 +#### Method 2 ```javascript arrayList.length = 0; @@ -210,7 +225,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); @@ -225,7 +240,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) { @@ -237,7 +252,10 @@ Above implementation can also empty the array. But not recommended to use often. ## Question 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` + +### 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]; @@ -458,10 +476,6 @@ var foo = function bar() { // bar is undefined here ``` - - - - ## Question 17. What is the difference between declaring a function in the formats listed below? ```javascript From c9c0e81f3fcac54ab8b81c4289c344f2d8bff867 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 24 Jun 2018 01:39:23 +0200 Subject: [PATCH 056/112] q7 grammar --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3654ddd..5178c6e 100644 --- a/README.md +++ b/README.md @@ -261,7 +261,7 @@ The best way to find whether an object is instance of a particular class or not 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) { @@ -273,7 +273,7 @@ function greet(param) { } ``` -However, in 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. +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) { @@ -285,7 +285,7 @@ However, in above implementation it might not necessary to check the type of the } ``` -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 the type of an object, As we mentioned that we can use `Object.prototype.toString` From 037a0eb85eb7453e849355df02650ed148cb61d2 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 24 Jun 2018 13:06:49 +0200 Subject: [PATCH 057/112] q7-q14 grammar --- README.md | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 5178c6e..881c7ff 100644 --- a/README.md +++ b/README.md @@ -326,8 +326,9 @@ 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 **local variable**. `delete` operator doesn't affect local variable. +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 **local variable**. `delete` operator doesn't affect local variables. ## Question 9. What will be the output of the following code? @@ -341,8 +342,9 @@ var output = (function() { console.log(output); ``` +### Answer -> 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`. +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`. ## Question 10. What will be the output of the following code? @@ -356,8 +358,9 @@ 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`. +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`. ## Question 11. What will be the output of the following code? @@ -371,7 +374,8 @@ delete emp1.company console.log(emp1.company); ``` -> The code above 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`. @@ -383,7 +387,12 @@ 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. @@ -396,10 +405,10 @@ 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. -> The code above will output `5` as output. When we used `delete` operator for deleting an array element then, the array length is not affected by this. This holds even if you deleted all elements of an array using `delete` operator. - -So when delete operator removes an array element that deleted element is 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"]`. +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"]`. @@ -412,8 +421,9 @@ console.log(bar + "xyz"); console.log(bar + true); console.log(bar + false); ``` +### Answer -> The code above 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 - Number + String -> Concatenation @@ -427,8 +437,9 @@ console.log(bar + false); var z = 1, y = z = typeof y; console.log(y); ``` +### Answer -> The code above will output 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: +The code above will output 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: ```javascript var z; @@ -446,7 +457,9 @@ var foo = function bar() { return 12; }; typeof bar(); ``` -> The code above 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** @@ -489,6 +502,7 @@ 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 : @@ -512,7 +526,7 @@ function bar() { ``` -The another advantage of first-one way of declaration that you can declare function based on certain condition for example: +Another advantage of first-one way of declaration that you can declare function based on certain condition for example: ```javascript ``` -Another advantage of first-one way of declaration that you can declare function based on certain condition for example: +Another advantage of declaring the function using function expressions is that you can declare function based on certain condition, for example: ```javascript ``` -But If you try to run similar code in the following format, it would give an error +But If you try to run similar code in the following format, it would result in an error ```javascript ``` -Another advantage of declaring the function using function expressions is that you can declare function based on certain condition, for example: - -```javascript - -``` - -But If you try to run similar code in the following format, it would result in an error - -```javascript - -``` - ## Question 18. what is function hoisting in JavaScript? **Function Expression** From 10afe78aefe9b11b9459ada083a4d2c2541d803a Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Tue, 14 Aug 2018 15:50:16 +0200 Subject: [PATCH 073/112] q2 replaced thanks to @fssq1993 and @yairEO --- README.md | 25 ++++++++----------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 456751b..b3739e4 100644 --- a/README.md +++ b/README.md @@ -43,30 +43,21 @@ console.log(y); // Output: ReferenceError: y is not defined [http://stackoverflow.com/questions/20822022/javascript-variable-definition-declaration](http://stackoverflow.com/questions/20822022/javascript-variable-definition-declaration) -## Question 2. What will be the output of the following code? +## Question 2. For which value of `x` the results of the following statements are not the same? + ```javascript -var y = 1; -if (function f() {}) { - y += typeof f; -} -console.log(y); +// if( x <= 100 ) {...} +if( !(x > 100) ) {...} ``` ### Answer -The code above would give the output `1undefined`. inside `if` statement we have `function f(){}`. Here's it's a function expression, not function statement, which is why f is not a variable. +`NaN <= 100` is `false` and `NaN > 100` is also `false`, so if the +value of `x` is `NaN`, the statements are not the same. -As a reminder, function expression is something like this: -```javascript -var myFunc1 = new function() {} -var myFunc2 = new function whatever() {} // whatever is not a variable here -``` +The same holds true for any value of x that being converted to Number, returns NaN, e.g.: `undefined`, `[1,2,5]`, `{a:22}` , etc. -A function statement is something like this: -```javascript -function myFunc3() {} -``` -You can read about [function expressions](https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function) and [function statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function) on MDN. +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 `isNaN()` function. ## Question 3. What is the drawback of having private methods in a JavaScript object? From 7fa59a4824bece9d26cb00ede848a0387ca3a7a0 Mon Sep 17 00:00:00 2001 From: AndroidFanatic Date: Mon, 20 Aug 2018 10:23:13 +0530 Subject: [PATCH 074/112] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b3739e4..a6e2385 100644 --- a/README.md +++ b/README.md @@ -130,7 +130,7 @@ innerFuncVar = y globalVar = abc ``` -## Question 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 From e15b5d6306adbac9418896954a8a21953f4a0bb7 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 2 Sep 2018 00:29:38 +0300 Subject: [PATCH 075/112] grammar fix --- README.md | 52 ++++++++++++++++++++++++++-------------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index a6e2385..543cb42 100644 --- a/README.md +++ b/README.md @@ -2645,7 +2645,7 @@ console.log(obj.innerMessage); Answer: 4) undefined true -### 3. What would the output of following code ? +### 3. What would be the output of following code ? ```javascript var obj = { @@ -2665,7 +2665,7 @@ console.log(obj.innerMessage()); Answer: 1) Hello -### 4. What would the output of following code ? +### 4. What would be the output of following code ? ```javascript var obj = { @@ -2686,7 +2686,7 @@ console.log(obj.innerMessage()); Answer: 3) undefined -### 5. What would the output of following code ? +### 5. What would be the output of following code ? ```javascript var obj = { @@ -2708,7 +2708,7 @@ console.log(obj.innerMessage()); Answer: 2) 'Hello' -### 6. What would the output of following code ? +### 6. What would be the output of following code ? ```javascript function myFunc(){ @@ -2726,7 +2726,7 @@ console.log(myFunc()); Answer: 3) undefined -### 7. What would the output of following code ? +### 7. What would be the output of following code ? ```javascript function myFunc(){ @@ -2744,7 +2744,7 @@ console.log(myFunc()); Answer: 2) 'Hi John' -### 8. What would the output of following code ? +### 8. What would be the output of following code ? ```javascript function myFunc() { @@ -2761,7 +2761,7 @@ console.log(myFunc()); Answer: 2) 'Hi John' -### 9. What would the output of following code ? +### 9. What would be the output of following code ? ```javascript function myFunc(param1,param2) { @@ -2779,7 +2779,7 @@ console.log(myFunc("a","b","c","d")); Answer: a) 2 2 2 -### 10. What would the output of following code ? +### 10. What would be the output of following code ? ```javascript function myFunc() { @@ -2799,7 +2799,7 @@ 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){ @@ -2829,7 +2829,7 @@ Answer: 1) John Person ## Scopes -### 1. What would the output of following code ? +### 1. What would be the output of following code ? ```javascript function passWordMngr() { @@ -2852,7 +2852,7 @@ console.log(userInfo.userName); Answer: 3) 12345678 undefined -### 2. What would the output of following code ? +### 2. What would be the output of following code ? ```javascript var employeeId = 'aq123'; @@ -2869,7 +2869,7 @@ console.log(Employee.employeeId); Answer: 4) undefined -### 3. What would the output of following code ? +### 3. What would be the output of following code ? ```javascript var employeeId = 'aq123'; @@ -2891,7 +2891,7 @@ console.log(new Employee().employeeId); Answer: 2) bq1uy 1BJKSJ bq1uy -### 4. What would the output of following code ? +### 4. What would be the output of following code ? ```javascript var employeeId = 'aq123'; @@ -2914,7 +2914,7 @@ Answer: 1) foo123 aq123 ## Call, Apply, Bind -### 1. What would the output of following code ? +### 1. What would be the output of following code ? ```javascript (function() { @@ -2933,7 +2933,7 @@ Answer: 1) foo123 aq123 Answer: 4) [ 'W', 'o', 'r', 'l', 'd' ] -### 2. What would the output of following code ? +### 2. What would be the output of following code ? ```javascript (function() { @@ -2964,7 +2964,7 @@ Answer: 4) [ 'W', 'o', 'r', 'l', 'd' ] Answer: 1) Total amount left in account: 5600 Total amount left in account: 5300 -### 3. What would the output of following code ? +### 3. What would be the output of following code ? ```javascript (function() { @@ -2996,7 +2996,7 @@ Answer: 1) Total amount left in account: 5600 Total amount left in account: 5300 Answer: 1) 5600 5300 5100 -### 4. What would the output of following code ? +### 4. What would be the output of following code ? ```javascript (function() { @@ -3028,7 +3028,7 @@ Answer: 1) 5600 5300 5100 Answer: 2) 3600 3300 3100 -### 5. What would the output of following code ? +### 5. What would be the output of following code ? ```javascript (function greetNewCustomer() { @@ -3049,7 +3049,7 @@ Answer: 1) Hello John ## Callback Function -### 1. What would the output of following code ? +### 1. What would be the output of following code ? ```javascript function getDataFromServer(apiUrl){ @@ -3074,7 +3074,7 @@ getDataFromServer('www.google.com').then(function(name){ Answer: 1) John -### 2. What would the output of following code ? +### 2. What would be the output of following code ? ```javascript (function(){ @@ -3122,7 +3122,7 @@ Answer: 1) [ 2, 8, 15, 16, 23, 42 ] ## Return Statement -### 1. What would the output of following code ? +### 1. What would be the output of following code ? ```javascript (function(){ @@ -3144,7 +3144,7 @@ Answer: 1) [ 2, 8, 15, 16, 23, 42 ] Answer: 4) Uncaught TypeError: Cannot read property 'fullName' of undefined -### 2. What would the output of following code ? +### 2. What would be the output of following code ? ```javascript function getNumber(){ @@ -3162,7 +3162,7 @@ console.log(numb); Answer: 1) 5 -### 3. What would the output of following code ? +### 3. What would be the output of following code ? ```javascript function getNumber(){ @@ -3180,7 +3180,7 @@ console.log(numb); Answer: 2) undefined -### 4**. What would the output of following code ? +### 4**. What would be the output of following code ? ```javascript function mul(x){ @@ -3202,7 +3202,7 @@ console.log(mul(2)(3)[1](4)); Answer: 1) 6, 10 -### 5**. What would the output of following code ? +### 5**. What would be the output of following code ? ```javascript function mul(x) { @@ -3226,7 +3226,7 @@ console.log(mul(2)(3).sum(4)); Answer: 1) 6, 10 -### 6. What would the output of following code ? +### 6. What would be the output of following code ? ```javascript function mul(x) { From be266526816ba6b4ccfee34668db4d75a3045ce8 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Tue, 25 Sep 2018 19:56:39 +0200 Subject: [PATCH 076/112] added more questions --- README.md | 202 +++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 161 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 543cb42..5dd7f75 100644 --- a/README.md +++ b/README.md @@ -489,22 +489,18 @@ The main difference is function `foo` is defined at `run-time` and is called fun ```javascript // Run-Time function declaration - ``` ```javascript // Parse-Time function declaration - ``` ## Question 18. what is function hoisting in JavaScript? @@ -1177,7 +1173,7 @@ Be sure that you can implement the promise, read [one of the articles on a topic ## Question 33. How to check whether a key exist in a JavaScript object or not. ->Let say we have `person` object with property **name** and **age** +Let say we have `person` object with property **name** and **age** ```javascript var person = { @@ -1263,7 +1259,7 @@ for (var i = 0; i < arr.length; i++) { ## Question 36. What is best way to detect an arrays object on JavaScript ? ->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 @@ -1279,9 +1275,21 @@ function(value){ Let's discuss some way to detect an array in JavaScript. -**Method 1 :** +**Method 1:** -Duck typing test for array type detection +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 ```javascript // Duck typing arrays @@ -1300,20 +1308,11 @@ 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:** +**Method 3:** -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. - ->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. @@ -1330,7 +1329,7 @@ function(value){ ## Question 37. Best way to detect reference values of any type in JavaScript ? -> 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**. + 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 @@ -1372,7 +1371,7 @@ console.log(emp1 instanceof Object); // true ## Question 38. Describe Object-Based inheritance in JavaScript. -> Object-based inheritance also called prototypal inheritance in which we one object inherit from another object without invoking a constructor function. + Object-based inheritance also called prototypal inheritance in which we one object inherit from another object without invoking a constructor function. The ECMAScript 5 **Object.create()** method is the easiest way for one object to inherit from another. @@ -1419,11 +1418,11 @@ 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"`. ->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. +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. Let say we have `Person` class which has name, age, salary properties and **incrementSalary()** method. @@ -1484,7 +1483,7 @@ Type-based inheritance is best used with developer defined constructor function ## 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. + 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: @@ -1510,7 +1509,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();** @@ -1535,7 +1534,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(); @@ -1593,7 +1592,7 @@ delete employee.name; // fails silently unless it's in strict mode ## Question 44. 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** + For example, If you log `console.log("Some message")` then output should be **(your message) Some message** 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. @@ -1627,7 +1626,7 @@ For example: We can create string using string literal and using String construc // using String constructor function var objStr = new String("Hi I am string object"); ``` -> We can use typeof operator to test string literal and instanceof operator to test String object. + We can use typeof operator to test string literal and instanceof operator to test String object. ```javascript function isString(str) { @@ -1641,7 +1640,7 @@ For example: We can create string using string literal and using String construc ``` ## Question 46 . What is typical use case for anonymous function in JavaScript ? -> Anonymous functions basically used in following scenario. + Anonymous functions basically used in following scenario. 1. No name is needed if function is only used in one place, then there is no need to add a name to function. @@ -1691,9 +1690,9 @@ For example: We can create string using string literal and using String construc alert("Hi I am anonymous callback function"); }); ``` -The best way to take decision for using anonymous function is to asked. +The best way to make a decision for using anonymous function is to ask the following question: -> Will the function which I am going to define will use anywhere else. + Will the function which I am going to define, be used anywhere else? If your answer is yes then go and create named function rather anonymous function. @@ -1704,7 +1703,7 @@ If your answer is yes then go and create named function rather anonymous functio ## Question 47 . How to set a default parameter value ? -> 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 : + 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 @@ -1762,7 +1761,7 @@ sentEmail({ ``` ## Question 48. Write code for merge two JavaScript Object dynamically. -> Let say you have two object +Let say you have two objects ```javascript var person = { @@ -1787,7 +1786,7 @@ name , age , addressLine1 , addressLine2 , city */ **Method 1: Using ES6, Object assign method** ```javascript -const merge = (toObj, fromObj) => Object.assign(toObj, fromObj); +const merge = (toObj, fromObj) = Object.assign(toObj, fromObj); ``` **Method 2: Without using in-built function** @@ -1810,7 +1809,7 @@ function merge(toObj, fromObj) { ``` ## Question 49. What is non-enumerable property in JavaScript and how can create ? ->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. +Object can have properties that don't show up when you iterate through object using for...in loop or using Object.keys() to get an array of property names. This properties is know as non-enumerable properties. Let say we have following object @@ -1857,7 +1856,7 @@ Changing non-enumerable property value will return error in `strict mode`. In no ## Question 50. What is Function binding ? -> 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. + Function binding falls in advance JavaScript category and this is very popular technique to use in conjunction with event handler and callback function to preserve code execution context while passing function as a parameter. Let's consider the following example: @@ -1898,6 +1897,126 @@ btn.addEventListener('click', clickHandler.handleClick.bind(clickHandler)); # 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) +``` + +The output will `'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) +``` +The output will `{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) +``` + +The output will `{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) +``` + +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) +``` + +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. + +### 5. 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); +``` +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]` + + +### 6. What would be the output of following code? + +```javascript +var arrA = [{prop1: "value of array A!!"}, {someProp: "also value of array A!"}]; +var arrB = arrA.slice(); +arrB[0].prop1=42; +console.log(arrA); +``` + +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); @@ -2088,7 +2207,7 @@ Answer: 1) undefined Answer: 3) function function -## Object +## Objects ### 1. What would be the output of following code ? @@ -2328,7 +2447,7 @@ Answer: 3) foo foo Answer: 2) undefined undefined -## Array +## Arrays ### 1. What would be the output of following code? @@ -2598,7 +2717,7 @@ Answer: 1. [ 'bar', 'john' ] [] [ 'foo' ] Answer: 3. [ 15, 16, 2, 23, 42, 8 ] -## Function: +## Functions ### 1. What would be the output of following code ? @@ -3047,7 +3166,8 @@ Answer: 1) Hello John ### 6. Suggest your question! -## Callback Function + +## Callback Functions ### 1. What would be the output of following code ? From 6aeeb8c23dca9276702291c5ed1a351318369626 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Fri, 28 Sep 2018 14:28:58 +0200 Subject: [PATCH 077/112] style --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 5dd7f75..69837e3 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,7 @@ 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 @@ -197,7 +197,7 @@ arrayList.length = 0; The code above will clear the existing array by setting its length to 0. This way of emptying an array will also update all the reference variables that point to the original array. -For Instance: +For instance: ```javascript var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array @@ -1257,11 +1257,11 @@ for (var i = 0; i < arr.length; i++) { -## Question 36. What is best way to detect an arrays object on JavaScript ? +## Question 36. How to check if the value of a variable in an array? 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){ @@ -1314,7 +1314,7 @@ So this method is not a best way to detect an array as you can see it's not hand 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){ @@ -1375,7 +1375,7 @@ console.log(emp1 instanceof Object); // true The ECMAScript 5 **Object.create()** method is the easiest way for one object to inherit from another. -**For Instance:** +**For instance:** ```javascript var employee = { @@ -1391,7 +1391,7 @@ 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. -**For Instance:** Defining `displayName()` method on `emp1` will not automatically override the employee `displayName`. +**For instance:** Defining `displayName()` method on `emp1` will not automatically override the employee `displayName`. ```javascript emp1.displayName = function() { @@ -1703,7 +1703,7 @@ If your answer is yes then go and create named function rather anonymous functio ## Question 47 . How to set a default parameter value ? - 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 : + 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 @@ -1716,7 +1716,7 @@ def sentEmail(configuration, provider = 'Gmail'): There are a lot of ways by which you can achieve this in pre ES2015. -Let's understand below code by which we achieved setting default parameter value. +Let's understand the code below by which we achieved setting default parameter value. **Method 1: Setting default parameter value** From 219bfb8afa488f05f44967158628a7fe5be1e200 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 29 Sep 2018 00:25:17 +0200 Subject: [PATCH 078/112] style --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 69837e3..7fe2b3c 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ It's a book about frontend interview question. We hope that it will help all javascript developers to prepare for a technical job interview. -## If you want to buy a book in paper form +## Want to by a book in paper form? Want some badass flashcards? - This Book will be completed by September 2018 and then it will be available to buy. If you want me to sent an early copy of this book, please add your name and email address in google form here [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 the interviewers printed on beautiful poker-size flashcards. From 02913369035844ecfd03bc8162715b6894b8df76 Mon Sep 17 00:00:00 2001 From: Islam Sayed Date: Sun, 30 Sep 2018 07:52:52 +0200 Subject: [PATCH 079/112] fix typo fix typo from by to buy in line 7 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7fe2b3c..8f0a937 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ It's a book about frontend interview question. We hope that it will help all javascript developers to prepare for a technical job interview. -## Want to by a book in paper form? Want some badass flashcards? +## Want to buy a book in paper form? Want some badass flashcards? - This Book will be completed by September 2018 and then it will be available to buy. If you want me to sent an early copy of this book, please add your name and email address in google form here [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 the interviewers printed on beautiful poker-size flashcards. From 5a01d5649995064f0d7794ff6bd1d158dcda1ae9 Mon Sep 17 00:00:00 2001 From: Islam Sayed Date: Sun, 30 Sep 2018 08:22:39 +0200 Subject: [PATCH 080/112] add output for Boolean + Boolean Add missing output for the plus operator with all Boolean values which would be "Addition" --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 7fe2b3c..bae1921 100644 --- a/README.md +++ b/README.md @@ -407,10 +407,12 @@ console.log(bar + false); 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 + ## Question 15. What will be the output of the following code? From 5aaf80884a9bce5414c21d13a696513af8a060a2 Mon Sep 17 00:00:00 2001 From: Umesh Kumar Date: Mon, 1 Oct 2018 18:04:12 +0530 Subject: [PATCH 081/112] fix typo error --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4de35de..14d0190 100644 --- a/README.md +++ b/README.md @@ -837,7 +837,7 @@ obj1.myMethod(); // will print "Hi there" following with obj1. ## 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 exmaple of IIFE: +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() { From 8efd04a2d5e0d4ee957bb00bc065f16c8d1d4f2f Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 6 Oct 2018 17:17:30 +0200 Subject: [PATCH 082/112] terminological changes --- README.md | 50 ++++++++++++++++++++++++-------------------------- 1 file changed, 24 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 14d0190..2587739 100644 --- a/README.md +++ b/README.md @@ -477,13 +477,13 @@ var foo = function bar() { ```javascript var foo = function() { // Some code -}; +} ``` ```javascript function bar () { // Some code -}; +} ``` ### Answer @@ -502,21 +502,23 @@ The main difference is function `foo` is defined at `run-time` and is called fun bar(); // Call bar function here, It will not give an Error function bar() { console.log("Hi I am inside Foo"); -}; +} ``` -## Question 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; - }; + } ``` -### Answer - -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: +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 @@ -525,7 +527,7 @@ var foo = function foo() { }; ``` -The code above behind the scene look something like below code: +The code above behind the scene look something like this: ```javascript var foo = undefined; @@ -1371,11 +1373,9 @@ console.log(emp1 instanceof Employee); // true console.log(emp1 instanceof Object); // true ``` -## Question 38. Describe Object-Based inheritance in JavaScript. - - Object-based inheritance also called prototypal inheritance in which we one object inherit from another object without invoking a constructor function. +## Question 38. How does Object.create method works JavaScript? -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:** @@ -1391,7 +1391,7 @@ 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` will not automatically override the employee `displayName`. @@ -1406,7 +1406,7 @@ 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. -**For Example** +**For example** ```javascript var emp1 = Object.create(employee, { @@ -1418,13 +1418,11 @@ 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. -## 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? Let say we have `Person` class which has name, age, salary properties and **incrementSalary()** method. @@ -1449,7 +1447,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 @@ -1493,7 +1491,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 +1565,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"; @@ -1791,7 +1789,7 @@ name , age , addressLine1 , addressLine2 , city */ const merge = (toObj, fromObj) = Object.assign(toObj, fromObj); ``` -**Method 2: Without using in-built function** +**Method 2: Without using built-in function** ```javascript function merge(toObj, fromObj) { @@ -1809,7 +1807,7 @@ function merge(toObj, fromObj) { } } ``` -## Question 49. What is non-enumerable property in JavaScript and how can create ? +## Question 49. What is non-enumerable property in JavaScript and how you can create one? 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. @@ -1843,7 +1841,7 @@ Object.defineProperty(person, 'phoneNo',{ Object.keys(person); // ['name', 'salary', 'country'] ``` -In above example `phoneNo` property didn't show up because we made it non-enumerable by setting **enumerable:false** +In the example above `phoneNo` property didn't show up because we made it non-enumerable by setting **enumerable:false** Now let's try to change value of `phoneNo` From aafa07a441f30ad72f249691a0741855253d5cbf Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sat, 6 Oct 2018 17:35:57 +0200 Subject: [PATCH 083/112] Question 3 clearer examples --- README.md | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 2587739..f4d2b03 100644 --- a/README.md +++ b/README.md @@ -59,11 +59,11 @@ The same holds true for any value of x that being converted to Number, returns N 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 `isNaN()` function. -## Question 3. What is the drawback of having private methods in a JavaScript object? +## Question 3. What is the drawback of declaring methods directly in JavaScript objects? ### Answer -One of the drawback of creating a private method in JavaScript is that they are very memory inefficient because a new copy of the method would be created for each instance. +One of the drawback 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. Let's see it on example: ```javascript var Employee = function (name, company, salary) { @@ -71,18 +71,24 @@ var Employee = function (name, company, salary) { this.company = company || ""; this.salary = salary || 5000; - // We can create a private method like this - var increaseSalary = function () { - this.salary = this.salary + 1000; + // We can create a method like this: + this.formatSalary = function () { + return "$ " + this.salary; }; - }; -``` +// we can also create method in Employee's prototype: +Employee.prototype.formatSalary2 = function() { + return "$ " + this.salary; +} -Here each instance variable `emp1`, `emp2`, `emp3` has own copy of increaseSalary private method. However the `displayIncreasedSalary` will only be added once to an object `Employee.prototype`. +//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); +``` -So as recommendation don't go for a private method unless it's necessary. +Here each instance variable `emp1`, `emp2`, `emp3` has own copy of `formatSalary` method. However the `formatSalary2` will only be added once to an object `Employee.prototype`. ## Question 4. What is “closure” in javascript? Can you provide an example? From d3ae6bddd2b2c8cb530c0174e59c6d89175138d6 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 11 Nov 2018 19:19:25 +0100 Subject: [PATCH 084/112] #46 fixed thanks to @nomean42 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f4d2b03..037cb10 100644 --- a/README.md +++ b/README.md @@ -2776,7 +2776,7 @@ Answer: 4) undefined true var obj = { message: "Hello", innerMessage: function() { - console.log(this.message); + return this.message; } }; From 3d27d2d6f099458dcbfefbb962c43c99552a20e3 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 11 Nov 2018 19:20:23 +0100 Subject: [PATCH 085/112] #63 fixed thanks to @nomean42 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 037cb10..fbfee0e 100644 --- a/README.md +++ b/README.md @@ -2487,7 +2487,7 @@ Answer: 3) ["100"] 1 ``` 1. [] [] [Array[5]] 1 -2. [] [undefined × 100] Array[5] 5 +2. [] [undefined × 100] Array[5] 1 3. [] [] ['1',2,'3',4,5.6] 5 4. [] [] [Array[5]] 5 From c1022254dbfac53514ad533a0c188fac572d6e15 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 11 Nov 2018 19:21:11 +0100 Subject: [PATCH 086/112] #61 fixed thanks to @nomean42 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fbfee0e..58d6be3 100644 --- a/README.md +++ b/README.md @@ -1792,7 +1792,7 @@ name , age , addressLine1 , addressLine2 , city */ **Method 1: Using ES6, Object assign method** ```javascript -const merge = (toObj, fromObj) = Object.assign(toObj, fromObj); +const merge = (toObj, fromObj) => Object.assign(toObj, fromObj); ``` **Method 2: Without using built-in function** From f0eedd61a53117cfddfdcb5cff02b1ae04a5ce3e Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 11 Nov 2018 19:24:41 +0100 Subject: [PATCH 087/112] #61 fixed thanks to @nomean42 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 58d6be3..cc71d94 100644 --- a/README.md +++ b/README.md @@ -1789,7 +1789,7 @@ merge(person , address); /* Now person should have 5 properties name , age , addressLine1 , addressLine2 , city */ ``` -**Method 1: Using ES6, Object assign method** +**Method 1: Using ES6, Object.assign method** ```javascript const merge = (toObj, fromObj) => Object.assign(toObj, fromObj); From cdb86b673e78b6dd065e4cc550ecb7b1ab872820 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 11 Nov 2018 19:27:31 +0100 Subject: [PATCH 088/112] #60 fixed thanks to @vibl --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cc71d94..a7c6b85 100644 --- a/README.md +++ b/README.md @@ -1618,7 +1618,7 @@ function appLog() { console.log.apply(console, args); } -console.log(appLog("Some error message")); +appLog("Some error message"); //output of above console: 'your app name Some error message' ``` From 561f8f17df47ff52116634a1510673e3286627e4 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Sun, 11 Nov 2018 19:29:38 +0100 Subject: [PATCH 089/112] #59 fixed thanks to @vibl --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a7c6b85..391a54b 100644 --- a/README.md +++ b/README.md @@ -1091,7 +1091,7 @@ Solution: 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]; From 607d5620959720df7970c9d8db5b0bb6e48f9894 Mon Sep 17 00:00:00 2001 From: Orinami Olatunji Date: Sat, 24 Nov 2018 14:40:40 +0100 Subject: [PATCH 090/112] Update README.md Fixed what I think is a typo in line 16: 'will stop execute thereafter' to 'will stop executing thereafter' --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 391a54b..4d35cb3 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ It's a book about frontend interview question. We hope that it will help all jav ### 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 execute thereafter. But If you use `typeof undeclared_variable` then it will return `undefined`. +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. From 18fb7ca907d483c41f94f171ca13f68eef601af8 Mon Sep 17 00:00:00 2001 From: LLeeL <47989994+LLeeL@users.noreply.github.com> Date: Wed, 20 Mar 2019 22:18:15 -0400 Subject: [PATCH 091/112] Change coding questions 6 missing 3,4,5 in array (otherwise will not match the output) add arrB[3] = 20; to show the difference between passed by value and passed by reference --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d35cb3..03ca4aa 100644 --- a/README.md +++ b/README.md @@ -1992,9 +1992,10 @@ Arrays are object in JS, so both varaibles arrA and arrB point to the same array ### 6. What would be the output of following code? ```javascript -var arrA = [{prop1: "value of array A!!"}, {someProp: "also value of array A!"}]; +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); ``` From b461d61f33c3f204e5a76d69689b7e1f4db7838d Mon Sep 17 00:00:00 2001 From: Anand Shenoy Date: Mon, 13 May 2019 21:30:54 -0700 Subject: [PATCH 092/112] Adding a Question between 17 and 18 --- README.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 03ca4aa..8e7a9c1 100644 --- a/README.md +++ b/README.md @@ -478,7 +478,7 @@ var foo = function bar() { // bar is undefined here ``` -## Question 17. What is the difference between declaring a function in the formats listed below? +## Question 17a. What is the difference between declaring a function in the formats listed below? ```javascript var foo = function() { @@ -510,6 +510,21 @@ function bar() { console.log("Hi I am inside Foo"); } ``` +## Question 17b. What is the output of the following? + +```javascript +bar(); +(function abc(){console.log('something')})(); +function bar(){console.log('bar got called')}; +``` +### Answer + +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. ## Question 18. In which case the function definition is not hoisted in JavaScript? From c49bc46a18488957e0f63097769726f36d5d5fb4 Mon Sep 17 00:00:00 2001 From: Chris Diana Date: Sat, 1 Jun 2019 11:10:06 -0600 Subject: [PATCH 093/112] Function declaration typo and grammar fixes --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 03ca4aa..48eb6b8 100644 --- a/README.md +++ b/README.md @@ -493,7 +493,7 @@ function bar () { ``` ### Answer -The main difference is function `foo` is defined at `run-time` and is called function expression, whereas function `bar` is defined at parse time and is called function statement. To understand in better, let's 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 From c04040bdc98c34245cfdec21c3a6bdde4e98d999 Mon Sep 17 00:00:00 2001 From: Yuri Katkov Date: Mon, 8 Jul 2019 17:01:48 +0300 Subject: [PATCH 094/112] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index edaa43b..f27ba64 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ It's a book about frontend interview question. We hope that it will help all jav ## Want to buy a book in paper form? Want some badass flashcards? - - This Book will be completed by September 2018 and then it will be available to buy. If you want me to sent an early copy of this book, please add your name and email address in google form here [Google Form](https://goo.gl/forms/c8ubV1tWBBdz6fJP2). + - This Book will be soon completed and then it will be available to buy in a paper form. If you want me to sent an early copy of this book, please add your name and email address in google form here [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 the interviewers printed on beautiful poker-size flashcards. ## Question 1. What's the difference between `undefined` and `not defined` in JavaScript From f4dcf2921fccdd86bc4e20f25820f4f9031b14da Mon Sep 17 00:00:00 2001 From: Vova Date: Fri, 27 Sep 2019 21:50:44 +0300 Subject: [PATCH 095/112] resolve ganqqwerty/123-Essential-JavaScript-Interview-Questions#78 --- README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f27ba64..74ecb19 100644 --- a/README.md +++ b/README.md @@ -1864,16 +1864,15 @@ 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** + Now let's try to change value of `phoneNo` ```javascript person.phoneNo = '7777777777'; ``` -Changing non-enumerable 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. - -**Bonus** -**Object.defineProperty()** is also let you create read-only properties as we saw above, we are not able to modify phoneNo value of a person object. +**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. ## Question 50. What is Function binding ? From b7c226654c95d98054d2330e01b9c484ed467678 Mon Sep 17 00:00:00 2001 From: Pramod Mali Date: Tue, 5 Nov 2019 21:23:39 +0530 Subject: [PATCH 096/112] Added Interview Question --- README.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/README.md b/README.md index 74ecb19..d0adc70 100644 --- a/README.md +++ b/README.md @@ -3391,7 +3391,32 @@ console.log(mul(2)(3)(4)(5)(6)); Answer: 1) 720 +### 6. 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 From 3c6405cc89d3a795ee7a9a6bb0ee08996862d9a2 Mon Sep 17 00:00:00 2001 From: Pramod Mali Date: Tue, 5 Nov 2019 23:15:29 +0530 Subject: [PATCH 097/112] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d0adc70..5737ad9 100644 --- a/README.md +++ b/README.md @@ -3391,7 +3391,7 @@ console.log(mul(2)(3)(4)(5)(6)); Answer: 1) 720 -### 6. What would be the output of following code ? +### 7. What would be the output of following code ? ```javascript function getName1(){ From 616695c43737d82e2767a8fd7d057deba5c9bc38 Mon Sep 17 00:00:00 2001 From: Tomer Ovadia Date: Tue, 12 Nov 2019 19:38:42 +0200 Subject: [PATCH 098/112] Update README.md --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index 74ecb19..eeb3953 100644 --- a/README.md +++ b/README.md @@ -1352,6 +1352,18 @@ function(value){ } ``` +**Method 4:** + +You can query the constructor name: + +```javascript +function isArray(value) { + return value.constructor.name === "Array"; +} + +``` + + ## Question 37. Best way to detect reference values of any type in JavaScript ? 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**. From 234c12998b88e831cf4711649d09f9d43e6b0911 Mon Sep 17 00:00:00 2001 From: Tomer Ovadia Date: Tue, 12 Nov 2019 19:45:04 +0200 Subject: [PATCH 099/112] Update README.md --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index eeb3953..c638e88 100644 --- a/README.md +++ b/README.md @@ -1363,6 +1363,15 @@ function isArray(value) { ``` +**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 ? From a294916d3d74db80457150c9c65b7855131c521a Mon Sep 17 00:00:00 2001 From: Harman Kumar <50094184+harmansingha@users.noreply.github.com> Date: Sat, 30 Nov 2019 12:53:33 +0530 Subject: [PATCH 100/112] Added New Method for setting default value in ES6 --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index c638e88..6124331 100644 --- a/README.md +++ b/README.md @@ -1802,6 +1802,27 @@ sentEmail({ }, 'Yahoo Mail'); ``` +**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'); +``` + ## Question 48. Write code for merge two JavaScript Object dynamically. Let say you have two objects From 3f0a94f412d962b149677a35bbd9f70df92734e4 Mon Sep 17 00:00:00 2001 From: Moshiur Rahman <15215020+moshiurse@users.noreply.github.com> Date: Sun, 1 Dec 2019 00:06:28 +0600 Subject: [PATCH 101/112] fix duplicate variable name --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c638e88..4c4b870 100644 --- a/README.md +++ b/README.md @@ -1046,8 +1046,8 @@ This method is useful if we want to create several similar objects. In the code // 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 From c6439af1d361b2f896909dc883e8de254aca60e7 Mon Sep 17 00:00:00 2001 From: Pramod Mali Date: Tue, 3 Dec 2019 17:21:45 +0530 Subject: [PATCH 102/112] Added explaination to Question --- README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/README.md b/README.md index 5737ad9..746f472 100644 --- a/README.md +++ b/README.md @@ -3418,7 +3418,26 @@ personObj.getName2(); 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); +} + +Object.prototype.getName2 = () =>{ + console.log(Object.getPrototypeOf(this).name); +} + +let personObj = { + name:"Tony", + print:getName1 +} + +personObj.print(); +Object.prototype.name="Steve"; +personObj.getName2(); +``` ## Contributing From cb6acce9a22d7d2ff3417e07418c4a73e394ff0f Mon Sep 17 00:00:00 2001 From: Pramod Mali Date: Mon, 13 Jan 2020 23:01:16 +0530 Subject: [PATCH 103/112] Updating question 35 --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index 746f472..bb1afb0 100644 --- a/README.md +++ b/README.md @@ -1280,7 +1280,16 @@ for (var i = 0; i < arr.length; i++) { } ``` +This can also achieve by forEach (allows you to keep that variable within the forEach’s scope) +```javascript +var arr = [10, 32, 65, 2]; +arr.forEach(function(i) { + setTimeout(function() { + console.log('The index of this number is: ' + i); + }, 3000); +}) +``` ## Question 36. How to check if the value of a variable in an array? From ff5be2a8fc4e76fc3204b0996403c6f34e2ba6d2 Mon Sep 17 00:00:00 2001 From: Rahul Kumar <37505384+rahuldbs@users.noreply.github.com> Date: Mon, 6 Apr 2020 21:54:11 +0530 Subject: [PATCH 104/112] corrected the foreach solution of question 35 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5e0d5f2..c222fdd 100644 --- a/README.md +++ b/README.md @@ -1284,7 +1284,7 @@ This can also achieve by forEach (allows you to keep that variable within the fo ```javascript var arr = [10, 32, 65, 2]; -arr.forEach(function(i) { +arr.forEach(function(ele, i) { setTimeout(function() { console.log('The index of this number is: ' + i); }, 3000); From fae6fabf9a32eb6bf0e656189dcef47e038f32d3 Mon Sep 17 00:00:00 2001 From: thinhnv Date: Sun, 9 Aug 2020 16:38:42 +0700 Subject: [PATCH 105/112] :art: [REFACTOR] - Add collapsed answers - fix the counting wrong 1 - Hide the answers in the collapsed section! Make people easy to practise the questions! 2 - Fix the counting wrong in question 40-44 ( missing 41 42 43 ) --- README.md | 634 ++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 524 insertions(+), 110 deletions(-) diff --git a/README.md b/README.md index c222fdd..5a4ba4d 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ It's a book about frontend interview question. We hope that it will help all jav ## Question 1. What's the difference between `undefined` and `not defined` in JavaScript -### Answer +
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`. @@ -42,6 +42,7 @@ 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) +
## Question 2. For which value of `x` the results of the following statements are not the same? @@ -50,7 +51,7 @@ console.log(y); // Output: ReferenceError: y is not defined // if( x <= 100 ) {...} if( !(x > 100) ) {...} ``` -### Answer +
Answer `NaN <= 100` is `false` and `NaN > 100` is also `false`, so if the value of `x` is `NaN`, the statements are not the same. @@ -59,9 +60,11 @@ The same holds true for any value of x that being converted to Number, returns N 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 `isNaN()` function. +
+ ## Question 3. What is the drawback of declaring methods directly in JavaScript objects? -### Answer +
Answer One of the drawback 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. Let's see it on example: @@ -90,9 +93,11 @@ var emp3 = new Employee('Erich Fromm', 'Company 3', 1299483); Here each instance variable `emp1`, `emp2`, `emp3` has own copy of `formatSalary` method. However the `formatSalary2` will only be added once to an object `Employee.prototype`. +
+ ## Question 4. What is “closure” in javascript? Can you provide an example? -### Answer +
Answer 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. @@ -136,13 +141,15 @@ innerFuncVar = y globalVar = abc ``` +
+ ## 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 ``` -### Answer +
Answer Below is the code followed by the explanation of how it works: @@ -165,6 +172,8 @@ In Javascript function defined inside has access to outer function variable and - A function can be pass as a parameter to another function - A function can be returned from another function +
+ ## Question 6. How to empty an array in JavaScript? For instance: @@ -174,7 +183,7 @@ var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; How can we empty the array above? -### Answer +
Answer There are a couple of ways by which we can empty an array, So let's discuss all the possible way by which we can empty an array. @@ -238,9 +247,11 @@ while(arrayList.length) { Above implementation can also empty the array. But not recommended to use often. +
+ ## Question 7. How to check if an object is an array or not? -### Answer +
Answer The best way to find whether an object is instance of a particular class or not using `toString` method from `Object.prototype` @@ -303,6 +314,8 @@ Array.isArray(arrayList); `Array.isArray` is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5 +
+ ## Question 8. What will be the output of the following code? ```javascript @@ -313,11 +326,13 @@ var output = (function(x) { console.log(output); ``` -### Answer +
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 **local variable**. `delete` operator doesn't affect local variables. +
+ ## Question 9. What will be the output of the following code? ```javascript @@ -329,11 +344,13 @@ var output = (function() { console.log(output); ``` -### Answer +
Answer 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`. +
+ ## Question 10. What will be the output of the following code? ```javascript @@ -345,11 +362,13 @@ var output = (function() { console.log(output); ``` -### Answer +
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`. +
+ ## Question 11. What will be the output of the following code? ```javascript @@ -361,12 +380,14 @@ delete emp1.company console.log(emp1.company); ``` -### Answer +
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`. +
+ ## Question 12. What is `undefined x 1` in JavaScript ```javascript @@ -374,7 +395,7 @@ var trees = ["redwood", "bay", "cedar", "oak", "maple"]; delete trees[3]; ``` -### Answer +
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"]` @@ -385,6 +406,8 @@ Clearly we can see that Chrome has its own way of displaying uninitialized index +
+ ## Question 13. What will be the output of the following code? ```javascript @@ -392,13 +415,15 @@ var trees = ["xyz", "xxxx", "test", "ryan", "apple"]; delete trees[3]; console.log(trees.length); ``` -### Answer +
Answer The code above will output `5` as output. When we used `delete` operator for deleting an array element then, the array length is not affected by this. This holds even if you deleted all elements of an array using `delete` operator. So when delete operator removes an array element that deleted element is no longer present in the array. In place of value at deleted 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"]`. +
+ ## Question 14. What will be the output of the following code? ```javascript @@ -408,7 +433,7 @@ console.log(bar + "xyz"); console.log(bar + true); console.log(bar + false); ``` -### Answer +
Answer The code above will output `1, "truexyz", 2, 1` as output. Here's a general guideline for the plus operator: - Number + Number -> Addition @@ -420,13 +445,15 @@ The code above will output `1, "truexyz", 2, 1` as output. Here's a general guid +
+ ## Question 15. What will be the output of the following code? ```javascript var z = 1, y = z = typeof y; console.log(y); ``` -### Answer +
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: @@ -438,6 +465,8 @@ z = typeof y; y = z; ``` +
+ ## Question 16. What will be the output of the following code? ```javascript @@ -446,7 +475,7 @@ var foo = function bar() { return 12; }; typeof bar(); ``` -### Answer +
Answer The output will be `Reference Error`. To fix the bug we can try to rewrite the code a little bit: @@ -478,6 +507,8 @@ var foo = function bar() { // bar is undefined here ``` +
+ ## Question 17a. What is the difference between declaring a function in the formats listed below? ```javascript @@ -491,7 +522,7 @@ function bar () { // Some code } ``` -### Answer +
Answer 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 : @@ -510,6 +541,8 @@ function bar() { console.log("Hi I am inside Foo"); } ``` +
+ ## Question 17b. What is the output of the following? ```javascript @@ -517,7 +550,7 @@ bar(); (function abc(){console.log('something')})(); function bar(){console.log('bar got called')}; ``` -### Answer +
Answer The output will be : ``` @@ -526,10 +559,11 @@ 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. -## Question 18. In which case the function definition is not hoisted in JavaScript? +
+## Question 18. In which case the function definition is not hoisted in JavaScript? -### Answer +
Answer Let's take the following **function expression** @@ -566,6 +600,8 @@ foo = function foo() { foo(); // Now foo is defined here ``` +
+ ## Question 19. What will be the output of the following code? ```javascript @@ -579,7 +615,7 @@ var salary = "1000$"; console.log("My New Salary " + salary); })(); ``` -### Answer +
Answer 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. @@ -596,9 +632,11 @@ var salary = "1000$"; })(); ``` +
+ ## Question 20. What’s the difference between `typeof` and `instanceof`? -### Answer +
Answer `typeof` is an operator that returns a string with the type of whatever you pass. @@ -623,6 +661,8 @@ name instanceof String; // Output : true 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) +
+ ## Question 21. Calculate the length of the associative array ```javascript @@ -632,7 +672,7 @@ var counterArray = { }; counterArray["C"] = 1; ``` -### Answer +
Answer First of all, in case of JavaScript an associative array is the same as an object. Secondly, even though is no built-in function or property available to calculate the length/size an object, we can write such function ourselves. @@ -676,7 +716,12 @@ _.size({one: 1, two: 2, three: 3}); => 3 ``` +
+ ## Question 22. Difference between `Function`, `Method` and `Constructor` calls in JavaScript. + +
Answer + If your are familiar with Object-oriented programming, More likely familiar to thinking of functions, methods, and class constructors as three separate things. But In JavaScript, these are just three different usage patterns of one single construct. functions : The simplest usages of function call: @@ -731,6 +776,8 @@ Unlike function calls and method calls, a constructor call `new Employee('John D The primary role of the constructor function is to initialize the object. +
+ ## Question 23. What would be the output of the following code? ```javascript @@ -742,7 +789,7 @@ var person = new User("xyz")["location"] = "USA"; console.log(person); ``` -### Answer +
Answer 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. @@ -763,9 +810,11 @@ foo["location"] = "USA"; ``` +
+ ## Question 24. What are Service Workers and when can you use them? -### Answer +
Answer It’s a technology that allows your web application to use cached resources first, and provide default experience offline, before getting more data from the network later. This principle is commonly known as Offline First. @@ -773,7 +822,12 @@ Service Workers actively use promises. A Service Worker has to be installed,acti As of 2017, Service Workers are not supported in IE and Safari. +
+ ## Question 25. What is the difference between a method and a function in javascript? + +
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 @@ -857,8 +911,11 @@ obj1.myMethod(); // will print "Hi there" following with obj1. ``` +
+ ## Question 26. What is IIFE (Immediately Invoked Function Expression) and how it can be useful? -### Answer +
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: @@ -923,8 +980,10 @@ Variables and functions that you declare inside an IIFE are not visible to the o code, it helps to prevent polluting the global scope and provide the module interface to the outside. +
+ ## Question 27. Describe Singleton Pattern In JavaScript -### Answer +
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. @@ -1027,9 +1086,11 @@ 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. +
+ ## Question 28. What are the ways of creating objects in JavaScript ? -### Answer +
Answer #### Method 1: Function based @@ -1095,12 +1156,14 @@ employee.getName = function(){ `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){ @@ -1133,8 +1196,12 @@ 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. +
Answer + > Suppose we have given an object `person` ```javascript @@ -1161,6 +1228,8 @@ 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. ```javascript @@ -1169,7 +1238,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){ @@ -1181,8 +1250,12 @@ function Clone(object){ } ``` +
+ ## Question 32. What are promises and how they are useful? +
Answer + We use promises for handling asynchronous interactions in a sequential manner. They are especially useful when we need to do an async operation and THEN do another async operation based on the results of the first one. For example, if you want to request the list of all flights and then for each flight you want to request some details about it. The promise represents the future value. It has an internal state (`pending`, `fulfilled` and `rejected`) and works like a state machine. A promise object has `then` method, where you can specify what to do when the promise is fulfilled or rejected. @@ -1196,8 +1269,12 @@ Also mention that you know about more sophisticated concepts: 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). +
+ ## 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 @@ -1233,7 +1310,12 @@ console.log(person.hasOwnProperty('name')); // print true console.log(person.hasOwnProperty('salary')); // print false ``` +
+ ## Question 34. What is NaN, why do we need it, and when can it break the page? + +
Answer + `NaN` stands for “not a number.” and it can break your table of numbers when it has an arithmetic operation that is not allowed. Here are some examples of how you can get `NaN`: ```javascript @@ -1255,6 +1337,8 @@ To check if the current value of the variable is NaN, you have to use the `isNaN 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 @@ -1265,6 +1349,8 @@ for (var i = 0; i < arr.length; i++) { }, 3000); } ``` +
Answer + For ES6, you can just replace `var i` with `let i`. For ES5, you need to create a function scope like here: @@ -1291,8 +1377,12 @@ arr.forEach(function(ele, i) { }) ``` +
+ ## Question 36. How to check if the value of a variable in an array? +
Answer + We always encounter in such situation where we need to know whether value is type of array or not. For instance : the code below perform some operation based value type @@ -1382,8 +1472,12 @@ function isArray(value) { } ``` +
+ ## 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 @@ -1424,8 +1518,12 @@ console.log(emp1 instanceof Employee); // true console.log(emp1 instanceof Object); // true ``` +
+ ## Question 38. How does Object.create method works JavaScript? +
Answer + The ECMAScript 5 **Object.create()** method is the easiest way for one object to inherit from another, without invoking a constructor function. **For instance:** @@ -1473,8 +1571,12 @@ In the example above, `emp1` is created with it's own value for name, so calling 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. 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. ```javascript @@ -1532,8 +1634,12 @@ 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 ?. +
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: @@ -1642,9 +1748,13 @@ delete employee.name; // fails silently unless it's in strict mode ``` -## Question 44. Write a log function which will add prefix `(your message)` to every message you log using console.log ? +
+ +## 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** +
Answer + Logging error message or some informative message is always required when you dealing with client side JavaScript using console.log method. Some time you want to add some prefix to identify message generated log from your application hence you would like to prefix your app name in every console.log. A general way to do this keep adding your app name in every console.log message like @@ -1667,7 +1777,9 @@ appLog("Some error message"); //output of above console: 'your app name Some error message' ``` -## Question 45 . Write a function which will test string as a literal and as an object ? +
+ +## Question 42 . Write a function which will test string as a literal and as an object ? For example: We can create string using string literal and using String constructor function. @@ -1677,6 +1789,9 @@ For example: We can create string using string literal and using String construc // using String constructor function var objStr = new String("Hi I am string object"); ``` + +
Answer + We can use typeof operator to test string literal and instanceof operator to test String object. ```javascript @@ -1689,7 +1804,11 @@ For example: We can create string using string literal and using String construc console.log(isString(ltrlStr)); // true console.log(isString(objStr)); // true ``` -## Question 46 . What is typical use case for anonymous function in JavaScript ? +
+ +## Question 43 . What is typical use case for anonymous function in JavaScript ? + +
Answer Anonymous functions basically used in following scenario. @@ -1752,7 +1871,11 @@ If your answer is yes then go and create named function rather anonymous functio 1. It can reduce a bit of code, particularly in recursive function and in callback function. 2. Avoid needless global namespace pollutions. -## Question 47 . How to set a default parameter value ? +
+ +## 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 : @@ -1832,7 +1955,9 @@ sentEmail({ }, 'Yahoo Mail'); ``` -## Question 48. Write code for merge two JavaScript Object dynamically. +
+ +## Question 45. Write code for merge two JavaScript Object dynamically. Let say you have two objects ```javascript @@ -1849,6 +1974,8 @@ var address = { ``` Write merge function which will take two object and add all the own property of second object into first object. +
Answer + ```javascript merge(person , address); @@ -1879,7 +2006,11 @@ function merge(toObj, fromObj) { } } ``` -## Question 49. What is non-enumerable property in JavaScript and how you can create one? +
+ +## Question 46. What is non-enumerable property in JavaScript and how you can create one? + +
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. @@ -1925,7 +2056,11 @@ person.phoneNo = '7777777777'; **Object.defineProperty()** also lets you create read-only properties as we saw above, we are not able to modify phoneNo value of a person object. This is because descriptor 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. -## Question 50. What is Function binding ? +
+ +## Question 47. What is Function binding ? + +
Answer Function binding falls in advance JavaScript category and this is very popular technique to use in conjunction with event handler and callback function to preserve code execution context while passing function as a parameter. @@ -1965,6 +2100,7 @@ btn.addEventListener('click', clickHandler.handleClick.bind(clickHandler)); `bind` method is available to all the function similar to call and apply method which take argument value of `this`. +
# Coding Questions @@ -1982,20 +2118,29 @@ strB="bye there!"; console.log (strA) ``` -The output will `'hi there'` because we're dealing with strings here. Strings are +
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? + +
+ +### 2. What would be the output of following code? ```javascript var objA = {prop1: 42}; var objB = objA; objB.prop1 = 90; console.log(objA) ``` -The output will `{prop1: 90}` because we're dealing with objects here. Objects are + +
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? +
+ +### 3. What would be the output of following code? ```javascript var objA = {prop1: 42}; @@ -2004,7 +2149,10 @@ objB = {}; console.log(objA) ``` -The output will `{prop1: 42}`. + +
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. @@ -2012,7 +2160,9 @@ 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? +
+ +### 4. What would be the output of following code? ```javascript var arrA = [0,1,2,3,4,5]; @@ -2021,13 +2171,18 @@ 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? +
+ +### 5. What would be the output of following code? ```javascript var arrA = [0,1,2,3,4,5]; var arrB = arrA.slice(); @@ -2035,12 +2190,17 @@ 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. -### 5. What would be the output of following code? +
+ +### 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]; @@ -2048,13 +2208,17 @@ 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]` +
-### 6. What would be the output of following code? +### 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]; @@ -2064,6 +2228,8 @@ 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, @@ -2088,6 +2254,7 @@ two elements. This is why changing the property of `arrB[0]` in `arrB` will also change the `arrA[0]`. +
## Hoisting @@ -2098,9 +2265,13 @@ This is why changing the property of `arrB[0]` in `arrB` will also change the `a 3. Type Error 4. ReferenceError: employeeId is not defined -Answer: 4) ReferenceError: employeeId is not defined +
Answer -### 2. What would be the output of following code? + 4) ReferenceError: employeeId is not defined + +
+ +### 2. What would be the output of following code? ```javascript console.log(employeeId); @@ -2112,7 +2283,11 @@ var employeeId = '19000'; 3. Type Error 4. ReferenceError: employeeId is not defined -Answer: 2) undefined +
Answer + + 2) undefined + +
### 3. What would be the output of following code? @@ -2129,7 +2304,11 @@ var employeeId = '1234abe'; 3. Type Error 4. ReferenceError: employeeId is not defined -Answer: 2) undefined +
Answer + + 2) undefined + +
### 4. What would be the output of following code? @@ -2149,7 +2328,11 @@ var employeeId = '1234abe'; 3. '1234abe' 4. ReferenceError: employeeId is not defined -Answer: 2) undefined +
Answer + + 2) undefined + +
### 5. What would be the output of following code? @@ -2167,7 +2350,11 @@ Answer: 2) undefined 3. 'Hi I am inside displayFunc' 4. ReferenceError: displayFunc is not defined -Answer: 1) undefined +
Answer + + 1) undefined + +
### 6. What would be the output of following code? @@ -2186,7 +2373,11 @@ console.log(employeeId); 3. 'abc123' 4. ReferenceError: employeeId is not defined -Answer: 2) '123bcd' +
Answer + + 2) '123bcd' + +
### 7. What would be the output of following code? @@ -2208,7 +2399,11 @@ console.log(employeeId); 3. 'abc123' 4. ReferenceError: employeeId is not defined -Answer: 3) 'abc123' +
Answer + + 3) 'abc123' + +
### 8. What would be the output of following code? @@ -2231,7 +2426,11 @@ foo(); 3. string 4. ReferenceError: employeeId is not defined -Answer: 2) 'function' +
Answer + + 2) 'function' + +
### 9. What would be the output of following code? @@ -2253,7 +2452,11 @@ foo(); 3. 'Car' 4. ReferenceError: product is not defined -Answer: 1) undefined +
Answer + + 1) undefined + +
### 10. What would be the output of following code? @@ -2277,7 +2480,11 @@ Answer: 1) undefined 3. function function 4. ReferenceError: bar is not defined -Answer: 3) function function +
Answer + + 3) function function + +
## Objects @@ -2306,7 +2513,11 @@ Answer: 3) function function 3. ["name", "salary", "country", "phoneNo"] 4. ["name", "salary", "country"] -Answer: 3) ["name", "salary", "country", "phoneNo"] +
Answer + + 3) ["name", "salary", "country", "phoneNo"] + +
### 2. What would be the output of following code ? @@ -2333,7 +2544,11 @@ Answer: 3) ["name", "salary", "country", "phoneNo"] 3. ["name", "salary", "country", "phoneNo"] 4. ["name", "salary", "country"] -Answer: 4) ["name", "salary", "country"] +
Answer + + 4) ["name", "salary", "country"] + +
### 3. What would be the output of following code ? @@ -2356,7 +2571,11 @@ Answer: 4) ["name", "salary", "country"] 3. true false 4. true true -Answer: 2) false false +
Answer + + 2) false false + +
### 4. What would be the output of following code ? @@ -2373,7 +2592,11 @@ Answer: 2) false false 3. true false 4. true true -Answer: 2) false false +
Answer + + 2) false false + +
### 5. What would be the output of following code ? @@ -2394,7 +2617,11 @@ Answer: 2) false false 3. true false 4. true true -Answer: 2) false false +
Answer + + 2) false false + +
### 6. What would be the output of following code ? @@ -2413,7 +2640,11 @@ Answer: 2) false false 3. true false 4. true true -Answer: 2) false false +
Answer + + 2) false false + +
### 7. What would be the output of following code ? @@ -2432,7 +2663,11 @@ Answer: 2) false false 3. true false 4. true true -Answer: 4) true true +
Answer + + 4) true true + +
### 8. What would be the output of following code ? @@ -2453,7 +2688,11 @@ Answer: 4) true true 3. true true true true 4. true true false false -Answer: 3) true true true true +
Answer + + 3) true true true true + +
### 9. What would be the output of following code ? @@ -2473,7 +2712,11 @@ Answer: 3) true true true true 3. foo foo 4. bar foo -Answer: 2) bar bar +
Answer + + 2) bar bar + +
### 10. What would be the output of following code ? @@ -2495,7 +2738,11 @@ Answer: 2) bar bar 3. foo foo 4. bar foo -Answer: 3) foo foo +
Answer + + 3) foo foo + +
### 11. What would be the output of following code ? @@ -2517,7 +2764,11 @@ Answer: 3) foo foo 3. foo foo 4. undefined bar -Answer: 2) undefined undefined +
Answer + + 2) undefined undefined + +
## Arrays @@ -2536,7 +2787,11 @@ Answer: 2) undefined undefined 3. ["100"] 1 4. ReferenceError: array is not defined -Answer: 3) ["100"] 1 +
Answer + + 3) ["100"] 1 + +
### 2. What would be the output of following code? @@ -2557,7 +2812,11 @@ Answer: 3) ["100"] 1 3. [] [] ['1',2,'3',4,5.6] 5 4. [] [] [Array[5]] 5 -Answer: 1) [] [] [Array[5]] 1 +
Answer + + 1) [] [] [Array[5]] 1 + +
### 3. What would be the output of following code? @@ -2575,7 +2834,11 @@ Answer: 1) [] [] [Array[5]] 1 3. 6 4. undefined -Answer: 1) 11 +
Answer + + 1) 11 + +
### 4. What would be the output of following code? @@ -2593,7 +2856,11 @@ Answer: 1) 11 3. 6 4. undefined -Answer: 3) 6 +
Answer + + 3) 6 + +
### 5. What would be the output of following code? @@ -2611,7 +2878,11 @@ Answer: 3) 6 3. Type Error 4. undefined -Answer: 1) [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ] +
Answer + + 1) [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ] + +
### 6. What would be the output of following code? @@ -2630,7 +2901,11 @@ Answer: 1) [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ] 3. 1 -1 -1 -1 4. 1 undefined -1 4 -Answer: 1) 1 -1 -1 4 +
Answer + + 1) 1 -1 -1 4 + +
### 7. What would be the output of following code? @@ -2648,7 +2923,11 @@ Answer: 1) 1 -1 -1 4 3. 1 1 -1 4. 1 undefined undefined -Answer: 2) 1 6 -1 +
Answer + + 2) 1 6 -1 + +
### 8. What would be the output of following code? @@ -2673,7 +2952,11 @@ Answer: 2) 1 6 -1 3. [ 2, 4, 8, 12, 16 ] true 4. [ 2, 4, 8, 12, 16 ] false -Answer: 3) [ 2, 4, 8, 12, 16 ] true +
Answer + + 3) [ 2, 4, 8, 12, 16 ] true + +
### 9. What would be the output of following code? @@ -2709,11 +2992,15 @@ Answer: 3) [ 2, 4, 8, 12, 16 ] true [ 2, '12', true,false] -Answer: 1) [ 2, '12', true ] +
Answer + + 1) [ 2, '12', true ] [ 2, '12', true ] [ 2, '12', true ] [ 2, '12', true ] +
+ ### 10. What would be the output of following code? ```javascript @@ -2748,12 +3035,16 @@ Answer: 1) [ 2, '12', true ] [] [ 'foo', 'bar', 'john', 'ritz' ] -Answer: 1) [ '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 @@ -2770,7 +3061,11 @@ Answer: 1) [ 'bar', 'john', 'ritz' ] 3. [ 'bar', 'john' ] [ 'bar', 'john' ] [ 'bar', 'john' ] 4. [ 'bar', 'john' ] [] [] -Answer: 1. [ 'bar', 'john' ] [] [ 'foo' ] +
Answer + + 1. [ 'bar', 'john' ] [] [ 'foo' ] + +
### 12. What would be the output of following code? @@ -2787,7 +3082,11 @@ Answer: 1. [ 'bar', 'john' ] [] [ 'foo' ] 3. [ 15, 16, 2, 23, 42, 8 ] 4. [ 2, 8, 15, 16, 23, 42 ] -Answer: 3. [ 15, 16, 2, 23, 42, 8 ] +
Answer + + 3. [ 15, 16, 2, 23, 42, 8 ] + +
## Functions @@ -2814,7 +3113,11 @@ console.log(funcA()); 3. Type Error 4. ReferenceError: this is not defined -Answer: 1) +
Answer + + 1) + +
### 2. What would be the output of following code ? @@ -2834,7 +3137,11 @@ console.log(obj.innerMessage); 3. Type Error 4. undefined true -Answer: 4) undefined true +
Answer + + 4) undefined true + +
### 3. What would be the output of following code ? @@ -2854,7 +3161,11 @@ console.log(obj.innerMessage()); 3. Type Error 4. ReferenceError: this.message is not defined -Answer: 1) Hello +
Answer + + 1) Hello + +
### 4. What would be the output of following code ? @@ -2875,8 +3186,12 @@ console.log(obj.innerMessage()); 3. undefined 4. ReferenceError: this.message is not defined -Answer: 3) undefined +
Answer + + 3) undefined +
+ ### 5. What would be the output of following code ? ```javascript @@ -2897,7 +3212,11 @@ console.log(obj.innerMessage()); 3. undefined 4. ReferenceError: self.message is not defined -Answer: 2) 'Hello' +
Answer + + 2) 'Hello' + +
### 6. What would be the output of following code ? @@ -2915,7 +3234,11 @@ console.log(myFunc()); 3. undefined 4. ReferenceError: this.message is not defined -Answer: 3) undefined +
Answer + + 3) undefined + +
### 7. What would be the output of following code ? @@ -2933,7 +3256,11 @@ console.log(myFunc()); 3. undefined 4. ReferenceError: this.message is not defined -Answer: 2) 'Hi John' +
Answer + + 2) 'Hi John' + +
### 8. What would be the output of following code ? @@ -2950,7 +3277,11 @@ console.log(myFunc()); 3. undefined 4. ReferenceError: this.message is not defined -Answer: 2) 'Hi John' +
Answer + + 2) 'Hi John' + +
### 9. What would be the output of following code ? @@ -2968,7 +3299,11 @@ console.log(myFunc("a","b","c","d")); 3. undefined 4. ReferenceError -Answer: a) 2 2 2 +
Answer + + a) 2 2 2 + +
### 10. What would be the output of following code ? @@ -2986,7 +3321,11 @@ console.log(myFunc("a","b","c","d")); 3. undefined 4. ReferenceError -Answer: 2) 0 2 4 +
Answer + + 2) 0 2 4 + +
## Object Oriented @@ -3016,7 +3355,11 @@ var person1 = new Person('John'); 3. John undefined 4. John John -Answer: 1) John Person +
Answer + + 1) John Person + +
## Scopes @@ -3041,7 +3384,11 @@ console.log(userInfo.userName); 3. 12345678 undefined 4. undefined undefined -Answer: 3) 12345678 undefined +
Answer + + 3) 12345678 undefined + +
### 2. What would be the output of following code ? @@ -3058,7 +3405,11 @@ console.log(Employee.employeeId); 3. bq1uy 4. undefined -Answer: 4) undefined +
Answer + + 4) undefined + +
### 3. What would be the output of following code ? @@ -3080,7 +3431,11 @@ console.log(new Employee().employeeId); 3. bq1uy 1BJKSJ kj182 4. undefined 1BJKSJ kj182 -Answer: 2) bq1uy 1BJKSJ bq1uy +
Answer + + 2) bq1uy 1BJKSJ bq1uy + +
### 4. What would be the output of following code ? @@ -3101,7 +3456,11 @@ var employeeId = 'aq123'; 3. aq123 aq123 4. foo123 undefined -Answer: 1) foo123 aq123 +
Answer + + 1) foo123 aq123 + +
## Call, Apply, Bind @@ -3122,7 +3481,11 @@ Answer: 1) foo123 aq123 3. World 4. [ 'W', 'o', 'r', 'l', 'd' ] -Answer: 4) [ 'W', 'o', 'r', 'l', 'd' ] +
Answer + + 4) [ 'W', 'o', 'r', 'l', 'd' ] + +
### 2. What would be the output of following code ? @@ -3153,7 +3516,11 @@ Answer: 4) [ 'W', 'o', 'r', 'l', 'd' ] 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 +
Answer + + 1) Total amount left in account: 5600 Total amount left in account: 5300 + +
### 3. What would be the output of following code ? @@ -3185,7 +3552,11 @@ Answer: 1) Total amount left in account: 5600 Total amount left in account: 5300 3. 5600 3300 5100 4. undefined undefined undefined -Answer: 1) 5600 5300 5100 +
Answer + + 1) 5600 5300 5100 + +
### 4. What would be the output of following code ? @@ -3217,7 +3588,11 @@ Answer: 1) 5600 5300 5100 3. 5600 3300 5100 4. undefined undefined undefined -Answer: 2) 3600 3300 3100 +
Answer + + 2) 3600 3300 3100 + +
### 5. What would be the output of following code ? @@ -3234,7 +3609,11 @@ Answer: 2) 3600 3300 3100 3. Window 4. undefined -Answer: 1) Hello John +
Answer + + 1) Hello John + +
### 6. Suggest your question! @@ -3264,7 +3643,11 @@ getDataFromServer('www.google.com').then(function(name){ 3. Reference Error 4. fn is not defined -Answer: 1) John +
Answer + + 1) John + +
### 2. What would be the output of following code ? @@ -3308,9 +3691,13 @@ Answer: 1) John [42, 23, 16, 15, 8, 2] 4. Reference Error -Answer: 1) [ 2, 8, 15, 16, 23, 42 ] +
Answer + + 1) [ 2, 8, 15, 16, 23, 42 ] [ 2, 8, 15, 16, 23, 42 ] [ 2, 8, 15, 16, 23, 42 ] + +
## Return Statement @@ -3334,7 +3721,11 @@ Answer: 1) [ 2, 8, 15, 16, 23, 42 ] 3. Reference Error 4. Uncaught TypeError: Cannot read property 'fullName' of undefined -Answer: 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 ? @@ -3352,7 +3743,11 @@ console.log(numb); 3. 2 4. (2,4,5) -Answer: 1) 5 +
Answer + + 1) 5 + +
### 3. What would be the output of following code ? @@ -3370,7 +3765,11 @@ console.log(numb); 3. "" 4. 0 -Answer: 2) undefined +
Answer + + 2) undefined + +
### 4**. What would be the output of following code ? @@ -3392,7 +3791,11 @@ console.log(mul(2)(3)[1](4)); 3. Reference Error 4. 10, 6 -Answer: 1) 6, 10 +
Answer + + 1) 6, 10 + +
### 5**. What would be the output of following code ? @@ -3416,7 +3819,11 @@ console.log(mul(2)(3).sum(4)); 3. Reference Error 4. 10, 6 -Answer: 1) 6, 10 +
Answer + + 1) 6, 10 + +
### 6. What would be the output of following code ? @@ -3440,7 +3847,11 @@ console.log(mul(2)(3)(4)(5)(6)); 3. Reference Error 4. Type Error -Answer: 1) 720 +
Answer + + 1) 720 + +
### 7. What would be the output of following code ? @@ -3467,7 +3878,9 @@ personObj.getName2(); 3. undefined Tony 4. Tony Tony -Answer: 2) Tony undefined +
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: @@ -3490,6 +3903,7 @@ Object.prototype.name="Steve"; personObj.getName2(); ``` +
## Contributing From 93751de0c0d41dcf3fc38c3e742419317cced0b9 Mon Sep 17 00:00:00 2001 From: AlexTaietti Date: Sun, 16 Aug 2020 02:40:08 +0100 Subject: [PATCH 106/112] corrected some typos --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 5a4ba4d..3f3f3b4 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ var x; // declaring x 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 (what we are doing is called "initialisation"), Here declaration and assignment of value happen inline for variable x, In JavaScript both variable declarations and function declarations go to the top of the scope in which they are declared, then assignment happens—this series of events is called `hoisting`. A variable can be declared but not defined. When we try to access it, It will result `undefined`. @@ -644,7 +644,7 @@ The `typeof` operator checks if a value belongs to one of the seven basic types: `typeof(null)` will return `object`. -`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. It `instanceof` operator checks the current object and returns true if the object is of the specified type, 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(); @@ -674,11 +674,11 @@ counterArray["C"] = 1; ```
Answer -First of all, in case of JavaScript an associative array is the same as an object. Secondly, even though is no built-in function or property available to calculate the length/size an object, we can write such function ourselves. +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. #### 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 3 From b32e23ec3b80f94764b0e80a486ab6e1f11fa649 Mon Sep 17 00:00:00 2001 From: AlexTaietti Date: Sat, 22 Aug 2020 21:17:49 +0100 Subject: [PATCH 107/112] corrected typos and rephrased some sentences --- README.md | 77 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 41 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 3f3f3b4..b8b329b 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,12 @@ # 123-JavaScript-Interview-Questions -It's a book about frontend interview question. We hope that it will help all javascript developers to prepare for a technical job interview. +This book's goal is to help javascript frontend developers prepare for technical job interviews through a collection of carefully compiled questions. ## Want to buy a book in paper form? Want some badass flashcards? - - This Book will be soon completed and then it will be available to buy in a paper form. If you want me to sent an early copy of this book, please add your name and email address in google form here [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 the interviewers printed on beautiful poker-size flashcards. + - 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 @@ -17,14 +17,14 @@ In JavaScript if you try to use a variable that doesn't exist and has not been d 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 for 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 ``` -`var x = 1` is both declaration and definition (what we are doing is called "initialisation"), Here declaration and assignment of value happen inline for variable x, 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`. +`var x = 1` is both declaration and definition, here declaration and assignment of value happen inline for variable x—what we are doing is called "initialisation". In JavaScript both variable declarations and function declarations go to the top of the scope in which they are declared, then assignment happens—this series of events is called "hoisting". A variable can be declared but not defined. When we try to access it, It will result `undefined`. @@ -48,7 +48,7 @@ console.log(y); // Output: ReferenceError: y is not defined ```javascript -// if( x <= 100 ) {...} +if( x <= 100 ) {...} if( !(x > 100) ) {...} ```
Answer @@ -56,9 +56,9 @@ if( !(x > 100) ) {...} `NaN <= 100` is `false` and `NaN > 100` is also `false`, so if the value of `x` is `NaN`, the statements are not the same. -The same holds true for any value of x that being converted to Number, returns NaN, e.g.: `undefined`, `[1,2,5]`, `{a:22}` , etc. +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. -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 `isNaN()` function. +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.
@@ -66,7 +66,7 @@ This is why you need to pay attention when you deal with numeric variables. `NaN
Answer -One of the drawback 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. Let's see it on example: +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) { @@ -80,7 +80,7 @@ var Employee = function (name, company, salary) { }; }; -// we can also create method in Employee's prototype: +// Alternatively we can add the method to Employee's prototype: Employee.prototype.formatSalary2 = function() { return "$ " + this.salary; } @@ -91,7 +91,7 @@ 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 `formatSalary` method. However the `formatSalary2` will only be added once to an object `Employee.prototype`. +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`.
@@ -99,39 +99,45 @@ Here each instance variable `emp1`, `emp2`, `emp3` has own copy of `formatSalary
Answer -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 the variables in three scopes: -The closure has access to the variable in three scopes: - Variable declared in his own scope -- Variable declared in parent function 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 the function as closure has access to the 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 @@ -151,8 +157,6 @@ console.log(mul(4)(3)(4)); // output : 48 ```
Answer -Below is the code followed by the explanation of how it works: - ```javascript function mul (x) { return function (y) { // anonymous function @@ -163,14 +167,15 @@ function mul (x) { } ``` -Here the `mul` function accepts the first argument and returns the anonymous function which takes the second parameter and returns the anonymous function which takes the third parameter and returns the 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 the function as well and passed as an 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 -- A function can be stored as variable -- A function can be pass as a parameter to another function -- A function can be returned from another 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
From a14c83391324e6030e3e8ac5f64593e75250a7bc Mon Sep 17 00:00:00 2001 From: Kamlesh Pandey <47499656+KamleshPandey98@users.noreply.github.com> Date: Thu, 1 Oct 2020 20:03:56 +0530 Subject: [PATCH 108/112] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b8b329b..824b2b1 100644 --- a/README.md +++ b/README.md @@ -3776,7 +3776,7 @@ console.log(numb);
-### 4**. What would be the output of following code ? +### 4. What would be the output of following code ? ```javascript function mul(x){ @@ -3802,7 +3802,7 @@ console.log(mul(2)(3)[1](4));
-### 5**. What would be the output of following code ? +### 5. What would be the output of following code ? ```javascript function mul(x) { From 0f3706c1b447b7f012145718d4a259b885bfef89 Mon Sep 17 00:00:00 2001 From: pranav247sw Date: Mon, 26 Apr 2021 11:49:14 +0530 Subject: [PATCH 109/112] Typp/Grammar checks and corrections --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b8b329b..df5e30f 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ A closure is a function defined inside another function (called parent function) The closure has access to the variables in three scopes: -- Variable declared in his own scope +- Variable declared in its own scope - Variable declared in its parent function's scope - Variable declared in the global namespace @@ -333,7 +333,7 @@ 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 **local variable**. `delete` operator doesn't affect local variables. +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.
From dd5e263b75e971019c8585ea6e2fbe72e9ce254f Mon Sep 17 00:00:00 2001 From: kalon1997 Date: Thu, 12 May 2022 12:21:33 +0530 Subject: [PATCH 110/112] added 48th ques about callbackhell promise async/await --- README.md | 130 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) diff --git a/README.md b/README.md index fdae8f6..a83a053 100644 --- a/README.md +++ b/README.md @@ -2107,6 +2107,136 @@ btn.addEventListener('click', clickHandler.handleClick.bind(clickHandler)); +### 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 From fd7a01788d0c33f58ec296e622ae653fb4a45dc6 Mon Sep 17 00:00:00 2001 From: Akhil24-abd Date: Mon, 17 Oct 2022 23:39:22 +0530 Subject: [PATCH 111/112] Questions added --- README.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/README.md b/README.md index fdae8f6..a4fc97a 100644 --- a/README.md +++ b/README.md @@ -3910,6 +3910,41 @@ personObj.getName2(); +### 8 . What would be the output of the following code ? +```javascript +let a = true; +let c = 0; + +setTimeout(() => { + a = false; +},2000) + +while(a){ + console.log('Hello') +} +``` +
Answer +The above program will print Hello infinitely. Since, Javascript is a single threaded language the actual execution happens only on the main thread. So, setTimeout will wailt for 2000 milliseconds on a seperate thread as while loop has occupied the main thread. The exit condition for the loop is to set the variable a as fasle. But as the loop continously running on the main thread , it a cannot be set false. +
+ +### 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) +``` + +
Answer +The above program will print 0 to 9 sequentially. +
+ ## Contributing 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. From 3bb40311689916c371d8a4fba35cfc13c093b774 Mon Sep 17 00:00:00 2001 From: sumeyra davran Date: Sat, 25 Nov 2023 11:37:44 +0300 Subject: [PATCH 112/112] update the answer --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a4fc97a..42c4b1f 100644 --- a/README.md +++ b/README.md @@ -3120,7 +3120,9 @@ console.log(funcA());
Answer - 1) + 1) funcA Window {...} + innerFunc1 Window {...} + innerFunA11 Window {...}