├── .gitignore
├── LICENSE
├── ML_Project_Time_Series(V2).ipynb
├── ML_Project_Time_Series.ipynb
├── README.md
└── coverPage.png
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | Tricky-Question.js
3 | node_modules
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | BSD 3-Clause License
2 |
3 | Copyright (c) 2017, Nishant Kumar
4 | All rights reserved.
5 |
6 | Redistribution and use in source and binary forms, with or without
7 | modification, are permitted provided that the following conditions are met:
8 |
9 | * Redistributions of source code must retain the above copyright notice, this
10 | list of conditions and the following disclaimer.
11 |
12 | * Redistributions in binary form must reproduce the above copyright notice,
13 | this list of conditions and the following disclaimer in the documentation
14 | and/or other materials provided with the distribution.
15 |
16 | * Neither the name of the copyright holder nor the names of its
17 | contributors may be used to endorse or promote products derived from
18 | this software without specific prior written permission.
19 |
20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # 123-JavaScript-Interview-Questions
4 |
5 | This book's goal is to help javascript frontend developers prepare for technical job interviews through a collection of carefully compiled questions.
6 |
7 | ## Want to buy a book in paper form? Want some badass flashcards?
8 |
9 | - 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).
10 | - 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.
11 |
12 | ## Question 1. What's the difference between `undefined` and `not defined` in JavaScript
13 |
14 | Answer
15 |
16 | 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`.
17 |
18 | Before starting further discussion let's understand the difference between declaration and definition.
19 |
20 | `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.
21 |
22 | ```javascript
23 | var x; // declaring x
24 | console.log(x); // output: undefined
25 | ```
26 |
27 | `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".
28 |
29 | A variable can be declared but not defined. When we try to access it, It will result `undefined`.
30 |
31 | ```javascript
32 | var x; // Declaration
33 | typeof x === 'undefined'; // Will return true
34 | ```
35 |
36 | A variable can be neither declared nor defined. When we try to reference such variable then the result will be `not defined`.
37 |
38 | ```javascript
39 | console.log(y); // Output: ReferenceError: y is not defined
40 | ```
41 |
42 | ### Ref Link:
43 | [http://stackoverflow.com/questions/20822022/javascript-variable-definition-declaration](http://stackoverflow.com/questions/20822022/javascript-variable-definition-declaration)
44 |
45 |
46 |
47 | ## Question 2. For which value of `x` the results of the following statements are not the same?
48 |
49 |
50 | ```javascript
51 | if( x <= 100 ) {...}
52 | if( !(x > 100) ) {...}
53 | ```
54 | Answer
55 |
56 | `NaN <= 100` is `false` and `NaN > 100` is also `false`, so if the
57 | value of `x` is `NaN`, the statements are not the same.
58 |
59 | 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.
60 |
61 | 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.
62 |
63 |
64 |
65 | ## Question 3. What is the drawback of declaring methods directly in JavaScript objects?
66 |
67 | Answer
68 |
69 | 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:
70 |
71 | ```javascript
72 | var Employee = function (name, company, salary) {
73 | this.name = name || "";
74 | this.company = company || "";
75 | this.salary = salary || 5000;
76 |
77 | // We can create a method like this:
78 | this.formatSalary = function () {
79 | return "$ " + this.salary;
80 | };
81 | };
82 |
83 | // Alternatively we can add the method to Employee's prototype:
84 | Employee.prototype.formatSalary2 = function() {
85 | return "$ " + this.salary;
86 | }
87 |
88 | //creating objects
89 | var emp1 = new Employee('Yuri Garagin', 'Company 1', 1000000);
90 | var emp2 = new Employee('Dinesh Gupta', 'Company 2', 1039999);
91 | var emp3 = new Employee('Erich Fromm', 'Company 3', 1299483);
92 | ```
93 |
94 | 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`.
95 |
96 |
97 |
98 | ## Question 4. What is “closure” in javascript? Can you provide an example?
99 |
100 | Answer
101 |
102 | 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.
103 |
104 | The closure has access to the variables in three scopes:
105 |
106 | - Variable declared in its own scope
107 | - Variable declared in its parent function's scope
108 | - Variable declared in the global namespace
109 |
110 | ```javascript
111 | var globalVar = "abc"; //Global variable
112 |
113 | // Parent self-invoking function
114 | (function outerFunction (outerArg) { // start of outerFunction's scope
115 |
116 | var outerFuncVar = 'x'; // Variable declared in outerFunction's function scope
117 |
118 | // Closure self-invoking function
119 | (function innerFunction (innerArg) { // start of innerFunction's scope
120 |
121 | var innerFuncVar = "y"; // variable declared in innerFunction's function scope
122 | console.log(
123 | "outerArg = " + outerArg + "\n" +
124 | "outerFuncVar = " + outerFuncVar + "\n" +
125 | "innerArg = " + innerArg + "\n" +
126 | "innerFuncVar = " + innerFuncVar + "\n" +
127 | "globalVar = " + globalVar);
128 |
129 | // end of innerFunction's scope
130 |
131 | })(5); // Pass 5 as parameter to our Closure
132 |
133 | // end of outerFunction's scope
134 |
135 | })(7); // Pass 7 as parameter to the Parent function
136 | ```
137 |
138 | `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.
139 |
140 | The output of the code above would be:
141 |
142 | ```javascript
143 | outerArg = 7
144 | outerFuncVar = x
145 | innerArg = 5
146 | innerFuncVar = y
147 | globalVar = abc
148 | ```
149 |
150 |
151 |
152 | ## Question 5. Write a mul function which will work properly when invoked with following syntax.
153 |
154 | ```javascript
155 | console.log(mul(2)(3)(4)); // output : 24
156 | console.log(mul(4)(3)(4)); // output : 48
157 | ```
158 | Answer
159 |
160 | ```javascript
161 | function mul (x) {
162 | return function (y) { // anonymous function
163 | return function (z) { // anonymous function
164 | return x * y * z;
165 | };
166 | };
167 | }
168 | ```
169 |
170 | 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.
171 |
172 | 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.
173 |
174 | - A function is an instance of the Object type
175 | - A function can have properties and has a link to its constructor method
176 | - A function can be stored as a variable
177 | - A function can be passed as a parameter to another function
178 | - A function can be returned by another function
179 |
180 |
181 |
182 | ## Question 6. How to empty an array in JavaScript?
183 | For instance:
184 |
185 | ```javascript
186 | var arrayList = ['a', 'b', 'c', 'd', 'e', 'f'];
187 | ```
188 |
189 | How can we empty the array above?
190 |
191 | Answer
192 |
193 | 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.
194 |
195 | #### Method 1
196 |
197 | ```javascript
198 | arrayList = [];
199 | ```
200 |
201 | 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`.
202 |
203 | For instance:
204 |
205 | ```javascript
206 | var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
207 | var anotherArrayList = arrayList; // Referenced arrayList by another variable
208 | arrayList = []; // Empty the array
209 | console.log(anotherArrayList); // Output ['a', 'b', 'c', 'd', 'e', 'f']
210 | ```
211 |
212 | #### Method 2
213 |
214 | ```javascript
215 | arrayList.length = 0;
216 | ```
217 |
218 | 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.
219 |
220 | For instance:
221 |
222 | ```javascript
223 | var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
224 | var anotherArrayList = arrayList; // Referenced arrayList by another variable
225 | arrayList.length = 0; // Empty the array by setting length to 0
226 | console.log(anotherArrayList); // Output []
227 | ```
228 |
229 | #### Method 3
230 |
231 | ```javascript
232 | arrayList.splice(0, arrayList.length);
233 | ```
234 |
235 | Above implementation will also work perfectly. This way of empty the array will also update all the references of the original array.
236 |
237 | ```javascript
238 | var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
239 | var anotherArrayList = arrayList; // Referenced arrayList by another variable
240 | arrayList.splice(0, arrayList.length); // Empty the array by setting length to 0
241 | console.log(anotherArrayList); // Output []
242 | ```
243 |
244 | #### Method 4
245 |
246 | ```javascript
247 | while(arrayList.length) {
248 | arrayList.pop();
249 | }
250 | ```
251 |
252 | Above implementation can also empty the array. But not recommended to use often.
253 |
254 |
255 |
256 |
257 | ## Question 7. How to check if an object is an array or not?
258 |
259 | Answer
260 |
261 | The best way to find whether an object is instance of a particular class or not using `toString` method from `Object.prototype`
262 |
263 | ```javascript
264 | var arrayList = [1 , 2, 3];
265 | ```
266 |
267 | 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?
268 |
269 | ```javascript
270 | function greet(param) {
271 | if() {
272 | // here have to check whether param is array or not
273 | }
274 | else {
275 | }
276 | }
277 | ```
278 |
279 | 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.
280 |
281 | ```javascript
282 | function greet(param) {
283 | if(typeof param === 'string') {
284 | }
285 | else {
286 | // If param is of type array then this block of code would execute
287 | }
288 | }
289 | ```
290 |
291 | 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.
292 |
293 | Coming back to checking the type of an object, As we mentioned that we can use `Object.prototype.toString`
294 |
295 | ```javascript
296 | if(Object.prototype.toString.call(arrayList) === '[object Array]') {
297 | console.log('Array!');
298 | }
299 | ```
300 |
301 | If you are using `jQuery` then you can also used jQuery `isArray` method:
302 |
303 | ```javascript
304 | if($.isArray(arrayList)) {
305 | console.log('Array');
306 | } else {
307 | console.log('Not an array');
308 | }
309 | ```
310 |
311 | FYI jQuery uses `Object.prototype.toString.call` internally to check whether an object is an array or not.
312 |
313 | In modern browser, you can also use:
314 |
315 | ```javascript
316 | Array.isArray(arrayList);
317 | ```
318 |
319 | `Array.isArray` is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5
320 |
321 |
322 |
323 |
324 | ## Question 8. What will be the output of the following code?
325 |
326 | ```javascript
327 | var output = (function(x) {
328 | delete x;
329 | return x;
330 | })(0);
331 |
332 | console.log(output);
333 | ```
334 | Answer
335 |
336 | 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.
337 |
338 |
339 |
340 |
341 | ## Question 9. What will be the output of the following code?
342 |
343 | ```javascript
344 | var x = 1;
345 | var output = (function() {
346 | delete x;
347 | return x;
348 | })();
349 |
350 | console.log(output);
351 | ```
352 | Answer
353 |
354 | 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`.
355 |
356 |
357 |
358 |
359 | ## Question 10. What will be the output of the following code?
360 |
361 | ```javascript
362 | var x = { foo : 1};
363 | var output = (function() {
364 | delete x.foo;
365 | return x.foo;
366 | })();
367 |
368 | console.log(output);
369 | ```
370 | Answer
371 |
372 | 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`.
373 |
374 |
375 |
376 |
377 | ## Question 11. What will be the output of the following code?
378 |
379 | ```javascript
380 | var Employee = {
381 | company: 'xyz'
382 | }
383 | var emp1 = Object.create(Employee);
384 | delete emp1.company
385 | console.log(emp1.company);
386 | ```
387 |
388 | Answer
389 | The code above will output `xyz` as output. Here `emp1` object got company as **prototype** property. delete operator doesn't delete prototype property.
390 |
391 | `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`.
392 |
393 |
394 |
395 |
396 | ## Question 12. What is `undefined x 1` in JavaScript
397 |
398 | ```javascript
399 | var trees = ["redwood", "bay", "cedar", "oak", "maple"];
400 | delete trees[3];
401 | ```
402 |
403 | Answer
404 | - 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"]`.
405 | - In the recent versions of Chrome you will see the word `empty` of `undefined x 1`.
406 | - When you run the same code in Firefox browser console then you will get `["redwood", "bay", "cedar", undefined, "maple"]`
407 |
408 | 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`.
409 |
410 | **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.
411 |
412 |
413 |
414 |
415 |
416 | ## Question 13. What will be the output of the following code?
417 |
418 | ```javascript
419 | var trees = ["xyz", "xxxx", "test", "ryan", "apple"];
420 | delete trees[3];
421 | console.log(trees.length);
422 | ```
423 | Answer
424 | 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.
425 |
426 | 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"]`.
427 |
428 |
429 |
430 |
431 |
432 | ## Question 14. What will be the output of the following code?
433 |
434 | ```javascript
435 | var bar = true;
436 | console.log(bar + 0);
437 | console.log(bar + "xyz");
438 | console.log(bar + true);
439 | console.log(bar + false);
440 | ```
441 | Answer
442 |
443 | The code above will output `1, "truexyz", 2, 1` as output. Here's a general guideline for the plus operator:
444 | - Number + Number -> Addition
445 | - Boolean + Number -> Addition
446 | - Boolean + Boolean -> Addition
447 | - Number + String -> Concatenation
448 | - String + Boolean -> Concatenation
449 | - String + String -> Concatenation
450 |
451 |
452 |
453 |
454 |
455 | ## Question 15. What will be the output of the following code?
456 |
457 | ```javascript
458 | var z = 1, y = z = typeof y;
459 | console.log(y);
460 | ```
461 | Answer
462 |
463 | 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:
464 |
465 | ```javascript
466 | var z;
467 | z = 1;
468 | var y;
469 | z = typeof y;
470 | y = z;
471 | ```
472 |
473 |
474 |
475 | ## Question 16. What will be the output of the following code?
476 |
477 | ```javascript
478 | // NFE (Named Function Expression)
479 | var foo = function bar() { return 12; };
480 | typeof bar();
481 | ```
482 |
483 | Answer
484 |
485 | The output will be `Reference Error`. To fix the bug we can try to rewrite the code a little bit:
486 |
487 | **Sample 1**
488 |
489 | ```javascript
490 | var bar = function() { return 12; };
491 | typeof bar();
492 | ```
493 |
494 | or
495 |
496 | **Sample 2**
497 |
498 | ```javascript
499 | function bar() { return 12; };
500 | typeof bar();
501 | ```
502 |
503 | The function definition can have only one reference variable as a function name, In **sample 1** `bar` is reference variable which is pointing to `anonymous function` and in **sample 2** we have function statement and `bar` is the function name.
504 |
505 | ```javascript
506 | var foo = function bar() {
507 | // foo is visible here
508 | // bar is visible here
509 | console.log(typeof bar()); // Works here :)
510 | };
511 | // foo is visible here
512 | // bar is undefined here
513 | ```
514 |
515 |
516 |
517 | ## Question 17a. What is the difference between declaring a function in the formats listed below?
518 |
519 | ```javascript
520 | var foo = function() {
521 | // Some code
522 | }
523 | ```
524 |
525 | ```javascript
526 | function bar () {
527 | // Some code
528 | }
529 | ```
530 | Answer
531 |
532 | 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 :
533 |
534 | ```javascript
535 | // Run-Time function declaration
536 | foo(); // Call foo function here, It will give an error
537 | var foo = function() {
538 | console.log("Hi I am inside Foo");
539 | };
540 | ```
541 |
542 | ```javascript
543 | // Parse-Time function declaration
544 | bar(); // Call bar function here, It will not give an Error
545 | function bar() {
546 | console.log("Hi I am inside Foo");
547 | }
548 | ```
549 |
550 |
551 | ## Question 17b. What is the output of the following?
552 |
553 | ```javascript
554 | bar();
555 | (function abc(){console.log('something')})();
556 | function bar(){console.log('bar got called')};
557 | ```
558 | Answer
559 |
560 | The output will be :
561 | ```
562 | bar got called
563 | something
564 | ```
565 | 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.
566 |
567 |
568 |
569 | ## Question 18. In which case the function definition is not hoisted in JavaScript?
570 |
571 | Answer
572 |
573 | Let's take the following **function expression**
574 |
575 | ```javascript
576 | var foo = function foo() {
577 | return 12;
578 | }
579 | ```
580 |
581 | 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:
582 |
583 | ```javascript
584 | foo(); // Here foo is still undefined
585 | var foo = function foo() {
586 | return 12;
587 | };
588 | ```
589 |
590 | The code above behind the scene look something like this:
591 |
592 | ```javascript
593 | var foo = undefined;
594 | foo(); // Here foo is undefined
595 | foo = function foo() {
596 | // Some code stuff
597 | }
598 | ```
599 |
600 | ```javascript
601 | var foo = undefined;
602 | foo = function foo() {
603 | // Some code stuff
604 | }
605 | foo(); // Now foo is defined here
606 | ```
607 |
608 |
609 |
610 | ## Question 19. What will be the output of the following code?
611 |
612 | ```javascript
613 | var salary = "1000$";
614 |
615 | (function () {
616 | console.log("Original salary was " + salary);
617 |
618 | var salary = "5000$";
619 |
620 | console.log("My New Salary " + salary);
621 | })();
622 | ```
623 | Answer
624 |
625 | 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.
626 |
627 | ```javascript
628 | var salary = "1000$";
629 |
630 | (function () {
631 | var salary = undefined;
632 | console.log("Original salary was " + salary);
633 |
634 | salary = "5000$";
635 |
636 | console.log("My New Salary " + salary);
637 | })();
638 | ```
639 |
640 |
641 |
642 | ## Question 20. What’s the difference between `typeof` and `instanceof`?
643 |
644 | Answer
645 |
646 | `typeof` is an operator that returns a string with the type of whatever you pass.
647 |
648 | The `typeof` operator checks if a value belongs to one of the seven basic types: `number`, `string`, `boolean`, `object`, `function`, `undefined` or `Symbol`.
649 |
650 | `typeof(null)` will return `object`.
651 |
652 | `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:
653 |
654 | ```javascript
655 | var dog = new Animal();
656 | dog instanceof Animal; // Output : true
657 | ```
658 |
659 | Here `dog instanceof Animal` is true since `dog` inherits from `Animal.prototype`
660 |
661 | ```javascript
662 | var name = new String("xyz");
663 | name instanceof String; // Output : true
664 | ```
665 |
666 |
667 | 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)
668 |
669 |
670 |
671 | ## Question 21. Calculate the length of the associative array
672 |
673 | ```javascript
674 | var counterArray = {
675 | A : 3,
676 | B : 4
677 | };
678 | counterArray["C"] = 1;
679 | ```
680 | Answer
681 |
682 | 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.
683 |
684 | #### Method 1
685 |
686 | `Object` has `keys` method which can be used to calculate the length of object.
687 |
688 | ```javascript
689 | Object.keys(counterArray).length; // Output 3
690 | ```
691 |
692 | #### Method 2
693 |
694 | We can also calculate the length of object by iterating through the object and by doing a count of own property of object. This way we will ignoge the properties that came from the object's prototype chain:
695 |
696 | ```javascript
697 | function getLength(object) {
698 | var count = 0;
699 | for(key in object) {
700 | // hasOwnProperty method check own property of object
701 | if(object.hasOwnProperty(key)) count++;
702 | }
703 | return count;
704 | }
705 | ```
706 |
707 | #### Method 3
708 |
709 | All modern browsers (including IE9+) support the [`getOwnPropertyNames`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames) method, so we can calculate the length using the following code:
710 |
711 | ```javascript
712 | Object.getOwnPropertyNames(counterArray).length; // Output 3
713 | ```
714 |
715 | #### Method 4
716 |
717 | [Underscore](https://underscorejs.org/#size) and [lodash](https://lodash.com/docs/4.17.10#size) libraries have the method `size` dedicated to calculate the object length. We don't recommend to include one of these libraries just to use the `size` method, but if it's already used in your project - why not?
718 |
719 | ```javascript
720 | _.size({one: 1, two: 2, three: 3});
721 | => 3
722 | ```
723 |
724 |
725 |
726 | ## Question 22. Difference between `Function`, `Method` and `Constructor` calls in JavaScript.
727 |
728 | Answer
729 |
730 | 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.
731 |
732 | functions : The simplest usages of function call:
733 |
734 | ```javascript
735 | function helloWorld(name) {
736 | return "hello world, " + name;
737 | }
738 |
739 | helloWorld("JS Geeks"); // "hello world JS Geeks"
740 | ```
741 |
742 | Methods in JavaScript are nothing more than object properties that are functions.
743 |
744 | ```javascript
745 | var obj = {
746 | helloWorld : function() {
747 | return "hello world, " + this.name;
748 | },
749 | name: 'John Carter'
750 | }
751 | obj.helloWorld(); // // "hello world John Carter"
752 | ```
753 |
754 | Notice how `helloWorld` refer to `this` properties of obj. Here it's clear or you might have already understood that `this` gets bound to `obj`. But the interesting point that we can copy a reference to the same function `helloWorld` in another object and get a difference answer. Let see:
755 |
756 | ```javascript
757 | var obj2 = {
758 | helloWorld : obj.helloWorld,
759 | name: 'John Doe'
760 | }
761 | obj2.helloWorld(); // "hello world John Doe"
762 | ```
763 |
764 | You might be wonder what exactly happens in a method call here. Here we call the expression itself determine the binding of this `this`, The expression `obj2.helloWorld()` looks up the `helloWorld` property of obj and calls it with receiver object `obj2`.
765 |
766 | The third use of functions is as constructors. Like function and method, `constructors` are defined with function.
767 |
768 | ```javascript
769 | function Employee(name, age) {
770 | this.name = name;
771 | this.age = age;
772 | }
773 |
774 | var emp1 = new Employee('John Doe', 28);
775 | emp1.name; // "John Doe"
776 | emp1.age; // 28
777 | ```
778 |
779 | Unlike function calls and method calls, a constructor call `new Employee('John Doe', 28)` creates a brand new object and passes it as the value of `this`, and implicitly returns the new object as its result.
780 |
781 | The primary role of the constructor function is to initialize the object.
782 |
783 |
784 |
785 |
786 | ## Question 23. What would be the output of the following code?
787 |
788 | ```javascript
789 | function User(name) {
790 | this.name = name || "JsGeeks";
791 | }
792 |
793 | var person = new User("xyz")["location"] = "USA";
794 | console.log(person);
795 | ```
796 |
797 | Answer
798 |
799 | 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.
800 |
801 | 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"`.
802 | Then it will be assigned to person.
803 |
804 | To better understand what's going on here, try to execute this code in console, line by line:
805 | ```javascript
806 | function User(name) {
807 | this.name = name || "JsGeeks";
808 | }
809 |
810 | var person;
811 | var foo = new User("xyz");
812 | foo["location"] = "USA";
813 | // the console will show you that the result of this is "USA"
814 |
815 | ```
816 |
817 |
818 |
819 |
820 | ## Question 24. What are Service Workers and when can you use them?
821 |
822 | Answer
823 |
824 | 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.
825 |
826 | Service Workers actively use promises. A Service Worker has to be installed,activated and then it can react on fetch, push and sync events.
827 |
828 | As of 2017, Service Workers are not supported in IE and Safari.
829 |
830 |
831 |
832 | ## Question 25. What is the difference between a method and a function in javascript?
833 |
834 | Answer
835 |
836 | 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).
837 |
838 | ```javascript
839 | // Function statement
840 | function myFunc() {
841 | // Do some stuff;
842 | }
843 |
844 | // Calling the function
845 | myFunc();
846 | ```
847 |
848 | Here myFunc() function call is not associated with object hence not invoked through any object.
849 |
850 | A function can take a form of immediately invoked function expression (IIFE):
851 |
852 | ```javascript
853 |
854 | // Anonymous Self-invoking Function
855 | (function() {
856 | // Do some stuff;
857 | })();
858 | ```
859 |
860 | Finally there are also arrow functions:
861 |
862 | ```javascript
863 | const myFunc = arg => {
864 | console.log("hello", arg)
865 | }
866 | ```
867 |
868 | A method is a piece of code that is called by its name and that is associated with the object. Methods are functions. When you call a method like this `obj1.myMethod()`, the reference to `obj1` gets assigned (bound) to `this` variable. In other words, the value of `this` will be `obj1` inside `myMethod`.
869 |
870 | Here are some examples of methods:
871 |
872 | ##### Example 1
873 | ```javascript
874 | var obj1 = {
875 | attribute: "xyz",
876 | myMethod: function () { // Method
877 | console.log(this.attribute);
878 | }
879 | };
880 |
881 | // Call the method
882 | obj1.myMethod();
883 | ```
884 |
885 | Here `obj1` is an object and `myMethod` is a method which is associated with `obj1`.
886 |
887 | ##### Example 2
888 | In ES6 we have classes. There the methods will look like this:
889 |
890 | ```javascript
891 | class MyAwesomeClass {
892 | myMethod() {
893 | console.log("hi there");
894 | }
895 | }
896 |
897 | const obj1 = new MyAwesomeClass();
898 | obj1.myMethod();
899 | ```
900 |
901 | Understand: the method is not some kind of special type of a function, and it's not about how you declare a function. It's the way we **call** a function. Look at that:
902 |
903 | ```javascript
904 | var obj1 = {
905 | prop1: "buddy"
906 | };
907 | var myFunc = function () {
908 | console.log("Hi there", this);
909 | };
910 | // let's call myFunc as a function:
911 | myFunc(); // will output "Hi there undefined" or "Hi there Window"
912 |
913 | obj1.myMethod = myFunc;
914 | //now we're calling myFunc as a method of obj1, so this will point to obj1
915 | obj1.myMethod(); // will print "Hi there" following with obj1.
916 |
917 | ```
918 |
919 |
920 |
921 | ## Question 26. What is IIFE (Immediately Invoked Function Expression) and how it can be useful?
922 | Answer
923 |
924 | #### Definition
925 | 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:
926 |
927 | ```javascript
928 | (function() {
929 | console.log("Hi, I'm IIFE!");
930 | })();
931 | // outputs "Hi, I'm IIFE!"
932 | ```
933 | #### Explanation
934 |
935 | So, here's how it works. Remember the difference between function statements (`function a () {}`) and function expressions (`var a = function() {}`)? So, IIFE is a function expression. To make it an expression we surround our function declaration into the parens. We do it to explicitly tell the parser that it's an expression, not a statement (JS doesn't allow statements in parens).
936 |
937 | After the function you can see the two `()` braces, this is how we run the function we just declared.
938 |
939 | That's it. The rest is details.
940 | - The function inside IIFE doesn't have to be anonymous. This one will work perfectly fine and will help to detect your function in a stacktrace during debugging:
941 | ```javascript
942 | (function myIIFEFunc() {
943 | console.log("Hi, I'm IIFE!");
944 | })();
945 | // outputs "Hi, I'm IIFE!"
946 | ```
947 | - It can take some parameters:
948 | ```javascript
949 | (function myIIFEFunc(param1) {
950 | console.log("Hi, I'm IIFE, " + param1);
951 | })("Yuri");
952 | // outputs "Hi, I'm IIFE, Yuri!"
953 | ```
954 | Here there value `"Yuri"` is passed to the `param1` of the function.
955 | - It can return a value:
956 | ```javascript
957 | var result = (function myIIFEFunc(param1) {
958 | console.log("Hi, I'm IIFE, " + param1);
959 | return 1;
960 | })("Yuri");
961 | // outputs "Hi, I'm IIFE, Yuri!"
962 | // result variable will contain 1
963 | ```
964 | - You don't have to surround the function declaration into parens, although it's the most common way to define IIFE. Instead you can use any of the following forms:
965 | - `~function(){console.log("hi I'm IIFE")}()`
966 | - `!function(){console.log("hi I'm IIFE")}()`
967 | - `+function(){console.log("hi I'm IIFE")}()`
968 | - `-function(){console.log("hi I'm IIFE")}()`
969 | - `(function(){console.log("hi I'm IIFE")}());`
970 | - `var i = function(){console.log("hi I'm IIFE")}();`
971 | - `true && function(){ console.log("hi I'm IIFE") }();`
972 | - `0, function(){ console.log("hi I'm IIFE") }();`
973 | - `new function(){ console.log("hi I'm IIFE") }`
974 | - `new function(){ console.log("hi I'm IIFE") }()`
975 |
976 | Please don't use all these forms to impress colleagues, but be prepared that you can encounter them in someone's code.
977 |
978 | #### Applications and usefulness
979 |
980 | Variables and functions that you declare inside an IIFE are not visible to the outside world, so you can:
981 | - Use the IIFE for isolating parts of the code to hide details of implementation.
982 | - Specify the input interface of your code by passing commonly used global objects (window, document, jQuery, etc.) IIFE’s parameters, and then reference these global objects within the IIFE via a local scope.
983 | - Use it in closures, when you use closures in loops.
984 | - IIFE is the basis of in the module pattern in ES5
985 | code, it helps to prevent polluting the global scope and provide the module interface to the outside.
986 |
987 |
988 |
989 |
990 | ## Question 27. Describe Singleton Pattern In JavaScript
991 | Answer
992 |
993 | 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.
994 |
995 | There are two important points in the traditional definition of Singleton pattern:
996 | - There should be only one instance allowed for a class and
997 | - We should allow global point of access to that single instance
998 |
999 | Let me define singleton pattern in JavaScript context:
1000 |
1001 | > It is an object that is used to create namespace and group together a related set of methods and attributes (encapsulation) and if we allow to initiate then it can be initiated only once.
1002 |
1003 | In JavaScript, we can create singleton though object literal. However, there is some another way but that I will cover in next post.
1004 |
1005 | A singleton object consists of two parts: The object itself, containing the members (Both methods and attributes) within it, and global variable used to access it. The variable is global so that object can be accessed anywhere in the page, this is a key feature of the singleton pattern.
1006 |
1007 | **JavaScript: A Singleton as a Namespace**
1008 |
1009 | As I have already stated above that singleton can be used to declare Namespace in JavaScript. NameSpacing is a large part of responsible programming in JavaScript. Because everything can be overwritten, and it is very easy to wipe out variable by mistake or a function, or even a class without even knowing it. A common example which happens frequently when you are working with another team member parallel,
1010 |
1011 | ```javascript
1012 | function findUserName(id) {
1013 |
1014 | }
1015 |
1016 | /* Later in the page another programmer
1017 | added code */
1018 | var findUserName = $('#user_list');
1019 |
1020 | /* You are trying to call :( */
1021 | console.log(findUserName())
1022 | ```
1023 |
1024 | One of the best ways to prevent accidentally overwriting variable is to namespace your code within a singleton object.
1025 |
1026 | ```javascript
1027 | /* Using Namespace */
1028 |
1029 | var MyNameSpace = {
1030 | findUserName : function(id) {},
1031 | // Other methods and attribute go here as well
1032 | }
1033 |
1034 | /* Later in the page another programmer
1035 | added code */
1036 | var findUserName = $('#user_list');
1037 |
1038 | /* You are trying to call and you make this time workable */
1039 | console.log(MyNameSpace.findUserName());
1040 | ```
1041 |
1042 | ### Singleton Design Pattern Implementation
1043 |
1044 | ```javascript
1045 | /* Lazy Instantiation skeleton for a singleton pattern */
1046 |
1047 | var MyNameSpace = {};
1048 | MyNameSpace.Singleton = (function() {
1049 |
1050 | // Private attribute that holds the single instance
1051 | var singletonInstance;
1052 |
1053 | // All of the normal code goes here
1054 | function constructor() {
1055 | // Private members
1056 | var privateVar1 = "Nishant";
1057 | var privateVar2 = [1,2,3,4,5];
1058 |
1059 | function privateMethod1() {
1060 | // code stuff
1061 | }
1062 |
1063 | function privateMethod1() {
1064 | // code stuff
1065 | }
1066 |
1067 | return {
1068 | attribute1 : "Nishant",
1069 | publicMethod: function() {
1070 | alert("Nishant");// some code logic
1071 | }
1072 | }
1073 | }
1074 |
1075 | return {
1076 | // public method (Global access point to Singleton object)
1077 | getInstance: function() {
1078 | //instance already exist then return
1079 | if(!singletonInstance) {
1080 | singletonInstance = constructor();
1081 | }
1082 | return singletonInstance;
1083 | }
1084 | }
1085 |
1086 | })();
1087 |
1088 | // getting access of publicMethod
1089 | console.log(MyNamespace.Singleton.getInstance().publicMethod());
1090 | ```
1091 |
1092 | 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.
1093 |
1094 |
1095 |
1096 | ## Question 28. What are the ways of creating objects in JavaScript ?
1097 |
1098 | Answer
1099 |
1100 | #### Method 1: Function based
1101 |
1102 | This method is useful if we want to create several similar objects. In the code sample below, we wrote the function `Employee` and used it as a constructor by calling it with the `new` operator.
1103 |
1104 | ```javascript
1105 |
1106 | function Employee(fName, lName, age, salary){
1107 | this.firstName = fName;
1108 | this.lastName = lName;
1109 | this.age = age;
1110 | this.salary = salary;
1111 | }
1112 |
1113 | // Creating multiple object which have similar property but diff value assigned to object property.
1114 | var employee1 = new Employee('John', 'Moto', 24, '5000$');
1115 | var employee2 = new Employee('Ryan', 'Jor', 26, '3000$');
1116 | var employee3 = new Employee('Andre', 'Salt', 26, '4000$');
1117 | ```
1118 |
1119 | #### Method 2: Object Literal
1120 |
1121 | Object Literal is best way to create an object and this is used frequently. Below is code sample for create employee object which contains property as well as method.
1122 |
1123 | ```javascript
1124 | var employee = {
1125 | name : 'Nishant',
1126 | salary : 245678,
1127 | getName : function(){
1128 | return this.name;
1129 | }
1130 | }
1131 | ```
1132 | The code sample below is Nested Object Literal, Here address is an object inside employee object.
1133 |
1134 | ```javascript
1135 | var employee = {
1136 | name : 'Nishant',
1137 | salary : 245678,
1138 | address : {
1139 | addressLine1 : 'BITS Pilani',
1140 | addressLine2 : 'Vidya Vihar'.
1141 | phoneNumber: {
1142 | workPhone: 7098889765,
1143 | homePhone: 1234567898
1144 | }
1145 | }
1146 | }
1147 | ```
1148 | #### Method 3: From `Object` using `new` keyword
1149 |
1150 | In the code below, a sample object has been created using `Object`'s constructor function.
1151 |
1152 | ```javascript
1153 | var employee = new Object(); // Created employee object using new keywords and Object()
1154 | employee.name = 'Nishant';
1155 | employee.getName = function(){
1156 | return this.name;
1157 | }
1158 | ```
1159 |
1160 | #### Method 4:** Using `Object.create`
1161 |
1162 | `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`.
1163 |
1164 |
1165 |
1166 | ## Question 29. Write a function called deepClone which takes an object and creates a object copy of it.
1167 |
1168 | ``` javascript
1169 | var newObject = deepClone(obj);
1170 | ```
1171 | Answer
1172 |
1173 | ```javascript
1174 | function deepClone(object){
1175 | var newObject = {};
1176 | for(var key in object){
1177 | if(typeof object[key] === 'object' && object[key] !== null ){
1178 | newObject[key] = deepClone(object[key]);
1179 | }else{
1180 | newObject[key] = object[key];
1181 | }
1182 | }
1183 | return newObject;
1184 | }
1185 | ```
1186 |
1187 | **Explanation:** We have been asked to do deep copy of object so What's basically it's mean ??. Let's understand in this way you have been given an object `personalDetail` this object contains some property which again a type of object here as you can see `address` is an object and `phoneNumber` in side an `address` is also an object. In simple term `personalDetail` is nested object(object inside object). So Here deep copy means we have to copy all the property of `personalDetail` object including nested object.
1188 |
1189 | ```javascript
1190 | var personalDetail = {
1191 | name : 'Nishant',
1192 | address : {
1193 | location: 'xyz',
1194 | zip : '123456',
1195 | phoneNumber : {
1196 | homePhone: 8797912345,
1197 | workPhone : 1234509876
1198 | }
1199 | }
1200 | }
1201 | ```
1202 | So when we do deep clone then we should copy every property (including the nested object).
1203 |
1204 |
1205 |
1206 | ## Question 30. Best way to detect `undefined` object property in JavaScript.
1207 |
1208 | Answer
1209 |
1210 | > Suppose we have given an object `person`
1211 |
1212 | ```javascript
1213 | var person = {
1214 | name: 'Nishant',
1215 | age : 24
1216 | }
1217 | ```
1218 | Here the `person` object has a `name` and `age` property. Now we are trying to access the **salary** property which we haven't declared on the person object so while accessing it will return undefined. So how we will ensure whether property is undefined or not before performing some operation over it?
1219 |
1220 | **Explanation:**
1221 |
1222 | We can use `typeof` operator to check undefined
1223 |
1224 | ```javascript
1225 | if(typeof someProperty === 'undefined'){
1226 | console.log('something is undefined here');
1227 | }
1228 | ```
1229 | Now we are trying to access salary property of person object.
1230 |
1231 | ```javascript
1232 | if(typeof person.salary === 'undefined'){
1233 | console.log("salary is undefined here because we haven't declared");
1234 | }
1235 | ```
1236 |
1237 |
1238 | ## 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.
1239 |
1240 | ```javascript
1241 | var objectLit = {foo : 'Bar'};
1242 | var cloneObj = Clone(obj); // Clone is the function which you have to write
1243 | console.log(cloneObj === Clone(objectLit)); // this should return false
1244 | console.log(cloneObj == Clone(objectLit)); // this should return true
1245 | ```
1246 | Answer
1247 |
1248 | ```javascript
1249 | function Clone(object){
1250 | var newObject = {};
1251 | for(var key in object){
1252 | newObject[key] = object[key];
1253 | }
1254 | return newObject;
1255 | }
1256 | ```
1257 |
1258 |
1259 |
1260 | ## Question 32. What are promises and how they are useful?
1261 |
1262 | Answer
1263 |
1264 | 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.
1265 |
1266 | A promise object has `then` method, where you can specify what to do when the promise is fulfilled or rejected.
1267 |
1268 | 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.
1269 |
1270 | Also mention that you know about more sophisticated concepts:
1271 | - `async/await` which makes the code appear even more linear
1272 | - RxJS observables can be viewed as the recyclable promises
1273 |
1274 | 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).
1275 |
1276 |
1277 |
1278 |
1279 | ## Question 33. How to check whether a key exist in a JavaScript object or not.
1280 |
1281 | Answer
1282 |
1283 | Let say we have `person` object with property **name** and **age**
1284 |
1285 | ```javascript
1286 | var person = {
1287 | name: 'Nishant',
1288 | age: 24
1289 | }
1290 | ```
1291 | Now we want to check whether `name` property exist in `person` object or not ?
1292 |
1293 | 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.
1294 |
1295 | So how we will check whether property is own property or inherited property.
1296 |
1297 | Method 1: We can use `in` operator on objet to check own property or inherited property.
1298 |
1299 | ```javascript
1300 | console.log('name' in person); // checking own property print true
1301 | console.log('salary' in person); // checking undefined property print false
1302 | ```
1303 | `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.
1304 |
1305 | Here
1306 |
1307 | ```javascript
1308 | console.log('toString' in person); // Will print true
1309 | ```
1310 | If we want to test property of object instance not inherited properties then we will use `hasOwnProperty` method of object instance.
1311 |
1312 | ```javascript
1313 | console.log(person.hasOwnProperty('toString')); // print false
1314 | console.log(person.hasOwnProperty('name')); // print true
1315 | console.log(person.hasOwnProperty('salary')); // print false
1316 | ```
1317 |
1318 |
1319 |
1320 | ## Question 34. What is NaN, why do we need it, and when can it break the page?
1321 |
1322 | Answer
1323 |
1324 | `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`:
1325 |
1326 | ```javascript
1327 | Math.sqrt(-5);
1328 | Math.log(-1);
1329 | 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. */
1330 | ```
1331 |
1332 | `NaN` is not equal to any number, it’s not less or more than any number, also it's not equal to itself:
1333 |
1334 | ```javascript
1335 | NaN !== NaN
1336 | NaN < 2 // false
1337 | NaN > 2 // false
1338 | NaN === 2 // false
1339 | ```
1340 |
1341 | 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.
1342 |
1343 | Further reading: [great blogpost on ariya.io](https://ariya.io/2014/05/the-curious-case-of-javascript-nan)
1344 |
1345 |
1346 |
1347 | ## Question 35. Fix the bug using ES5 only
1348 |
1349 | ```javascript
1350 | var arr = [10, 32, 65, 2];
1351 | for (var i = 0; i < arr.length; i++) {
1352 | setTimeout(function() {
1353 | console.log('The index of this number is: ' + i);
1354 | }, 3000);
1355 | }
1356 | ```
1357 | Answer
1358 |
1359 | For ES6, you can just replace `var i` with `let i`.
1360 |
1361 | For ES5, you need to create a function scope like here:
1362 |
1363 | ```javascript
1364 | var arr = [10, 32, 65, 2];
1365 | for (var i = 0; i < arr.length; i++) {
1366 | setTimeout(function(j) {
1367 | return function () {
1368 | console.log('The index of this number is: ' + j)
1369 | };
1370 | }(i), 3000);
1371 | }
1372 | ```
1373 |
1374 | This can also achieve by forEach (allows you to keep that variable within the forEach’s scope)
1375 |
1376 | ```javascript
1377 | var arr = [10, 32, 65, 2];
1378 | arr.forEach(function(ele, i) {
1379 | setTimeout(function() {
1380 | console.log('The index of this number is: ' + i);
1381 | }, 3000);
1382 | })
1383 | ```
1384 |
1385 |
1386 |
1387 | ## Question 36. How to check if the value of a variable in an array?
1388 |
1389 | Answer
1390 |
1391 | We always encounter in such situation where we need to know whether value is type of array or not.
1392 |
1393 | For instance : the code below perform some operation based value type
1394 |
1395 | ```javascript
1396 | function(value){
1397 | if("value is an array"){
1398 | // Then perform some operation
1399 | }else{
1400 | // otherwise
1401 | }
1402 | }
1403 | ```
1404 |
1405 | Let's discuss some way to detect an array in JavaScript.
1406 |
1407 | **Method 1:**
1408 |
1409 | Juriy Zaytsev (Also known as kangax) proposed an elegant solution to this.
1410 |
1411 | ```javascript
1412 | function isArray(value){
1413 | return Object.prototype.toString.call(value) === '[object Array]';
1414 | }
1415 | ```
1416 | 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.
1417 |
1418 |
1419 | **Method 2:**
1420 |
1421 | Duck typing test for array type detection
1422 |
1423 | ```javascript
1424 | // Duck typing arrays
1425 | function isArray(value){
1426 | return typeof value.sort === 'function';
1427 | }
1428 | ```
1429 | As we can see above isArray method will return true if value object have `sort` method of type `function`. Now assume you have created a object with sort method
1430 |
1431 | ```javascript
1432 | var bar = {
1433 | sort: function(){
1434 | // Some code
1435 | }
1436 | }
1437 | ```
1438 | 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.
1439 |
1440 | 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.
1441 |
1442 | **Method 3:**
1443 |
1444 | 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.
1445 |
1446 | In many JavaScript libraries you may see the code below for detecting an value of type array.
1447 |
1448 | ```javascript
1449 | function(value){
1450 | // ECMAScript 5 feature
1451 | if(typeof Array.isArray === 'function'){
1452 | return Array.isArray(value);
1453 | }else{
1454 | return Object.prototype.toString.call(value) === '[object Array]';
1455 | }
1456 | }
1457 | ```
1458 |
1459 | **Method 4:**
1460 |
1461 | You can query the constructor name:
1462 |
1463 | ```javascript
1464 | function isArray(value) {
1465 | return value.constructor.name === "Array";
1466 | }
1467 |
1468 | ```
1469 |
1470 | **Method 5:**
1471 |
1472 | You check if a given value is an `instanceof Array`:
1473 |
1474 | ```javascript
1475 | function isArray(value) {
1476 | return value instanceof Array;
1477 | }
1478 | ```
1479 |
1480 |
1481 |
1482 | ## Question 37. Best way to detect reference values of any type in JavaScript ?
1483 |
1484 | Answer
1485 |
1486 | 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**.
1487 |
1488 | Detecting object using `typeof` operator
1489 |
1490 | ```javascript
1491 | console.log(typeof {}); // object
1492 | console.log(typeof []); // object
1493 | console.log(typeof new Array()); // object
1494 | console.log(typeof null); // object
1495 | console.log(typeof new RegExp()); // object
1496 | console.log(typeof new Date()); // object
1497 | ```
1498 | But the downside of using typeof operator to detect an object is that typeof returns `object` for `null` (However this is fact that null is an object in JavaScript).
1499 |
1500 | The best way to detect an object of specific reference type using `instanceof` operator.
1501 |
1502 | >Syntax : **value** instanceof **constructor**
1503 |
1504 | ```javascript
1505 | //Detecting an array
1506 | if(value instanceof Array){
1507 | console.log("value is type of array");
1508 | }
1509 | ```
1510 | ```javascript
1511 | // Employee constructor function
1512 | function Employee(name){
1513 | this.name = name; // Public property
1514 | }
1515 |
1516 | var emp1 = new Employee('John');
1517 |
1518 | console.log(emp1 instanceof Employee); // true
1519 | ```
1520 | `instanceof` not only check the constructor which is used to create an object but also check it's prototype chain see below example.
1521 |
1522 | ```javascript
1523 | console.log(emp1 instanceof Object); // true
1524 | ```
1525 |
1526 |
1527 |
1528 | ## Question 38. How does Object.create method works JavaScript?
1529 |
1530 | Answer
1531 |
1532 | The ECMAScript 5 **Object.create()** method is the easiest way for one object to inherit from another, without invoking a constructor function.
1533 |
1534 | **For instance:**
1535 |
1536 | ```javascript
1537 | var employee = {
1538 | name: 'Nishant',
1539 | displayName: function () {
1540 | console.log(this.name);
1541 | }
1542 | };
1543 |
1544 | var emp1 = Object.create(employee);
1545 | console.log(emp1.displayName()); // output "Nishant"
1546 | ```
1547 |
1548 | 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.
1549 |
1550 | **For instance:** Defining `displayName()` method on `emp1` will not automatically override the employee `displayName`.
1551 |
1552 | ```javascript
1553 | emp1.displayName = function() {
1554 | console.log('xyz-Anonymous');
1555 | };
1556 |
1557 | employee.displayName(); //Nishant
1558 | emp1.displayName();//xyz-Anonymous
1559 | ```
1560 |
1561 | 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.
1562 |
1563 | **For example**
1564 |
1565 | ```javascript
1566 | var emp1 = Object.create(employee, {
1567 | name: {
1568 | value: "John"
1569 | }
1570 | });
1571 |
1572 | emp1.displayName(); // "John"
1573 | employee.displayName(); // "Nishant"
1574 | ```
1575 | In the example above, `emp1` is created with it's own value for name, so calling **displayName()** method will display `"John"` instead of `"Nishant"`.
1576 |
1577 | 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.
1578 |
1579 |
1580 |
1581 | ## Question 39. How to use constructor functions for inheritance in JavaScript?
1582 |
1583 | Answer
1584 |
1585 | Let say we have `Person` class which has name, age, salary properties and **incrementSalary()** method.
1586 |
1587 | ```javascript
1588 | function Person(name, age, salary) {
1589 | this.name = name;
1590 | this.age = age;
1591 | this.salary = salary;
1592 | this.incrementSalary = function (byValue) {
1593 | this.salary = this.salary + byValue;
1594 | };
1595 | }
1596 | ```
1597 |
1598 | Now we wish to create Employee class which contains all the properties of Person class and wanted to add some additional properties into Employee class.
1599 |
1600 | ```javascript
1601 | function Employee(company){
1602 | this.company = company;
1603 | }
1604 |
1605 | //Prototypal Inheritance
1606 | Employee.prototype = new Person("Nishant", 24,5000);
1607 | ```
1608 | 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`.
1609 |
1610 | ```javascript
1611 | //Prototypal Inheritance
1612 | Employee.prototype = new Person("Nishant", 24,5000);
1613 |
1614 | var emp1 = new Employee("Google");
1615 |
1616 | console.log(emp1 instanceof Person); // true
1617 | console.log(emp1 instanceof Employee); // true
1618 | ```
1619 |
1620 | Let's understand Constructor inheritance
1621 |
1622 | ```javascript
1623 | //Defined Person class
1624 | function Person(name){
1625 | this.name = name || "Nishant";
1626 | }
1627 |
1628 | var obj = {};
1629 |
1630 | // obj inherit Person class properties and method
1631 | Person.call(obj); // constructor inheritance
1632 |
1633 | console.log(obj); // Object {name: "Nishant"}
1634 | ```
1635 | Here we saw calling **Person.call(obj)** define the name properties from `Person` to `obj`.
1636 |
1637 | ```javascript
1638 | console.log(name in obj); // true
1639 | ```
1640 | 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.
1641 |
1642 |
1643 |
1644 | ## Question 40. How we can prevent modification of object in JavaScript ?.
1645 |
1646 | Answer
1647 |
1648 | 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.
1649 |
1650 | There are three levels of preventing modification:
1651 |
1652 | **1: Prevent extensions :**
1653 |
1654 | No new properties or methods can be added to the object, but one can change the existing properties and method.
1655 |
1656 | For example:
1657 |
1658 | ```javascript
1659 | var employee = {
1660 | name: "Nishant"
1661 | };
1662 |
1663 | // lock the object
1664 | Object.preventExtensions(employee);
1665 |
1666 | // Now try to change the employee object property name
1667 | employee.name = "John"; // work fine
1668 |
1669 | //Now try to add some new property to the object
1670 | employee.age = 24; // fails silently unless it's inside the strict mode
1671 | ```
1672 | **2: Seal :**
1673 |
1674 | It is same as prevent extension, in addition to this also prevent existing properties and methods from being deleted.
1675 |
1676 | To seal an object, we use **Object.seal()** method. you can check whether an object is sealed or not using **Object.isSealed();**
1677 |
1678 | ```javascript
1679 | var employee = {
1680 | name: "Nishant"
1681 | };
1682 |
1683 | // Seal the object
1684 | Object.seal(employee);
1685 |
1686 | console.log(Object.isExtensible(employee)); // false
1687 | console.log(Object.isSealed(employee)); // true
1688 |
1689 | delete employee.name // fails silently unless it's in strict mode
1690 |
1691 | // Trying to add new property will give an error
1692 | employee.age = 30; // fails silently unless in strict mode
1693 | ```
1694 |
1695 | when an object is sealed, its existing properties and methods can't be removed. Sealed object are also non-extensible.
1696 |
1697 | **3: Freeze :**
1698 |
1699 | Same as seal, In addition to this prevent existing properties methods from being modified (All properties and methods are read only).
1700 |
1701 | To freeze an object, use Object.freeze() method. We can also determine whether an object is frozen using Object.isFrozen();
1702 |
1703 | ```javascript
1704 | var employee = {
1705 | name: "Nishant"
1706 | };
1707 |
1708 | //Freeze the object
1709 | Object.freeze(employee);
1710 |
1711 | // Seal the object
1712 | Object.seal(employee);
1713 |
1714 | console.log(Object.isExtensible(employee)); // false
1715 | console.log(Object.isSealed(employee)); // true
1716 | console.log(Object.isFrozen(employee)); // true
1717 |
1718 |
1719 | employee.name = "xyz"; // fails silently unless in strict mode
1720 | employee.age = 30; // fails silently unless in strict mode
1721 | delete employee.name // fails silently unless it's in strict mode
1722 | ```
1723 |
1724 | Frozen objects are considered both non-extensible and sealed.
1725 |
1726 | **Recommended:**
1727 |
1728 | If you are decided to prevent modification, sealed, freeze the object then use in strict mode so that you can catch the error.
1729 |
1730 | For example:
1731 |
1732 | ```javascript
1733 | "use strict";
1734 |
1735 | var employee = {
1736 | name: "Nishant"
1737 | };
1738 |
1739 | //Freeze the object
1740 | Object.freeze(employee);
1741 |
1742 | // Seal the object
1743 | Object.seal(employee);
1744 |
1745 | console.log(Object.isExtensible(employee)); // false
1746 | console.log(Object.isSealed(employee)); // true
1747 | console.log(Object.isFrozen(employee)); // true
1748 |
1749 |
1750 | employee.name = "xyz"; // fails silently unless in strict mode
1751 | employee.age = 30; // fails silently unless in strict mode
1752 | delete employee.name; // fails silently unless it's in strict mode
1753 | ```
1754 |
1755 |
1756 |
1757 |
1758 | ## Question 41. Write a log function which will add prefix `(your message)` to every message you log using console.log ?
1759 | For example, If you log `console.log("Some message")` then output should be **(your message) Some message**
1760 |
1761 | Answer
1762 |
1763 | 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.
1764 |
1765 | A general way to do this keep adding your app name in every console.log message like
1766 |
1767 | ```javascript
1768 | console.log('your app name' + 'some error message');
1769 | ```
1770 | But doing in this way you have to write your app name everytime when you log message using console.
1771 |
1772 | There are some best way we can achieve this
1773 |
1774 | ```javascript
1775 | function appLog() {
1776 | var args = Array.prototype.slice.call(arguments);
1777 | args.unshift('your app name');
1778 | console.log.apply(console, args);
1779 | }
1780 |
1781 | appLog("Some error message");
1782 | //output of above console: 'your app name Some error message'
1783 | ```
1784 |
1785 |
1786 |
1787 | ## Question 42 . Write a function which will test string as a literal and as an object ?
1788 |
1789 | For example: We can create string using string literal and using String constructor function.
1790 |
1791 | ```javascript
1792 | // using string literal
1793 | var ltrlStr = "Hi I am string literal";
1794 | // using String constructor function
1795 | var objStr = new String("Hi I am string object");
1796 | ```
1797 |
1798 | Answer
1799 |
1800 | We can use typeof operator to test string literal and instanceof operator to test String object.
1801 |
1802 | ```javascript
1803 | function isString(str) {
1804 | return typeof(str) == 'string' || str instanceof String;
1805 | }
1806 |
1807 | var ltrlStr = "Hi I am string literal";
1808 | var objStr = new String("Hi I am string object");
1809 | console.log(isString(ltrlStr)); // true
1810 | console.log(isString(objStr)); // true
1811 | ```
1812 |
1813 |
1814 | ## Question 43 . What is typical use case for anonymous function in JavaScript ?
1815 |
1816 | Answer
1817 |
1818 | Anonymous functions basically used in following scenario.
1819 |
1820 | 1. No name is needed if function is only used in one place, then there is no need to add a name to function.
1821 |
1822 | Let's take the example of setTimeout function
1823 |
1824 | ```javascript
1825 | setTimeout(function(){
1826 | alert("Hello");
1827 | },1000);
1828 | ```
1829 | 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.
1830 |
1831 | 2. Anonymous functions are declared inline and inline functions have advantages in the case that they can access variable in the parent scopes.
1832 |
1833 | Let's take a example of event handler. Notify event of particular type (such as click) for a given object.
1834 |
1835 | 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.
1836 |
1837 | ```html
1838 |
1839 | ```
1840 | Add Event Listener
1841 |
1842 | ```javascript
1843 | var btn = document.getElementById('myBtn');
1844 | btn.addEventListener('click', function () {
1845 | alert('button clicked');
1846 | });
1847 | ```
1848 |
1849 | Above example shows used of anonymous function as a callback function in event handler.
1850 |
1851 | 3. Passing anonymous function as a parameter to calling function.
1852 |
1853 | Example:
1854 |
1855 | ```javascript
1856 | // Function which will execute callback function
1857 | function processCallback(callback){
1858 | if(typeof callback === 'function'){
1859 | callback();
1860 | }
1861 | }
1862 |
1863 | // Call function and pass anonymous function as callback
1864 | processCallback(function(){
1865 | alert("Hi I am anonymous callback function");
1866 | });
1867 | ```
1868 | The best way to make a decision for using anonymous function is to ask the following question:
1869 |
1870 | Will the function which I am going to define, be used anywhere else?
1871 |
1872 | If your answer is yes then go and create named function rather anonymous function.
1873 |
1874 | **Advantage of using anonymous function:**
1875 |
1876 | 1. It can reduce a bit of code, particularly in recursive function and in callback function.
1877 | 2. Avoid needless global namespace pollutions.
1878 |
1879 |
1880 |
1881 | ## Question 44 . How to set a default parameter value ?
1882 |
1883 | Answer
1884 |
1885 | 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 :
1886 |
1887 | ```python
1888 | // Define sentEmail function
1889 | // configuration : Configuration object
1890 | // provider : Email Service provider, Default would be gmail
1891 | def sentEmail(configuration, provider = 'Gmail'):
1892 | # Your code logic
1893 | ```
1894 | **In Pre ES6/ES2015**
1895 |
1896 | There are a lot of ways by which you can achieve this in pre ES2015.
1897 |
1898 | Let's understand the code below by which we achieved setting default parameter value.
1899 |
1900 | **Method 1: Setting default parameter value**
1901 |
1902 | ```javascript
1903 | function sentEmail(configuration, provider) {
1904 | // Set default value if user has not passed value for provider
1905 | provider = typeof provider !== 'undefined' ? provider : 'Gmail'
1906 | // Your code logic
1907 | ;
1908 | }
1909 | // In this call we are not passing provider parameter value
1910 | sentEmail({
1911 | from: 'xyz@gmail.com',
1912 | subject: 'Test Email'
1913 | });
1914 | // Here we are passing Yahoo Mail as a provider value
1915 | sentEmail({
1916 | from: 'xyz@gmail.com',
1917 | subject: 'Test Email'
1918 | }, 'Yahoo Mail');
1919 | ```
1920 |
1921 | **Method 2: Setting default parameter value**
1922 |
1923 | ```javascript
1924 | function sentEmail(configuration, provider) {
1925 | // Set default value if user has not passed value for provider
1926 | provider = provider || 'Gmail'
1927 | // Your code logic
1928 | ;
1929 | }
1930 | // In this call we are not passing provider parameter value
1931 | sentEmail({
1932 | from: 'xyz@gmail.com',
1933 | subject: 'Test Email'
1934 | });
1935 | // Here we are passing Yahoo Mail as a provider value
1936 | sentEmail({
1937 | from: 'xyz@gmail.com',
1938 | subject: 'Test Email'
1939 | }, 'Yahoo Mail');
1940 | ```
1941 |
1942 | **Method 3: Setting default parameter value in ES6**
1943 | ```javascript
1944 | function sendEmail(configuration, provider = "Gmail") {
1945 | // Set default value if user has not passed value for provider
1946 |
1947 | // Value of provider can be accessed directly
1948 | console.log(`Provider: ${provider}`);
1949 | }
1950 |
1951 | // In this call we are not passing provider parameter value
1952 | sentEmail({
1953 | from: 'xyz@gmail.com',
1954 | subject: 'Test Email'
1955 | });
1956 | // Here we are passing Yahoo Mail as a provider value
1957 | sentEmail({
1958 | from: 'xyz@gmail.com',
1959 | subject: 'Test Email'
1960 | }, 'Yahoo Mail');
1961 | ```
1962 |
1963 |
1964 |
1965 | ## Question 45. Write code for merge two JavaScript Object dynamically.
1966 | Let say you have two objects
1967 |
1968 | ```javascript
1969 | var person = {
1970 | name : 'John',
1971 | age : 24
1972 | }
1973 |
1974 | var address = {
1975 | addressLine1 : 'Some Location x',
1976 | addressLine2 : 'Some Location y',
1977 | city : 'NewYork'
1978 | }
1979 | ```
1980 | Write merge function which will take two object and add all the own property of second object into first object.
1981 |
1982 | Answer
1983 |
1984 | ```javascript
1985 | merge(person , address);
1986 |
1987 | /* Now person should have 5 properties
1988 | name , age , addressLine1 , addressLine2 , city */
1989 | ```
1990 | **Method 1: Using ES6, Object.assign method**
1991 |
1992 | ```javascript
1993 | const merge = (toObj, fromObj) => Object.assign(toObj, fromObj);
1994 | ```
1995 |
1996 | **Method 2: Without using built-in function**
1997 |
1998 | ```javascript
1999 | function merge(toObj, fromObj) {
2000 | // Make sure both of the parameter is an object
2001 | if (typeof toObj === 'object' && typeof fromObj === 'object') {
2002 | for (var pro in fromObj) {
2003 | // Assign only own properties not inherited properties
2004 | if (fromObj.hasOwnProperty(pro)) {
2005 | // Assign property and value
2006 | toObj[pro] = fromObj[pro];
2007 | }
2008 | }
2009 | }else{
2010 | throw "Merge function can apply only on object";
2011 | }
2012 | }
2013 | ```
2014 |
2015 |
2016 | ## Question 46. What is non-enumerable property in JavaScript and how you can create one?
2017 |
2018 | Answer
2019 |
2020 | 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.
2021 |
2022 | Let say we have following object
2023 |
2024 | ```javascript
2025 | var person = {
2026 | name: 'John'
2027 | };
2028 | person.salary = '10000$';
2029 | person['country'] = 'USA';
2030 |
2031 | console.log(Object.keys(person)); // ['name', 'salary', 'country']
2032 | ```
2033 | As we know that person object properties `name`, `salary` ,`country` are enumerable hence it's shown up when we called Object.keys(person).
2034 |
2035 | To create a non-enumerable property we have to use **Object.defineProperty()**. This is a special method for creating non-enumerable property in JavaScript.
2036 |
2037 | ```javascript
2038 | var person = {
2039 | name: 'John'
2040 | };
2041 | person.salary = '10000$';
2042 | person['country'] = 'USA';
2043 |
2044 | // Create non-enumerable property
2045 | Object.defineProperty(person, 'phoneNo',{
2046 | value : '8888888888',
2047 | enumerable: false
2048 | })
2049 |
2050 | Object.keys(person); // ['name', 'salary', 'country']
2051 | ```
2052 | In the example above `phoneNo` property didn't show up because we made it non-enumerable by setting **enumerable:false**
2053 |
2054 | **Bonus**
2055 |
2056 | Now let's try to change value of `phoneNo`
2057 |
2058 | ```javascript
2059 | person.phoneNo = '7777777777';
2060 | ```
2061 |
2062 | **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.
2063 |
2064 |
2065 |
2066 | ## Question 47. What is Function binding ?
2067 |
2068 | Answer
2069 |
2070 | 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.
2071 |
2072 | Let's consider the following example:
2073 |
2074 | ```javascript
2075 | var clickHandler = {
2076 | message: 'click event handler',
2077 | handleClick: function(event) {
2078 | console.log(this.message);
2079 | }
2080 | };
2081 |
2082 | var btn = document.getElementById('myBtn');
2083 | // Add click event to btn
2084 | btn.addEventListener('click', clickHandler.handleClick);
2085 | ```
2086 |
2087 | Here in this example clickHandler object is created which contain message properties and handleClick method.
2088 |
2089 | 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`.
2090 |
2091 | 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.
2092 |
2093 | ```javascript
2094 | var clickHandler = {
2095 | message: 'click event handler',
2096 | handleClick: function(event) {
2097 | console.log(this.message);
2098 | }
2099 | };
2100 |
2101 | var btn = document.getElementById('myBtn');
2102 | // Add click event to btn and bind the clickHandler object
2103 | btn.addEventListener('click', clickHandler.handleClick.bind(clickHandler));
2104 | ```
2105 |
2106 | `bind` method is available to all the function similar to call and apply method which take argument value of `this`.
2107 |
2108 |
2109 |
2110 | # Coding Questions
2111 |
2112 | ## Passing values by reference vs by value
2113 | For a JS developer, it's crucially important to understand which values are passed by reference,
2114 | and which ones are passed by value. Remember that objects, including arrays are passed by reference
2115 | while strings, booleans and numbers are passed by value.
2116 |
2117 | ### 1. What would be the output of following code?
2118 |
2119 | ```javascript
2120 | var strA = "hi there";
2121 | var strB = strA;
2122 | strB="bye there!";
2123 | console.log (strA)
2124 | ```
2125 |
2126 | Answer
2127 |
2128 | The output will be `'hi there'` because we're dealing with strings here. Strings are
2129 | passed by value, that is, copied.
2130 |
2131 |
2132 |
2133 | ### 2. What would be the output of following code?
2134 | ```javascript
2135 | var objA = {prop1: 42};
2136 | var objB = objA;
2137 | objB.prop1 = 90;
2138 | console.log(objA)
2139 | ```
2140 |
2141 | Answer
2142 |
2143 | The output will be `{prop1: 90}` because we're dealing with objects here. Objects are
2144 | passed by reference, that is, `objA` and `objB` point to the same object in memory.
2145 |
2146 |
2147 |
2148 | ### 3. What would be the output of following code?
2149 |
2150 | ```javascript
2151 | var objA = {prop1: 42};
2152 | var objB = objA;
2153 | objB = {};
2154 | console.log(objA)
2155 | ```
2156 |
2157 |
2158 | Answer
2159 |
2160 | The output will be `{prop1: 42}`.
2161 |
2162 | When we assign `objA` to `objB`, the `objB` variable will point
2163 | to the same object as the `objB` variable.
2164 |
2165 | However, when we reassign `objB` to an empty object, we simply change where `objB` variable references to.
2166 | This doesn't affect where `objA` variable references to.
2167 |
2168 |
2169 |
2170 | ### 4. What would be the output of following code?
2171 |
2172 | ```javascript
2173 | var arrA = [0,1,2,3,4,5];
2174 | var arrB = arrA;
2175 | arrB[0]=42;
2176 | console.log(arrA)
2177 | ```
2178 |
2179 |
2180 | Answer
2181 |
2182 | The output will be `[42,1,2,3,4,5]`.
2183 |
2184 | Arrays are object in JavaScript and they are passed and assigned by reference. This is why
2185 | both `arrA` and `arrB` point to the same array `[0,1,2,3,4,5]`. That's why changing the first
2186 | element of the `arrB` will also modify `arrA`: it's the same array in the memory.
2187 |
2188 |
2189 |
2190 | ### 5. What would be the output of following code?
2191 | ```javascript
2192 | var arrA = [0,1,2,3,4,5];
2193 | var arrB = arrA.slice();
2194 | arrB[0]=42;
2195 | console.log(arrA)
2196 | ```
2197 |
2198 |
2199 | Answer
2200 |
2201 | The output will be `[0,1,2,3,4,5]`.
2202 |
2203 | The `slice` function copies all the elements of the array returning the new array. That's why
2204 | `arrA` and `arrB` reference two completely different arrays.
2205 |
2206 |
2207 |
2208 | ### 6. What would be the output of following code?
2209 |
2210 | ```javascript
2211 | var arrA = [{prop1: "value of array A!!"}, {someProp: "also value of array A!"}, 3,4,5];
2212 | var arrB = arrA;
2213 | arrB[0].prop1=42;
2214 | console.log(arrA);
2215 | ```
2216 |
2217 | Answer
2218 |
2219 | The output will be `[{prop1: 42}, {someProp: "also value of array A!"}, 3,4,5]`.
2220 |
2221 | Arrays are object in JS, so both varaibles arrA and arrB point to the same array. Changing
2222 | `arrB[0]` is the same as changing `arrA[0]`
2223 |
2224 |
2225 |
2226 | ### 7. What would be the output of following code?
2227 |
2228 | ```javascript
2229 | var arrA = [{prop1: "value of array A!!"}, {someProp: "also value of array A!"},3,4,5];
2230 | var arrB = arrA.slice();
2231 | arrB[0].prop1=42;
2232 | arrB[3] = 20;
2233 | console.log(arrA);
2234 | ```
2235 |
2236 | Answer
2237 |
2238 | The output will be `[{prop1: 42}, {someProp: "also value of array A!"}, 3,4,5]`.
2239 |
2240 | The `slice` function copies all the elements of the array returning the new array. However,
2241 | it doesn't do deep copying. Instead it does shallow copying. You can imagine slice implemented like this:
2242 |
2243 | ```javascript
2244 | function slice(arr) {
2245 | var result = [];
2246 | for (i = 0; i< arr.length; i++) {
2247 | result.push(arr[i]);
2248 | }
2249 | return result;
2250 | }
2251 | ```
2252 |
2253 | Look at the line with `result.push(arr[i])`. If `arr[i]` happens to be a number or string,
2254 | it will be passed by value, in other words, copied. If `arr[i]` is an object, it will be passed by reference.
2255 |
2256 | In case of our array `arr[0]` is an object `{prop1: "value of array A!!"}`. Only the reference
2257 | to this object will be copied. This effectively means that arrays arrA and arrB share first
2258 | two elements.
2259 |
2260 | This is why changing the property of `arrB[0]` in `arrB` will also change the `arrA[0]`.
2261 |
2262 |
2263 |
2264 | ## Hoisting
2265 |
2266 | ### 1. console.log(employeeId);
2267 |
2268 | 1. Some Value
2269 | 2. Undefined
2270 | 3. Type Error
2271 | 4. ReferenceError: employeeId is not defined
2272 |
2273 | Answer
2274 |
2275 | 4) ReferenceError: employeeId is not defined
2276 |
2277 |
2278 |
2279 | ### 2. What would be the output of following code?
2280 |
2281 | ```javascript
2282 | console.log(employeeId);
2283 | var employeeId = '19000';
2284 | ```
2285 |
2286 | 1. Some Value
2287 | 2. undefined
2288 | 3. Type Error
2289 | 4. ReferenceError: employeeId is not defined
2290 |
2291 | Answer
2292 |
2293 | 2) undefined
2294 |
2295 |
2296 |
2297 | ### 3. What would be the output of following code?
2298 |
2299 | ```javascript
2300 | var employeeId = '1234abe';
2301 | (function(){
2302 | console.log(employeeId);
2303 | var employeeId = '122345';
2304 | })();
2305 | ```
2306 |
2307 | 1. '122345'
2308 | 2. undefined
2309 | 3. Type Error
2310 | 4. ReferenceError: employeeId is not defined
2311 |
2312 | Answer
2313 |
2314 | 2) undefined
2315 |
2316 |
2317 |
2318 | ### 4. What would be the output of following code?
2319 |
2320 | ```javascript
2321 | var employeeId = '1234abe';
2322 | (function() {
2323 | console.log(employeeId);
2324 | var employeeId = '122345';
2325 | (function() {
2326 | var employeeId = 'abc1234';
2327 | }());
2328 | }());
2329 | ```
2330 |
2331 | 1. '122345'
2332 | 2. undefined
2333 | 3. '1234abe'
2334 | 4. ReferenceError: employeeId is not defined
2335 |
2336 | Answer
2337 |
2338 | 2) undefined
2339 |
2340 |
2341 |
2342 | ### 5. What would be the output of following code?
2343 |
2344 | ```javascript
2345 | (function() {
2346 | console.log(typeof displayFunc);
2347 | var displayFunc = function(){
2348 | console.log("Hi I am inside displayFunc");
2349 | }
2350 | }());
2351 | ```
2352 |
2353 | 1. undefined
2354 | 2. function
2355 | 3. 'Hi I am inside displayFunc'
2356 | 4. ReferenceError: displayFunc is not defined
2357 |
2358 | Answer
2359 |
2360 | 1) undefined
2361 |
2362 |
2363 |
2364 | ### 6. What would be the output of following code?
2365 |
2366 | ```javascript
2367 | var employeeId = 'abc123';
2368 | function foo(){
2369 | employeeId = '123bcd';
2370 | return;
2371 | }
2372 | foo();
2373 | console.log(employeeId);
2374 | ```
2375 |
2376 | 1. undefined
2377 | 2. '123bcd'
2378 | 3. 'abc123'
2379 | 4. ReferenceError: employeeId is not defined
2380 |
2381 | Answer
2382 |
2383 | 2) '123bcd'
2384 |
2385 |
2386 |
2387 | ### 7. What would be the output of following code?
2388 |
2389 | ```javascript
2390 | var employeeId = 'abc123';
2391 |
2392 | function foo() {
2393 | employeeId = '123bcd';
2394 | return;
2395 |
2396 | function employeeId() {}
2397 | }
2398 | foo();
2399 | console.log(employeeId);
2400 | ```
2401 |
2402 | 1. undefined
2403 | 2. '123bcd'
2404 | 3. 'abc123'
2405 | 4. ReferenceError: employeeId is not defined
2406 |
2407 | Answer
2408 |
2409 | 3) 'abc123'
2410 |
2411 |
2412 |
2413 | ### 8. What would be the output of following code?
2414 |
2415 | ```javascript
2416 | var employeeId = 'abc123';
2417 |
2418 | function foo() {
2419 | employeeId();
2420 | return;
2421 |
2422 | function employeeId() {
2423 | console.log(typeof employeeId);
2424 | }
2425 | }
2426 | foo();
2427 | ```
2428 |
2429 | 1. undefined
2430 | 2. function
2431 | 3. string
2432 | 4. ReferenceError: employeeId is not defined
2433 |
2434 | Answer
2435 |
2436 | 2) 'function'
2437 |
2438 |
2439 |
2440 | ### 9. What would be the output of following code?
2441 |
2442 | ```javascript
2443 | function foo() {
2444 | employeeId();
2445 | var product = 'Car';
2446 | return;
2447 |
2448 | function employeeId() {
2449 | console.log(product);
2450 | }
2451 | }
2452 | foo();
2453 | ```
2454 |
2455 | 1. undefined
2456 | 2. Type Error
2457 | 3. 'Car'
2458 | 4. ReferenceError: product is not defined
2459 |
2460 | Answer
2461 |
2462 | 1) undefined
2463 |
2464 |
2465 |
2466 | ### 10. What would be the output of following code?
2467 |
2468 | ```javascript
2469 | (function foo() {
2470 | bar();
2471 |
2472 | function bar() {
2473 | abc();
2474 | console.log(typeof abc);
2475 | }
2476 |
2477 | function abc() {
2478 | console.log(typeof bar);
2479 | }
2480 | }());
2481 | ```
2482 |
2483 | 1. undefined undefined
2484 | 2. Type Error
2485 | 3. function function
2486 | 4. ReferenceError: bar is not defined
2487 |
2488 | Answer
2489 |
2490 | 3) function function
2491 |
2492 |
2493 |
2494 | ## Objects
2495 |
2496 | ### 1. What would be the output of following code ?
2497 |
2498 | ```javascript
2499 | (function() {
2500 | 'use strict';
2501 |
2502 | var person = {
2503 | name: 'John'
2504 | };
2505 | person.salary = '10000$';
2506 | person['country'] = 'USA';
2507 |
2508 | Object.defineProperty(person, 'phoneNo', {
2509 | value: '8888888888',
2510 | enumerable: true
2511 | })
2512 |
2513 | console.log(Object.keys(person));
2514 | })();
2515 | ```
2516 | 1. Type Error
2517 | 2. undefined
2518 | 3. ["name", "salary", "country", "phoneNo"]
2519 | 4. ["name", "salary", "country"]
2520 |
2521 | Answer
2522 |
2523 | 3) ["name", "salary", "country", "phoneNo"]
2524 |
2525 |
2526 |
2527 | ### 2. What would be the output of following code ?
2528 |
2529 | ```javascript
2530 | (function() {
2531 | 'use strict';
2532 |
2533 | var person = {
2534 | name: 'John'
2535 | };
2536 | person.salary = '10000$';
2537 | person['country'] = 'USA';
2538 |
2539 | Object.defineProperty(person, 'phoneNo', {
2540 | value: '8888888888',
2541 | enumerable: false
2542 | })
2543 |
2544 | console.log(Object.keys(person));
2545 | })();
2546 | ```
2547 | 1. Type Error
2548 | 2. undefined
2549 | 3. ["name", "salary", "country", "phoneNo"]
2550 | 4. ["name", "salary", "country"]
2551 |
2552 | Answer
2553 |
2554 | 4) ["name", "salary", "country"]
2555 |
2556 |
2557 |
2558 | ### 3. What would be the output of following code ?
2559 |
2560 | ```javascript
2561 | (function() {
2562 | var objA = {
2563 | foo: 'foo',
2564 | bar: 'bar'
2565 | };
2566 | var objB = {
2567 | foo: 'foo',
2568 | bar: 'bar'
2569 | };
2570 | console.log(objA == objB);
2571 | console.log(objA === objB);
2572 | }());
2573 | ```
2574 | 1. false true
2575 | 2. false false
2576 | 3. true false
2577 | 4. true true
2578 |
2579 | Answer
2580 |
2581 | 2) false false
2582 |
2583 |
2584 |
2585 | ### 4. What would be the output of following code ?
2586 |
2587 | ```javascript
2588 | (function() {
2589 | var objA = new Object({foo: "foo"});
2590 | var objB = new Object({foo: "foo"});
2591 | console.log(objA == objB);
2592 | console.log(objA === objB);
2593 | }());
2594 | ```
2595 | 1. false true
2596 | 2. false false
2597 | 3. true false
2598 | 4. true true
2599 |
2600 | Answer
2601 |
2602 | 2) false false
2603 |
2604 |
2605 |
2606 | ### 5. What would be the output of following code ?
2607 |
2608 | ```javascript
2609 | (function() {
2610 | var objA = Object.create({
2611 | foo: 'foo'
2612 | });
2613 | var objB = Object.create({
2614 | foo: 'foo'
2615 | });
2616 | console.log(objA == objB);
2617 | console.log(objA === objB);
2618 | }());
2619 | ```
2620 | 1. false true
2621 | 2. false false
2622 | 3. true false
2623 | 4. true true
2624 |
2625 | Answer
2626 |
2627 | 2) false false
2628 |
2629 |
2630 |
2631 | ### 6. What would be the output of following code ?
2632 |
2633 | ```javascript
2634 | (function() {
2635 | var objA = Object.create({
2636 | foo: 'foo'
2637 | });
2638 | var objB = Object.create(objA);
2639 | console.log(objA == objB);
2640 | console.log(objA === objB);
2641 | }());
2642 | ```
2643 | 1. false true
2644 | 2. false false
2645 | 3. true false
2646 | 4. true true
2647 |
2648 | Answer
2649 |
2650 | 2) false false
2651 |
2652 |
2653 |
2654 | ### 7. What would be the output of following code ?
2655 |
2656 | ```javascript
2657 | (function() {
2658 | var objA = Object.create({
2659 | foo: 'foo'
2660 | });
2661 | var objB = Object.create(objA);
2662 | console.log(objA.toString() == objB.toString());
2663 | console.log(objA.toString() === objB.toString());
2664 | }());
2665 | ```
2666 | 1. false true
2667 | 2. false false
2668 | 3. true false
2669 | 4. true true
2670 |
2671 | Answer
2672 |
2673 | 4) true true
2674 |
2675 |
2676 |
2677 | ### 8. What would be the output of following code ?
2678 |
2679 | ```javascript
2680 | (function() {
2681 | var objA = Object.create({
2682 | foo: 'foo'
2683 | });
2684 | var objB = objA;
2685 | console.log(objA == objB);
2686 | console.log(objA === objB);
2687 | console.log(objA.toString() == objB.toString());
2688 | console.log(objA.toString() === objB.toString());
2689 | }());
2690 | ```
2691 | 1. true true true false
2692 | 2. true false true true
2693 | 3. true true true true
2694 | 4. true true false false
2695 |
2696 | Answer
2697 |
2698 | 3) true true true true
2699 |
2700 |
2701 |
2702 | ### 9. What would be the output of following code ?
2703 |
2704 | ```javascript
2705 | (function() {
2706 | var objA = Object.create({
2707 | foo: 'foo'
2708 | });
2709 | var objB = objA;
2710 | objB.foo = 'bar';
2711 | console.log(objA.foo);
2712 | console.log(objB.foo);
2713 | }());
2714 | ```
2715 | 1. foo bar
2716 | 2. bar bar
2717 | 3. foo foo
2718 | 4. bar foo
2719 |
2720 | Answer
2721 |
2722 | 2) bar bar
2723 |
2724 |
2725 |
2726 | ### 10. What would be the output of following code ?
2727 |
2728 | ```javascript
2729 | (function() {
2730 | var objA = Object.create({
2731 | foo: 'foo'
2732 | });
2733 | var objB = objA;
2734 | objB.foo = 'bar';
2735 |
2736 | delete objA.foo;
2737 | console.log(objA.foo);
2738 | console.log(objB.foo);
2739 | }());
2740 | ```
2741 | 1. foo bar
2742 | 2. bar bar
2743 | 3. foo foo
2744 | 4. bar foo
2745 |
2746 | Answer
2747 |
2748 | 3) foo foo
2749 |
2750 |
2751 |
2752 | ### 11. What would be the output of following code ?
2753 |
2754 | ```javascript
2755 | (function() {
2756 | var objA = {
2757 | foo: 'foo'
2758 | };
2759 | var objB = objA;
2760 | objB.foo = 'bar';
2761 |
2762 | delete objA.foo;
2763 | console.log(objA.foo);
2764 | console.log(objB.foo);
2765 | }());
2766 | ```
2767 | 1. foo bar
2768 | 2. undefined undefined
2769 | 3. foo foo
2770 | 4. undefined bar
2771 |
2772 | Answer
2773 |
2774 | 2) undefined undefined
2775 |
2776 |
2777 |
2778 | ## Arrays
2779 |
2780 | ### 1. What would be the output of following code?
2781 |
2782 | ```javascript
2783 | (function() {
2784 | var array = new Array('100');
2785 | console.log(array);
2786 | console.log(array.length);
2787 | }());
2788 | ```
2789 |
2790 | 1. undefined undefined
2791 | 2. [undefined × 100] 100
2792 | 3. ["100"] 1
2793 | 4. ReferenceError: array is not defined
2794 |
2795 | Answer
2796 |
2797 | 3) ["100"] 1
2798 |
2799 |
2800 |
2801 | ### 2. What would be the output of following code?
2802 |
2803 | ```javascript
2804 | (function() {
2805 | var array1 = [];
2806 | var array2 = new Array(100);
2807 | var array3 = new Array(['1',2,'3',4,5.6]);
2808 | console.log(array1);
2809 | console.log(array2);
2810 | console.log(array3);
2811 | console.log(array3.length);
2812 | }());
2813 | ```
2814 |
2815 | 1. [] [] [Array[5]] 1
2816 | 2. [] [undefined × 100] Array[5] 1
2817 | 3. [] [] ['1',2,'3',4,5.6] 5
2818 | 4. [] [] [Array[5]] 5
2819 |
2820 | Answer
2821 |
2822 | 1) [] [] [Array[5]] 1
2823 |
2824 |
2825 |
2826 | ### 3. What would be the output of following code?
2827 |
2828 | ```javascript
2829 | (function () {
2830 | var array = new Array('a', 'b', 'c', 'd', 'e');
2831 | array[10] = 'f';
2832 | delete array[10];
2833 | console.log(array.length);
2834 | }());
2835 | ```
2836 |
2837 | 1. 11
2838 | 2. 5
2839 | 3. 6
2840 | 4. undefined
2841 |
2842 | Answer
2843 |
2844 | 1) 11
2845 |
2846 |
2847 |
2848 | ### 4. What would be the output of following code?
2849 |
2850 | ```javascript
2851 | (function(){
2852 | var animal = ['cow','horse'];
2853 | animal.push('cat');
2854 | animal.push('dog','rat','goat');
2855 | console.log(animal.length);
2856 | })();
2857 | ```
2858 |
2859 | 1. 4
2860 | 2. 5
2861 | 3. 6
2862 | 4. undefined
2863 |
2864 | Answer
2865 |
2866 | 3) 6
2867 |
2868 |
2869 |
2870 | ### 5. What would be the output of following code?
2871 |
2872 | ```javascript
2873 | (function(){
2874 | var animal = ['cow','horse'];
2875 | animal.push('cat');
2876 | animal.unshift('dog','rat','goat');
2877 | console.log(animal);
2878 | })();
2879 | ```
2880 |
2881 | 1. [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ]
2882 | 2. [ 'cow', 'horse', 'cat', 'dog', 'rat', 'goat' ]
2883 | 3. Type Error
2884 | 4. undefined
2885 |
2886 | Answer
2887 |
2888 | 1) [ 'dog', 'rat', 'goat', 'cow', 'horse', 'cat' ]
2889 |
2890 |
2891 |
2892 | ### 6. What would be the output of following code?
2893 |
2894 | ```javascript
2895 | (function(){
2896 | var array = [1,2,3,4,5];
2897 | console.log(array.indexOf(2));
2898 | console.log([{name: 'John'},{name : 'John'}].indexOf({name:'John'}));
2899 | console.log([[1],[2],[3],[4]].indexOf([3]));
2900 | console.log("abcdefgh".indexOf('e'));
2901 | })();
2902 | ```
2903 |
2904 | 1. 1 -1 -1 4
2905 | 2. 1 0 -1 4
2906 | 3. 1 -1 -1 -1
2907 | 4. 1 undefined -1 4
2908 |
2909 | Answer
2910 |
2911 | 1) 1 -1 -1 4
2912 |
2913 |
2914 |
2915 | ### 7. What would be the output of following code?
2916 |
2917 | ```javascript
2918 | (function(){
2919 | var array = [1,2,3,4,5,1,2,3,4,5,6];
2920 | console.log(array.indexOf(2));
2921 | console.log(array.indexOf(2,3));
2922 | console.log(array.indexOf(2,10));
2923 | })();
2924 | ```
2925 |
2926 | 1. 1 -1 -1
2927 | 2. 1 6 -1
2928 | 3. 1 1 -1
2929 | 4. 1 undefined undefined
2930 |
2931 | Answer
2932 |
2933 | 2) 1 6 -1
2934 |
2935 |
2936 |
2937 | ### 8. What would be the output of following code?
2938 |
2939 | ```javascript
2940 | (function(){
2941 | var numbers = [2,3,4,8,9,11,13,12,16];
2942 | var even = numbers.filter(function(element, index){
2943 | return element % 2 === 0;
2944 | });
2945 | console.log(even);
2946 |
2947 | var containsDivisibleby3 = numbers.some(function(element, index){
2948 | return element % 3 === 0;
2949 | });
2950 |
2951 | console.log(containsDivisibleby3);
2952 | })();
2953 | ```
2954 |
2955 | 1. [ 2, 4, 8, 12, 16 ] [ 0, 3, 0, 0, 9, 0, 12]
2956 | 2. [ 2, 4, 8, 12, 16 ] [ 3, 9, 12]
2957 | 3. [ 2, 4, 8, 12, 16 ] true
2958 | 4. [ 2, 4, 8, 12, 16 ] false
2959 |
2960 | Answer
2961 |
2962 | 3) [ 2, 4, 8, 12, 16 ] true
2963 |
2964 |
2965 |
2966 | ### 9. What would be the output of following code?
2967 |
2968 | ```javascript
2969 | (function(){
2970 | var containers = [2,0,false,"", '12', true];
2971 | var containers = containers.filter(Boolean);
2972 | console.log(containers);
2973 | var containers = containers.filter(Number);
2974 | console.log(containers);
2975 | var containers = containers.filter(String);
2976 | console.log(containers);
2977 | var containers = containers.filter(Object);
2978 | console.log(containers);
2979 | })();
2980 | ```
2981 |
2982 | 1. [ 2, '12', true ]
2983 | [ 2, '12', true ]
2984 | [ 2, '12', true ]
2985 | [ 2, '12', true ]
2986 | 2. [false, true]
2987 | [ 2 ]
2988 | ['12']
2989 | [ ]
2990 | 3. [2,0,false,"", '12', true]
2991 | [2,0,false,"", '12', true]
2992 | [2,0,false,"", '12', true]
2993 | [2,0,false,"", '12', true]
2994 | 4. [ 2, '12', true ]
2995 | [ 2, '12', true, false ]
2996 | [ 2, '12', true,false ]
2997 | [ 2, '12', true,false]
2998 |
2999 |
3000 | Answer
3001 |
3002 | 1) [ 2, '12', true ]
3003 | [ 2, '12', true ]
3004 | [ 2, '12', true ]
3005 | [ 2, '12', true ]
3006 |
3007 |
3008 |
3009 | ### 10. What would be the output of following code?
3010 |
3011 | ```javascript
3012 | (function(){
3013 | var list = ['foo','bar','john','ritz'];
3014 | console.log(list.slice(1));
3015 | console.log(list.slice(1,3));
3016 | console.log(list.slice());
3017 | console.log(list.slice(2,2));
3018 | console.log(list);
3019 | })();
3020 | ```
3021 |
3022 | 1. [ 'bar', 'john', 'ritz' ]
3023 | [ 'bar', 'john' ]
3024 | [ 'foo', 'bar', 'john', 'ritz' ]
3025 | []
3026 | [ 'foo', 'bar', 'john', 'ritz' ]
3027 | 2. [ 'bar', 'john', 'ritz' ]
3028 | [ 'bar', 'john','ritz ]
3029 | [ 'foo', 'bar', 'john', 'ritz' ]
3030 | []
3031 | [ 'foo', 'bar', 'john', 'ritz' ]
3032 | 3. [ 'john', 'ritz' ]
3033 | [ 'bar', 'john' ]
3034 | [ 'foo', 'bar', 'john', 'ritz' ]
3035 | []
3036 | [ 'foo', 'bar', 'john', 'ritz' ]
3037 | 4. [ 'foo' ]
3038 | [ 'bar', 'john' ]
3039 | [ 'foo', 'bar', 'john', 'ritz' ]
3040 | []
3041 | [ 'foo', 'bar', 'john', 'ritz' ]
3042 |
3043 | Answer
3044 |
3045 | 1) [ 'bar', 'john', 'ritz' ]
3046 | [ 'bar', 'john' ]
3047 | [ 'foo', 'bar', 'john', 'ritz' ]
3048 | []
3049 | [ 'foo', 'bar', 'john', 'ritz' ]
3050 |
3051 |
3052 |
3053 | ### 11. What would be the output of following code?
3054 |
3055 | ```javascript
3056 | (function(){
3057 | var list = ['foo','bar','john'];
3058 | console.log(list.splice(1));
3059 | console.log(list.splice(1,2));
3060 | console.log(list);
3061 | })();
3062 | ```
3063 |
3064 | 1. [ 'bar', 'john' ] [] [ 'foo' ]
3065 | 2. [ 'bar', 'john' ] [] [ 'bar', 'john' ]
3066 | 3. [ 'bar', 'john' ] [ 'bar', 'john' ] [ 'bar', 'john' ]
3067 | 4. [ 'bar', 'john' ] [] []
3068 |
3069 | Answer
3070 |
3071 | 1. [ 'bar', 'john' ] [] [ 'foo' ]
3072 |
3073 |
3074 |
3075 | ### 12. What would be the output of following code?
3076 |
3077 | ```javascript
3078 | (function(){
3079 | var arrayNumb = [2, 8, 15, 16, 23, 42];
3080 | arrayNumb.sort();
3081 | console.log(arrayNumb);
3082 | })();
3083 | ```
3084 |
3085 | 1. [2, 8, 15, 16, 23, 42]
3086 | 2. [42, 23, 26, 15, 8, 2]
3087 | 3. [ 15, 16, 2, 23, 42, 8 ]
3088 | 4. [ 2, 8, 15, 16, 23, 42 ]
3089 |
3090 | Answer
3091 |
3092 | 3. [ 15, 16, 2, 23, 42, 8 ]
3093 |
3094 |
3095 |
3096 | ## Functions
3097 |
3098 | ### 1. What would be the output of following code ?
3099 |
3100 | ```javascript
3101 | function funcA(){
3102 | console.log("funcA ", this);
3103 | (function innerFuncA1(){
3104 | console.log("innerFunc1", this);
3105 | (function innerFunA11(){
3106 | console.log("innerFunA11", this);
3107 | })();
3108 | })();
3109 | }
3110 |
3111 | console.log(funcA());
3112 | ```
3113 |
3114 | 1. funcA Window {...}
3115 | innerFunc1 Window {...}
3116 | innerFunA11 Window {...}
3117 | 2. undefined
3118 | 3. Type Error
3119 | 4. ReferenceError: this is not defined
3120 |
3121 | Answer
3122 |
3123 | 1)
3124 |
3125 |
3126 |
3127 | ### 2. What would be the output of following code ?
3128 |
3129 | ```javascript
3130 | var obj = {
3131 | message: "Hello",
3132 | innerMessage: !(function() {
3133 | console.log(this.message);
3134 | })()
3135 | };
3136 |
3137 | console.log(obj.innerMessage);
3138 | ```
3139 |
3140 | 1. ReferenceError: this.message is not defined
3141 | 2. undefined
3142 | 3. Type Error
3143 | 4. undefined true
3144 |
3145 | Answer
3146 |
3147 | 4) undefined true
3148 |
3149 |
3150 |
3151 | ### 3. What would be the output of following code ?
3152 |
3153 | ```javascript
3154 | var obj = {
3155 | message: "Hello",
3156 | innerMessage: function() {
3157 | return this.message;
3158 | }
3159 | };
3160 |
3161 | console.log(obj.innerMessage());
3162 | ```
3163 |
3164 | 1. Hello
3165 | 2. undefined
3166 | 3. Type Error
3167 | 4. ReferenceError: this.message is not defined
3168 |
3169 | Answer
3170 |
3171 | 1) Hello
3172 |
3173 |
3174 |
3175 | ### 4. What would be the output of following code ?
3176 |
3177 | ```javascript
3178 | var obj = {
3179 | message: 'Hello',
3180 | innerMessage: function () {
3181 | (function () {
3182 | console.log(this.message);
3183 | }());
3184 | }
3185 | };
3186 | console.log(obj.innerMessage());
3187 | ```
3188 |
3189 | 1. Type Error
3190 | 2. Hello
3191 | 3. undefined
3192 | 4. ReferenceError: this.message is not defined
3193 |
3194 | Answer
3195 |
3196 | 3) undefined
3197 |
3198 |
3199 |
3200 | ### 5. What would be the output of following code ?
3201 |
3202 | ```javascript
3203 | var obj = {
3204 | message: 'Hello',
3205 | innerMessage: function () {
3206 | var self = this;
3207 | (function () {
3208 | console.log(self.message);
3209 | }());
3210 | }
3211 | };
3212 | console.log(obj.innerMessage());
3213 | ```
3214 |
3215 | 1. Type Error
3216 | 2. 'Hello'
3217 | 3. undefined
3218 | 4. ReferenceError: self.message is not defined
3219 |
3220 | Answer
3221 |
3222 | 2) 'Hello'
3223 |
3224 |
3225 |
3226 | ### 6. What would be the output of following code ?
3227 |
3228 | ```javascript
3229 | function myFunc(){
3230 | console.log(this.message);
3231 | }
3232 | myFunc.message = "Hi John";
3233 |
3234 | console.log(myFunc());
3235 | ```
3236 |
3237 | 1. Type Error
3238 | 2. 'Hi John'
3239 | 3. undefined
3240 | 4. ReferenceError: this.message is not defined
3241 |
3242 | Answer
3243 |
3244 | 3) undefined
3245 |
3246 |
3247 |
3248 | ### 7. What would be the output of following code ?
3249 |
3250 | ```javascript
3251 | function myFunc(){
3252 | console.log(myFunc.message);
3253 | }
3254 | myFunc.message = "Hi John";
3255 |
3256 | console.log(myFunc());
3257 | ```
3258 |
3259 | 1. Type Error
3260 | 2. 'Hi John'
3261 | 3. undefined
3262 | 4. ReferenceError: this.message is not defined
3263 |
3264 | Answer
3265 |
3266 | 2) 'Hi John'
3267 |
3268 |
3269 |
3270 | ### 8. What would be the output of following code ?
3271 |
3272 | ```javascript
3273 | function myFunc() {
3274 | myFunc.message = 'Hi John';
3275 | console.log(myFunc.message);
3276 | }
3277 | console.log(myFunc());
3278 | ```
3279 |
3280 | 1. Type Error
3281 | 2. 'Hi John'
3282 | 3. undefined
3283 | 4. ReferenceError: this.message is not defined
3284 |
3285 | Answer
3286 |
3287 | 2) 'Hi John'
3288 |
3289 |
3290 |
3291 | ### 9. What would be the output of following code ?
3292 |
3293 | ```javascript
3294 | function myFunc(param1,param2) {
3295 | console.log(myFunc.length);
3296 | }
3297 | console.log(myFunc());
3298 | console.log(myFunc("a","b"));
3299 | console.log(myFunc("a","b","c","d"));
3300 | ```
3301 |
3302 | 1. 2 2 2
3303 | 2. 0 2 4
3304 | 3. undefined
3305 | 4. ReferenceError
3306 |
3307 | Answer
3308 |
3309 | a) 2 2 2
3310 |
3311 |
3312 |
3313 | ### 10. What would be the output of following code ?
3314 |
3315 | ```javascript
3316 | function myFunc() {
3317 | console.log(arguments.length);
3318 | }
3319 | console.log(myFunc());
3320 | console.log(myFunc("a","b"));
3321 | console.log(myFunc("a","b","c","d"));
3322 | ```
3323 |
3324 | 1. 2 2 2
3325 | 2. 0 2 4
3326 | 3. undefined
3327 | 4. ReferenceError
3328 |
3329 | Answer
3330 |
3331 | 2) 0 2 4
3332 |
3333 |
3334 |
3335 | ## Object Oriented
3336 |
3337 | ### 1. What would be the output of following code ?
3338 |
3339 | ```javascript
3340 | function Person(name, age){
3341 | this.name = name || "John";
3342 | this.age = age || 24;
3343 | this.displayName = function(){
3344 | console.log(this.name);
3345 | }
3346 | }
3347 |
3348 | Person.name = "John";
3349 | Person.displayName = function(){
3350 | console.log(this.name);
3351 | }
3352 |
3353 | var person1 = new Person('John');
3354 | person1.displayName();
3355 | Person.displayName();
3356 | ```
3357 |
3358 | 1. John Person
3359 | 2. John John
3360 | 3. John undefined
3361 | 4. John John
3362 |
3363 | Answer
3364 |
3365 | 1) John Person
3366 |
3367 |
3368 |
3369 | ## Scopes
3370 |
3371 | ### 1. What would be the output of following code ?
3372 |
3373 | ```javascript
3374 | function passWordMngr() {
3375 | var password = '12345678';
3376 | this.userName = 'John';
3377 | return {
3378 | pwd: password
3379 | };
3380 | }
3381 | // Block End
3382 | var userInfo = passWordMngr();
3383 | console.log(userInfo.pwd);
3384 | console.log(userInfo.userName);
3385 | ```
3386 |
3387 | 1. 12345678 Window
3388 | 2. 12345678 John
3389 | 3. 12345678 undefined
3390 | 4. undefined undefined
3391 |
3392 | Answer
3393 |
3394 | 3) 12345678 undefined
3395 |
3396 |
3397 |
3398 | ### 2. What would be the output of following code ?
3399 |
3400 | ```javascript
3401 | var employeeId = 'aq123';
3402 | function Employee() {
3403 | this.employeeId = 'bq1uy';
3404 | }
3405 | console.log(Employee.employeeId);
3406 | ```
3407 |
3408 | 1. Reference Error
3409 | 2. aq123
3410 | 3. bq1uy
3411 | 4. undefined
3412 |
3413 | Answer
3414 |
3415 | 4) undefined
3416 |
3417 |
3418 |
3419 | ### 3. What would be the output of following code ?
3420 |
3421 | ```javascript
3422 | var employeeId = 'aq123';
3423 |
3424 | function Employee() {
3425 | this.employeeId = 'bq1uy';
3426 | }
3427 | console.log(new Employee().employeeId);
3428 | Employee.prototype.employeeId = 'kj182';
3429 | Employee.prototype.JobId = '1BJKSJ';
3430 | console.log(new Employee().JobId);
3431 | console.log(new Employee().employeeId);
3432 | ```
3433 |
3434 | 1. bq1uy 1BJKSJ bq1uy undefined
3435 | 2. bq1uy 1BJKSJ bq1uy
3436 | 3. bq1uy 1BJKSJ kj182
3437 | 4. undefined 1BJKSJ kj182
3438 |
3439 | Answer
3440 |
3441 | 2) bq1uy 1BJKSJ bq1uy
3442 |
3443 |
3444 |
3445 | ### 4. What would be the output of following code ?
3446 |
3447 | ```javascript
3448 | var employeeId = 'aq123';
3449 | (function Employee() {
3450 | try {
3451 | throw 'foo123';
3452 | } catch (employeeId) {
3453 | console.log(employeeId);
3454 | }
3455 | console.log(employeeId);
3456 | }());
3457 | ```
3458 |
3459 | 1. foo123 aq123
3460 | 2. foo123 foo123
3461 | 3. aq123 aq123
3462 | 4. foo123 undefined
3463 |
3464 | Answer
3465 |
3466 | 1) foo123 aq123
3467 |
3468 |
3469 |
3470 | ## Call, Apply, Bind
3471 |
3472 | ### 1. What would be the output of following code ?
3473 |
3474 | ```javascript
3475 | (function() {
3476 | var greet = 'Hello World';
3477 | var toGreet = [].filter.call(greet, function(element, index) {
3478 | return index > 5;
3479 | });
3480 | console.log(toGreet);
3481 | }());
3482 | ```
3483 |
3484 | 1. Hello World
3485 | 2. undefined
3486 | 3. World
3487 | 4. [ 'W', 'o', 'r', 'l', 'd' ]
3488 |
3489 | Answer
3490 |
3491 | 4) [ 'W', 'o', 'r', 'l', 'd' ]
3492 |
3493 |
3494 |
3495 | ### 2. What would be the output of following code ?
3496 |
3497 | ```javascript
3498 | (function() {
3499 | var fooAccount = {
3500 | name: 'John',
3501 | amount: 4000,
3502 | deductAmount: function(amount) {
3503 | this.amount -= amount;
3504 | return 'Total amount left in account: ' + this.amount;
3505 | }
3506 | };
3507 | var barAccount = {
3508 | name: 'John',
3509 | amount: 6000
3510 | };
3511 | var withdrawAmountBy = function(totalAmount) {
3512 | return fooAccount.deductAmount.bind(barAccount, totalAmount);
3513 | };
3514 | console.log(withdrawAmountBy(400)());
3515 | console.log(withdrawAmountBy(300)());
3516 | }());
3517 | ```
3518 |
3519 | 1. Total amount left in account: 5600 Total amount left in account: 5300
3520 | 2. undefined undefined
3521 | 3. Total amount left in account: 3600 Total amount left in account: 3300
3522 | 4. Total amount left in account: 5600 Total amount left in account: 5600
3523 |
3524 | Answer
3525 |
3526 | 1) Total amount left in account: 5600 Total amount left in account: 5300
3527 |
3528 |
3529 |
3530 | ### 3. What would be the output of following code ?
3531 |
3532 | ```javascript
3533 | (function() {
3534 | var fooAccount = {
3535 | name: 'John',
3536 | amount: 4000,
3537 | deductAmount: function(amount) {
3538 | this.amount -= amount;
3539 | return this.amount;
3540 | }
3541 | };
3542 | var barAccount = {
3543 | name: 'John',
3544 | amount: 6000
3545 | };
3546 | var withdrawAmountBy = function(totalAmount) {
3547 | return fooAccount.deductAmount.apply(barAccount, [totalAmount]);
3548 | };
3549 | console.log(withdrawAmountBy(400));
3550 | console.log(withdrawAmountBy(300));
3551 | console.log(withdrawAmountBy(200));
3552 | }());
3553 | ```
3554 |
3555 | 1. 5600 5300 5100
3556 | 2. 3600 3300 3100
3557 | 3. 5600 3300 5100
3558 | 4. undefined undefined undefined
3559 |
3560 | Answer
3561 |
3562 | 1) 5600 5300 5100
3563 |
3564 |
3565 |
3566 | ### 4. What would be the output of following code ?
3567 |
3568 | ```javascript
3569 | (function() {
3570 | var fooAccount = {
3571 | name: 'John',
3572 | amount: 6000,
3573 | deductAmount: function(amount) {
3574 | this.amount -= amount;
3575 | return this.amount;
3576 | }
3577 | };
3578 | var barAccount = {
3579 | name: 'John',
3580 | amount: 4000
3581 | };
3582 | var withdrawAmountBy = function(totalAmount) {
3583 | return fooAccount.deductAmount.call(barAccount, totalAmount);
3584 | };
3585 | console.log(withdrawAmountBy(400));
3586 | console.log(withdrawAmountBy(300));
3587 | console.log(withdrawAmountBy(200));
3588 | }());
3589 | ```
3590 |
3591 | 1. 5600 5300 5100
3592 | 2. 3600 3300 3100
3593 | 3. 5600 3300 5100
3594 | 4. undefined undefined undefined
3595 |
3596 | Answer
3597 |
3598 | 2) 3600 3300 3100
3599 |
3600 |
3601 |
3602 | ### 5. What would be the output of following code ?
3603 |
3604 | ```javascript
3605 | (function greetNewCustomer() {
3606 | console.log('Hello ' + this.name);
3607 | }.bind({
3608 | name: 'John'
3609 | })());
3610 | ```
3611 |
3612 | 1. Hello John
3613 | 2. Reference Error
3614 | 3. Window
3615 | 4. undefined
3616 |
3617 | Answer
3618 |
3619 | 1) Hello John
3620 |
3621 |
3622 |
3623 | ### 6. Suggest your question!
3624 |
3625 |
3626 | ## Callback Functions
3627 |
3628 | ### 1. What would be the output of following code ?
3629 |
3630 | ```javascript
3631 | function getDataFromServer(apiUrl){
3632 | var name = "John";
3633 | return {
3634 | then : function(fn){
3635 | fn(name);
3636 | }
3637 | }
3638 | }
3639 |
3640 | getDataFromServer('www.google.com').then(function(name){
3641 | console.log(name);
3642 | });
3643 |
3644 | ```
3645 |
3646 | 1. John
3647 | 2. undefined
3648 | 3. Reference Error
3649 | 4. fn is not defined
3650 |
3651 | Answer
3652 |
3653 | 1) John
3654 |
3655 |
3656 |
3657 | ### 2. What would be the output of following code ?
3658 |
3659 | ```javascript
3660 | (function(){
3661 | var arrayNumb = [2, 8, 15, 16, 23, 42];
3662 | Array.prototype.sort = function(a,b){
3663 | return a - b;
3664 | };
3665 | arrayNumb.sort();
3666 | console.log(arrayNumb);
3667 | })();
3668 |
3669 | (function(){
3670 | var numberArray = [2, 8, 15, 16, 23, 42];
3671 | numberArray.sort(function(a,b){
3672 | if(a == b){
3673 | return 0;
3674 | }else{
3675 | return a < b ? -1 : 1;
3676 | }
3677 | });
3678 | console.log(numberArray);
3679 | })();
3680 |
3681 | (function(){
3682 | var numberArray = [2, 8, 15, 16, 23, 42];
3683 | numberArray.sort(function(a,b){
3684 | return a-b;
3685 | });
3686 | console.log(numberArray);
3687 | })();
3688 | ```
3689 |
3690 | 1. [ 2, 8, 15, 16, 23, 42 ]
3691 | [ 2, 8, 15, 16, 23, 42 ]
3692 | [ 2, 8, 15, 16, 23, 42 ]
3693 | 2. undefined undefined undefined
3694 | 3. [42, 23, 16, 15, 8, 2]
3695 | [42, 23, 16, 15, 8, 2]
3696 | [42, 23, 16, 15, 8, 2]
3697 | 4. Reference Error
3698 |
3699 | Answer
3700 |
3701 | 1) [ 2, 8, 15, 16, 23, 42 ]
3702 | [ 2, 8, 15, 16, 23, 42 ]
3703 | [ 2, 8, 15, 16, 23, 42 ]
3704 |
3705 |
3706 |
3707 | ## Return Statement
3708 |
3709 | ### 1. What would be the output of following code ?
3710 |
3711 | ```javascript
3712 | (function(){
3713 | function sayHello(){
3714 | var name = "Hi John";
3715 | return
3716 | {
3717 | fullName: name
3718 | }
3719 | }
3720 | console.log(sayHello().fullName);
3721 | })();
3722 | ```
3723 |
3724 | 1. Hi John
3725 | 2. undefined
3726 | 3. Reference Error
3727 | 4. Uncaught TypeError: Cannot read property 'fullName' of undefined
3728 |
3729 | Answer
3730 |
3731 | 4) Uncaught TypeError: Cannot read property 'fullName' of undefined
3732 |
3733 |
3734 |
3735 | ### 2. What would be the output of following code ?
3736 |
3737 | ```javascript
3738 | function getNumber(){
3739 | return (2,4,5);
3740 | }
3741 |
3742 | var numb = getNumber();
3743 | console.log(numb);
3744 | ```
3745 |
3746 | 1. 5
3747 | 2. undefined
3748 | 3. 2
3749 | 4. (2,4,5)
3750 |
3751 | Answer
3752 |
3753 | 1) 5
3754 |
3755 |
3756 |
3757 | ### 3. What would be the output of following code ?
3758 |
3759 | ```javascript
3760 | function getNumber(){
3761 | return;
3762 | }
3763 |
3764 | var numb = getNumber();
3765 | console.log(numb);
3766 | ```
3767 |
3768 | 1. null
3769 | 2. undefined
3770 | 3. ""
3771 | 4. 0
3772 |
3773 | Answer
3774 |
3775 | 2) undefined
3776 |
3777 |
3778 |
3779 | ### 4. What would be the output of following code ?
3780 |
3781 | ```javascript
3782 | function mul(x){
3783 | return function(y){
3784 | return [x*y, function(z){
3785 | return x*y + z;
3786 | }];
3787 | }
3788 | }
3789 |
3790 | console.log(mul(2)(3)[0]);
3791 | console.log(mul(2)(3)[1](4));
3792 | ```
3793 |
3794 | 1. 6, 10
3795 | 2. undefined undefined
3796 | 3. Reference Error
3797 | 4. 10, 6
3798 |
3799 | Answer
3800 |
3801 | 1) 6, 10
3802 |
3803 |
3804 |
3805 | ### 5. What would be the output of following code ?
3806 |
3807 | ```javascript
3808 | function mul(x) {
3809 | return function(y) {
3810 | return {
3811 | result: x * y,
3812 | sum: function(z) {
3813 | return x * y + z;
3814 | }
3815 | };
3816 | };
3817 | }
3818 | console.log(mul(2)(3).result);
3819 | console.log(mul(2)(3).sum(4));
3820 | ```
3821 |
3822 | 1. 6, 10
3823 | 2. undefined undefined
3824 | 3. Reference Error
3825 | 4. 10, 6
3826 |
3827 | Answer
3828 |
3829 | 1) 6, 10
3830 |
3831 |
3832 |
3833 | ### 6. What would be the output of following code ?
3834 |
3835 | ```javascript
3836 | function mul(x) {
3837 | return function(y) {
3838 | return function(z) {
3839 | return function(w) {
3840 | return function(p) {
3841 | return x * y * z * w * p;
3842 | };
3843 | };
3844 | };
3845 | };
3846 | }
3847 | console.log(mul(2)(3)(4)(5)(6));
3848 | ```
3849 |
3850 | 1. 720
3851 | 2. undefined
3852 | 3. Reference Error
3853 | 4. Type Error
3854 |
3855 | Answer
3856 |
3857 | 1) 720
3858 |
3859 |
3860 |
3861 | ### 7. What would be the output of following code ?
3862 |
3863 | ```javascript
3864 | function getName1(){
3865 | console.log(this.name);
3866 | }
3867 |
3868 | Object.prototype.getName2 = () =>{
3869 | console.log(this.name)
3870 | }
3871 |
3872 | let personObj = {
3873 | name:"Tony",
3874 | print:getName1
3875 | }
3876 |
3877 | personObj.print();
3878 | personObj.getName2();
3879 | ```
3880 |
3881 | 1. undefined undefined
3882 | 2. Tony undefined
3883 | 3. undefined Tony
3884 | 4. Tony Tony
3885 |
3886 | Answer
3887 |
3888 | 2) Tony undefined
3889 |
3890 | 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:
3891 |
3892 | ```javascript
3893 | function getName1(){
3894 | console.log(this.name);
3895 | }
3896 |
3897 | Object.prototype.getName2 = () =>{
3898 | console.log(Object.getPrototypeOf(this).name);
3899 | }
3900 |
3901 | let personObj = {
3902 | name:"Tony",
3903 | print:getName1
3904 | }
3905 |
3906 | personObj.print();
3907 | Object.prototype.name="Steve";
3908 | personObj.getName2();
3909 | ```
3910 |
3911 |
3912 |
3913 | ### 8 . What would be the output of the following code ?
3914 | ```javascript
3915 | let a = true;
3916 | let c = 0;
3917 |
3918 | setTimeout(() => {
3919 | a = false;
3920 | },2000)
3921 |
3922 | while(a){
3923 | console.log('Hello')
3924 | }
3925 | ```
3926 | Answer
3927 | 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.
3928 |
3929 |
3930 | ### 9 . What would be the output of the following code ?
3931 | ```javascript
3932 |
3933 | let c=0;
3934 |
3935 | let id = setInterval(() => {
3936 | console.log(c++)
3937 | },200)
3938 |
3939 | setTimeout(() => {
3940 | clearInterval(id)
3941 | },2000)
3942 | ```
3943 |
3944 | Answer
3945 | The above program will print 0 to 9 sequentially.
3946 |
3947 |
3948 | ## Contributing
3949 |
3950 | 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.
3951 |
3952 |
3953 | ## License
3954 |
3955 | This book is released under a Creative Commons Attribution-Noncommercial- No Derivative Works 3.0 United States License.
3956 |
3957 | 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.
3958 |
3959 | Copyright Iurii Katkov and Nishant Kumar, 2017.
3960 |
--------------------------------------------------------------------------------
/coverPage.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hogan-tech/123-Essential-JavaScript-Interview-Questions/425d87750b3804f61a3c72ce320024fa4d1f59a4/coverPage.png
--------------------------------------------------------------------------------