From 93751de0c0d41dcf3fc38c3e742419317cced0b9 Mon Sep 17 00:00:00 2001 From: AlexTaietti Date: Sun, 16 Aug 2020 02:40:08 +0100 Subject: [PATCH 1/7] 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 2/7] 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 3/7] 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 4/7] 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 5/7] 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 6/7] 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 7/7] 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 {...}