├── LICENSE ├── README.md └── mozilla.md /LICENSE: -------------------------------------------------------------------------------- 1 | CC0 1.0 Universal 2 | 3 | Statement of Purpose 4 | 5 | The laws of most jurisdictions throughout the world automatically confer 6 | exclusive Copyright and Related Rights (defined below) upon the creator and 7 | subsequent owner(s) (each and all, an "owner") of an original work of 8 | authorship and/or a database (each, a "Work"). 9 | 10 | Certain owners wish to permanently relinquish those rights to a Work for the 11 | purpose of contributing to a commons of creative, cultural and scientific 12 | works ("Commons") that the public can reliably and without fear of later 13 | claims of infringement build upon, modify, incorporate in other works, reuse 14 | and redistribute as freely as possible in any form whatsoever and for any 15 | purposes, including without limitation commercial purposes. These owners may 16 | contribute to the Commons to promote the ideal of a free culture and the 17 | further production of creative, cultural and scientific works, or to gain 18 | reputation or greater distribution for their Work in part through the use and 19 | efforts of others. 20 | 21 | For these and/or other purposes and motivations, and without any expectation 22 | of additional consideration or compensation, the person associating CC0 with a 23 | Work (the "Affirmer"), to the extent that he or she is an owner of Copyright 24 | and Related Rights in the Work, voluntarily elects to apply CC0 to the Work 25 | and publicly distribute the Work under its terms, with knowledge of his or her 26 | Copyright and Related Rights in the Work and the meaning and intended legal 27 | effect of CC0 on those rights. 28 | 29 | 1. Copyright and Related Rights. A Work made available under CC0 may be 30 | protected by copyright and related or neighboring rights ("Copyright and 31 | Related Rights"). Copyright and Related Rights include, but are not limited 32 | to, the following: 33 | 34 | i. the right to reproduce, adapt, distribute, perform, display, communicate, 35 | and translate a Work; 36 | 37 | ii. moral rights retained by the original author(s) and/or performer(s); 38 | 39 | iii. publicity and privacy rights pertaining to a person's image or likeness 40 | depicted in a Work; 41 | 42 | iv. rights protecting against unfair competition in regards to a Work, 43 | subject to the limitations in paragraph 4(a), below; 44 | 45 | v. rights protecting the extraction, dissemination, use and reuse of data in 46 | a Work; 47 | 48 | vi. database rights (such as those arising under Directive 96/9/EC of the 49 | European Parliament and of the Council of 11 March 1996 on the legal 50 | protection of databases, and under any national implementation thereof, 51 | including any amended or successor version of such directive); and 52 | 53 | vii. other similar, equivalent or corresponding rights throughout the world 54 | based on applicable law or treaty, and any national implementations thereof. 55 | 56 | 2. Waiver. To the greatest extent permitted by, but not in contravention of, 57 | applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and 58 | unconditionally waives, abandons, and surrenders all of Affirmer's Copyright 59 | and Related Rights and associated claims and causes of action, whether now 60 | known or unknown (including existing as well as future claims and causes of 61 | action), in the Work (i) in all territories worldwide, (ii) for the maximum 62 | duration provided by applicable law or treaty (including future time 63 | extensions), (iii) in any current or future medium and for any number of 64 | copies, and (iv) for any purpose whatsoever, including without limitation 65 | commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes 66 | the Waiver for the benefit of each member of the public at large and to the 67 | detriment of Affirmer's heirs and successors, fully intending that such Waiver 68 | shall not be subject to revocation, rescission, cancellation, termination, or 69 | any other legal or equitable action to disrupt the quiet enjoyment of the Work 70 | by the public as contemplated by Affirmer's express Statement of Purpose. 71 | 72 | 3. Public License Fallback. Should any part of the Waiver for any reason be 73 | judged legally invalid or ineffective under applicable law, then the Waiver 74 | shall be preserved to the maximum extent permitted taking into account 75 | Affirmer's express Statement of Purpose. In addition, to the extent the Waiver 76 | is so judged Affirmer hereby grants to each affected person a royalty-free, 77 | non transferable, non sublicensable, non exclusive, irrevocable and 78 | unconditional license to exercise Affirmer's Copyright and Related Rights in 79 | the Work (i) in all territories worldwide, (ii) for the maximum duration 80 | provided by applicable law or treaty (including future time extensions), (iii) 81 | in any current or future medium and for any number of copies, and (iv) for any 82 | purpose whatsoever, including without limitation commercial, advertising or 83 | promotional purposes (the "License"). The License shall be deemed effective as 84 | of the date CC0 was applied by Affirmer to the Work. Should any part of the 85 | License for any reason be judged legally invalid or ineffective under 86 | applicable law, such partial invalidity or ineffectiveness shall not 87 | invalidate the remainder of the License, and in such case Affirmer hereby 88 | affirms that he or she will not (i) exercise any of his or her remaining 89 | Copyright and Related Rights in the Work or (ii) assert any associated claims 90 | and causes of action with respect to the Work, in either case contrary to 91 | Affirmer's express Statement of Purpose. 92 | 93 | 4. Limitations and Disclaimers. 94 | 95 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 96 | surrendered, licensed or otherwise affected by this document. 97 | 98 | b. Affirmer offers the Work as-is and makes no representations or warranties 99 | of any kind concerning the Work, express, implied, statutory or otherwise, 100 | including without limitation warranties of title, merchantability, fitness 101 | for a particular purpose, non infringement, or the absence of latent or 102 | other defects, accuracy, or the present or absence of errors, whether or not 103 | discoverable, all to the greatest extent permissible under applicable law. 104 | 105 | c. Affirmer disclaims responsibility for clearing rights of other persons 106 | that may apply to the Work or any use thereof, including without limitation 107 | any person's Copyright and Related Rights in the Work. Further, Affirmer 108 | disclaims responsibility for obtaining any necessary consents, permissions 109 | or other rights required for any use of the Work. 110 | 111 | d. Affirmer understands and acknowledges that Creative Commons is not a 112 | party to this document and has no duty or obligation with respect to this 113 | CC0 or use of the Work. 114 | 115 | For more information, please see 116 | 117 | 118 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JavaScript Interview Questions 2 | 3 | 📝 [25 Essential JavaScript Interview Questions](http://www.toptal.com/javascript/interview-questions) 4 | 5 | - - - 6 | 7 | 💬 **What is a potential pitfall with using `typeof bar === "object"` to determine if bar is an object? How can this pitfall be avoided?** 8 | > `#scope` `#type` `#variable` `#null` `#undefined` 9 | 10 | 💡 typeof `null` is `object` 11 | ```js 12 | (bar !== null) && (typeof bar === "object") 13 | ``` 14 | 15 | - - - 16 | 17 | 💬 **What will the code below output to the console and why?** 18 | ```js 19 | (function(){ 20 | var a = b = 3; 21 | })(); 22 | 23 | console.log("a defined? " + (typeof a !== 'undefined')); 24 | console.log("b defined? " + (typeof b !== 'undefined')); 25 | ``` 26 | > `#function_invocation` `#variable` `#scope` `#use_strict` 27 | 28 | 💡 `b` be defined outside of the scope of the enclosing function, try `"use strict";` to reveal error. 29 | ```js 30 | a defined? false 31 | b defined? true 32 | ``` 33 | 34 | - - - 35 | 36 | 💬 **What will the code below output to the console and why?** 37 | ```js 38 | var myObject = { 39 | foo: "bar", 40 | func: function() { 41 | var self = this; 42 | console.log("outer func: this.foo = " + this.foo); 43 | console.log("outer func: self.foo = " + self.foo); 44 | (function() { 45 | console.log("inner func: this.foo = " + this.foo); 46 | console.log("inner func: self.foo = " + self.foo); 47 | }()); 48 | } 49 | }; 50 | myObject.func(); 51 | ``` 52 | > `#closure` `#scope` `#this` `#self` `#function_invocation` 53 | 54 | 💡 'this' is inner function which foo never defined 55 | ```js 56 | outer func: this.foo = bar 57 | outer func: self.foo = bar 58 | inner func: this.foo = undefined 59 | inner func: self.foo = bar 60 | ``` 61 | 62 | - - - 63 | 64 | 💬 **What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?** 65 | > `#closure` `#scope` `#this` `#self` `#function_invocation` 66 | 67 | 💡 Avoid conflict from other modules and libraries e.g. 68 | ```js 69 | // pass jQuery in as $ 70 | (function($) { /* $ can be use */ } )(jQuery); 71 | ``` 72 | or with ready `#noConflict` 73 | ```js 74 | // release $ from other 75 | $.noConflict(); 76 | // wait for document reay and accept argument as $ and use it 77 | jQuery(document).ready(function($){/* $ can be use */}); 78 | ``` 79 | 80 | 💬 **What is the significance, and what are the benefits, of including 'use strict' at the beginning of a JavaScript source file?** 81 | > `#use_strict` `#global_variable` 82 | 83 | 💡 It's best practice to be more strict instead of failed silently. 84 | * **Makes debugging easier** : Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions, alerting you sooner to problems in your code and directing you more quickly to their source. 85 | * **Prevents accidental globals** : Without strict mode, assigning a value to an undeclared variable automatically creates a global variable with that name. This is one of the most common errors in JavaScript. In strict mode, attempting to do so throws an error. 86 | * **Eliminates `this` coercion** : Without strict mode, a reference to a this value of null or undefined is automatically coerced to the global. This can cause many headfakes and pull-out-your-hair kind of bugs. In strict mode, referencing a `this` value of null or undefined throws an error. 87 | * **Disallows duplicate property names or parameter values** : Strict mode throws an error when it detects a duplicate named property in an object (e.g., `var object = {foo: "bar", foo: "baz"};`) or a duplicate named argument for a function (e.g., `function foo(val1, val2, val1){}`), thereby catching what is almost certainly a bug in your code that you might otherwise have wasted lots of time tracking down. 88 | * **Makes eval() safer** : There are some differences in the way `eval()` behaves in strict mode and in non-strict mode. Most significantly, in strict mode, variables and functions declared inside of an eval() statement are not created in the containing scope (they are created in the containing scope in non-strict mode, which can also be a common source of problems). 89 | * **Throws error on invalid usage of delete** : The `delete` operator (used to remove properties from objects) cannot be used on non-configurable properties of the object. Non-strict code will fail silently when an attempt is made to delete a non-configurable property, whereas strict mode will throw an error in such a case. 90 | 91 | - - - 92 | 93 | 💬 **Consider the two functions below. Will they both return the same thing? Why or why not?** 94 | ```js 95 | function foo1() 96 | { 97 | return { 98 | bar: "hello" 99 | }; 100 | } 101 | 102 | function foo2() 103 | { 104 | return 105 | { 106 | bar: "hello" 107 | }; 108 | } 109 | 110 | console.log("foo1 : " + foo1()); 111 | console.log("foo2 : " + foo2()); 112 | ``` 113 | > `#pitfall` 114 | 💡 It'll see as `return;` because `;` are optional. 115 | ```js 116 | foo1 :[object Object] 117 | foo2 : undefined 118 | ``` 119 | - - - 120 | 121 | 💬 **What is `NaN`? What is its type? How can you reliably test if a value is equal to `NaN`?** 122 | 123 | > `#pitfall` `#Number` `#NaN` 124 | 125 | 💡 Stand for `Not a Number` but beware `typeof NaN === "number"` is `true` 126 | ```js 127 | // 128 | isNaN(NaN); // true 129 | isNaN(undefined); // true 130 | isNaN({}); // true 131 | 132 | isNaN(true); // false 133 | isNaN(null); // false 134 | isNaN(37); // false 135 | 136 | // strings 137 | isNaN("37"); // false: "37" is converted to the number 37 which is not NaN 138 | isNaN("37.37"); // false: "37.37" is converted to the number 37.37 which is not NaN 139 | isNaN(""); // false: the empty string is converted to 0 which is not NaN 140 | isNaN(" "); // false: a string with spaces is converted to 0 which is not NaN 141 | 142 | // dates 143 | isNaN(new Date()); // false 144 | isNaN(new Date().toString()); // true 145 | 146 | // This is a false positive and the reason why isNaN is not entirely reliable 147 | isNaN("blabla") // true: "blabla" is converted to a number. 148 | 149 | // extra point for ES6 150 | Number.isNaN(NaN); 151 | ``` 152 | 📎 [isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Confusing_special-case_behavior) 153 | 154 | - - - 155 | 156 | 💬 **What will the code below output? Explain your answer.** 157 | 158 | ```js 159 | console.log(0.1 + 0.2); 160 | console.log(0.1 + 0.2 == 0.3); 161 | ``` 162 | 163 | > `#pitfall` `#Number` 164 | 165 | 💡 Stand for `Not a Number` but beware `typeof NaN === "number"` is `true` 166 | ```js 167 | 0.30000000000000004 168 | false 169 | ``` 170 | 171 | - - - 172 | 173 | 💬 **Discuss possible ways to write a function isInteger(x) that determines if x is an integer.** 174 | > `#pitfall` `#Number` `#Integer` 175 | 176 | 💡 ES6 not provide `Number.isInteger()` 177 | ```js 178 | function isInteger(x) { return Math.round(x) === x; } 179 | ``` 180 | 181 | - - - 182 | 183 | 💬 **In what order will the numbers 1-4 be logged to the console when the code below is executed? Why?** 184 | ```js 185 | (function() { 186 | console.log(1); 187 | setTimeout(function(){console.log(2)}, 1000); 188 | setTimeout(function(){console.log(3)}, 0); 189 | console.log(4); 190 | })(); 191 | ``` 192 | > `#pitfall` `#async` 193 | 194 | 💡 Async will do thing after inline code. 195 | ```js 196 | 1 197 | 4 198 | 3 199 | 2 200 | ``` 201 | 202 | - - - 203 | 204 | 💬 **Write a simple function (less than 80 characters) that returns a boolean indicating whether or not a string is a [palindrome](http://www.palindromelist.net/).** 205 | 206 | > `#algorithm` 207 | 208 | 💡 Check word == reversed_word 209 | ```js 210 | function isPalindrome(str) { 211 | // trim non word and make it lower case 212 | str = str.replace(/\W/g, '').toLowerCase(); 213 | // compare with reversed text 214 | return (str == str.split('').reverse().join('')); 215 | } 216 | console.log(isPalindrome("level")); // logs 'true' 217 | console.log(isPalindrome("levels")); // logs 'false' 218 | console.log(isPalindrome("A car, a man, a maraca")); // logs 'true' 219 | ``` 220 | 221 | - - - 222 | 223 | 💬 **Write a `sum` method which will work properly when invoked using either syntax below.** 224 | ```js 225 | console.log(sum(2,3)); // Outputs 5 226 | console.log(sum(2)(3)); // Outputs 5 227 | ``` 228 | > `#algorithm` `#arguments` `#functional` 229 | 230 | 💡 Use functional programming 231 | ```js 232 | function sum(x) { 233 | if (arguments.length == 2) { 234 | return arguments[0] + arguments[1]; 235 | } else { 236 | return function(y) { return x + y; }; 237 | } 238 | } 239 | ``` 240 | or 241 | ```js 242 | function sum(x, y) { 243 | if (y !== undefined) { 244 | return x + y; 245 | } else { 246 | return function(y) { return x + y; }; 247 | } 248 | } 249 | ``` 250 | 251 | - - - 252 | 253 | 💬 **Consider the following code snippet:** 254 | ```js 255 | for (var i = 0; i < 5; i++) { 256 | var btn = document.createElement('button'); 257 | btn.appendChild(document.createTextNode('Button ' + i)); 258 | btn.addEventListener('click', function(){ console.log(i); }); 259 | document.body.appendChild(btn); 260 | } 261 | ``` 262 | (a) What gets logged to the console when the user clicks on “Button 4” and why? 263 | (b) Provide one or more alternate implementations that will work as expected. 264 | 265 | > `#closure` `#scope` 266 | 267 | 💡 `i` is `5` forever, need input i to closure function. 268 | ```js 269 | ... 270 | (function (i) { 271 | btn.addEventListener('click', function() { console.log(i); }); 272 | })(i); 273 | ... 274 | ``` 275 | - - - 276 | 277 | 💬 **What will the code below output to the console and why?** 278 | ```js 279 | var arr1 = "john".split(''); 280 | var arr2 = arr1.reverse(); 281 | var arr3 = "jones".split(''); 282 | arr2.push(arr3); 283 | console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1)); 284 | console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1)); 285 | ``` 286 | > `#array` `#referrence` 287 | 288 | 💡 Here's what happen. `silce(-1)` will pick 1 item backward which is `arr3` 289 | ```js 290 | var arr1 = "john".split(''); // arr1 = ["j","o","h","n"] 291 | var arr2 = arr1.reverse(); // arr2 = arr1 = ["n","h","o","j"] 292 | var arr3 = "jones".split(''); // arr3 = ["j","o","n","e","s"] 293 | arr2.push(arr3); // arr2 = arr1 = ["n","h","o","j",[,"j","o","n","e","s"]] 294 | ``` 295 | output 296 | ```js 297 | array 1: length=5 last=j,o,n,e,s 298 | array 2: length=5 last=j,o,n,e,s 299 | ``` 300 | - - - 301 | 302 | 💬 **What will the code below output to the console and why ?** 303 | ```js 304 | console.log(1 + "2" + "2"); 305 | console.log(1 + +"2" + "2"); 306 | console.log(1 + -"1" + "2"); 307 | console.log(+"1" + "1" + "2"); 308 | console.log( "A" - "B" + "2"); 309 | console.log( "A" - "B" + 2); 310 | ``` 311 | > `#String` `#Number``#operation` 312 | 313 | 💡 Rules : `1 + "2" = "12"` and `-"1" = -1` also last one will judge type 314 | ```js 315 | 122 316 | 32 317 | 02 318 | 112 319 | NaN2 320 | NaN 321 | ``` 322 | - - - 323 | 324 | 💬 **The following recursive code will cause a stack overflow if the array list is too large. How can you fix this and still retain the recursive pattern?** 325 | 326 | ```js 327 | var list = readHugeList(); 328 | 329 | var nextListItem = function() { 330 | var item = list.pop(); 331 | 332 | if (item) { 333 | // process the list item... 334 | nextListItem(); 335 | } 336 | }; 337 | ``` 338 | > `#recursive` `#async` 339 | 340 | 💡 Delay funcation call by `setTimeout` 341 | ```js 342 | var list = readHugeList(); 343 | 344 | var nextListItem = function() { 345 | var item = list.pop(); 346 | 347 | if (item) { 348 | // process the list item... 349 | setTimeout( nextListItem, 0); 350 | } 351 | }; 352 | ``` 353 | 354 | - - - 355 | 356 | 💬 **What is a “closure” in JavaScript? Provide an example.** 357 | > `#recursive` `#async` 358 | 359 | 💡 A closure is an inner function that has access to the variables in the outer (enclosing) function’s scope chain. 360 | ```js 361 | var x = 1; 362 | (function(y) { 363 | var i = "i"; 364 | console.log("i:" + i); 365 | console.log("x:" + x); 366 | console.log("y:" + y); 367 | (function(z) { 368 | var j = "j"; 369 | console.log("i:" + i); 370 | console.log("j:" + j); 371 | console.log("x:" + x); 372 | console.log("y:" + y); 373 | console.log("z:" + z); 374 | })(3); 375 | })(2); 376 | 377 | ``` 378 | 379 | - - - 380 | 381 | 💬 **What will be the output of the following code:** 382 | 383 | ```js 384 | for (var i = 0; i < 5; i++) { 385 | setTimeout(function() { console.log(i); }, i * 1000 ); 386 | } 387 | ``` 388 | **Explain your answer. How could the use of closures help here?** 389 | 390 | > `#closure` `#async` 391 | 392 | 💡 Only `5` is print, Need closure to cover `setTimeout` 393 | ```js 394 | for (var i = 0; i < 5; i++) { 395 | (function(i){ 396 | setTimeout(function() { console.log(i); }, i * 1000 ); 397 | })(i); 398 | } 399 | ``` 400 | 401 | - - - 402 | 403 | 💬 **What would the following lines of code output to the console?** 404 | ```js 405 | console.log("0 || 1 = "+(0 || 1)); 406 | console.log("1 || 2 = "+(1 || 2)); 407 | console.log("0 && 1 = "+(0 && 1)); 408 | console.log("1 && 2 = "+(1 && 2)); 409 | ``` 410 | > `#logic` 411 | 412 | 💡 Left to right process 413 | ```js 414 | 0 || 1 = 1 // 1 is true 415 | 1 || 2 = 1 // 1 is true 416 | 0 && 1 = 0 // 0 is false 417 | 1 && 2 = 2 // 1 is true then skip and check 2 which return 2 418 | ``` 419 | 420 | - - - 421 | 422 | 💬 **What will be the output when the following code is executed? Explain.** 423 | ```js 424 | console.log(false == '0') 425 | console.log(false === '0') 426 | ``` 427 | > `#equal` 428 | 429 | 💡 `==` is compare `value`, `===` is compare both `key` and `value` 430 | ```js 431 | true 432 | false 433 | ``` 434 | 435 | - - - 436 | 437 | 💬 **What is the output out of the following code? Explain your answer.** 438 | ```js 439 | var a={}, 440 | b={key:'b'}, 441 | c={key:'c'}; 442 | 443 | a[b]=123; 444 | a[c]=456; 445 | 446 | console.log(a[b]); 447 | ``` 448 | > `#object` 449 | 450 | 💡 `b` and `c` get convert to `[object Object]` 451 | ```js 452 | a[b]=123; // a["[object Object]"]=123; 453 | a[c]=456; // a["[object Object]"]=456; 454 | ``` 455 | so output is 456 | ```js 457 | 456 458 | ``` 459 | 460 | - - - 461 | 462 | 💬 **What will the following code output to the console, Explain your answer.** 463 | ```js 464 | console.log((function f(n){return ((n > 1) ? n * f(n-1) : n)})(10)); 465 | ``` 466 | > `#closure` 467 | 468 | 💡 The code will output the value of 10 factorial (i.e., 10!, or 3,628,800). 469 | ```js 470 | f(1): returns n, which is 1 471 | f(2): returns 2 * f(1), which is 2 472 | f(3): returns 3 * f(2), which is 6 473 | f(4): returns 4 * f(3), which is 24 474 | f(5): returns 5 * f(4), which is 120 475 | f(6): returns 6 * f(5), which is 720 476 | f(7): returns 7 * f(6), which is 5040 477 | f(8): returns 8 * f(7), which is 40320 478 | f(9): returns 9 * f(8), which is 362880 479 | f(10): returns 10 * f(9), which is 3628800 480 | ``` 481 | 482 | - - - 483 | 484 | 💬 **Consider the code snippet below. What will the console output be and why?** 485 | ```js 486 | (function(x) { 487 | return (function(y) { 488 | console.log(x); 489 | })(2) 490 | })(1); 491 | ``` 492 | > `#closure` 493 | 494 | 💡 Inner function still has access to the outer function’s variables. 495 | ``` 496 | 1 497 | ``` 498 | 499 | - - - 500 | 501 | 💬 **What will the following code output to the console and why:** 502 | ```js 503 | var hero = { 504 | _name: 'John Doe', 505 | getSecretIdentity: function (){ 506 | return this._name; 507 | } 508 | }; 509 | 510 | var stoleSecretIdentity = hero.getSecretIdentity; 511 | 512 | console.log(stoleSecretIdentity()); 513 | console.log(hero.getSecretIdentity()); 514 | ``` 515 | **What is the issue with this code and how can it be fixed.** 516 | 517 | > `#closure` `#function` `#call` `#bind` 518 | 519 | 💡 Stole `function` will miss their scope. 520 | output 521 | ```js 522 | undefined 523 | John Doe 524 | ``` 525 | Use `bind` to fix. 526 | ```js 527 | ... 528 | var stoleSecretIdentity = hero.getSecretIdentity.bind(hero); 529 | ... 530 | ``` 531 | Or temporary fix by `call` or `apply` each function with scope. 532 | ```js 533 | ... 534 | console.log(stoleSecretIdentity.call(hero)); 535 | console.log(stoleSecretIdentity.apply(hero)); 536 | ... 537 | ``` 538 | - - - 539 | 540 | 💬 **Create a function that, given a DOM Element on the page, will visit the element itself and all of its descendents (not just its immediate children). For each element visited, the function should pass that element to a provided callback function.** 541 | 542 | The arguments to the function should be: 543 | 544 | * a DOM element 545 | * a callback function (that takes a DOM element as its argument) 546 | 547 | > `#DOM` `#callback` `#traverse` 548 | 549 | 💡 Let's do it! 550 | ```js 551 | function Traverse(p_element, p_callback) { 552 | p_callback(p_element); 553 | var list = p_element.children; 554 | for (var i = 0; i < list.length; i++) { 555 | Traverse(list[i],p_callback); // recursive call 556 | } 557 | } 558 | ``` 559 | - - - 560 | 561 | 📝 [5 Typical JavaScript Interview Exercises](http://www.sitepoint.com/5-typical-javascript-interview-exercises/) 562 | 563 | - - - 564 | 565 | 💬 **Define a repeatify function on the String object. The function accepts an integer that specifies how many times the string has to be repeated. The function returns the string repeated the number of times specified. For example:** 566 | ```js 567 | console.log('hello'.repeatify(3)); // Should print hellohellohello. 568 | ``` 569 | > `#method` `#inherit` `#prototype` 570 | 571 | 💡 Define `repeatify` from `String.prototype` 572 | ```js 573 | String.prototype.repeatify = String.prototype.repeatify || function(times) { 574 | var str = ''; 575 | 576 | for (var i = 0; i < times; i++) { 577 | str += this; 578 | } 579 | 580 | return str; 581 | }; 582 | ``` 583 | 584 | - - - 585 | 586 | 💬 **What’s the result of executing this code and why.** 587 | ```js 588 | function test() { 589 | console.log(a); 590 | console.log(foo()); 591 | 592 | var a = 1; 593 | function foo() { 594 | return 2; 595 | } 596 | } 597 | test(); 598 | ``` 599 | > `#scope` 600 | 601 | 💡 `undefined` and `2` because what actually happen is 602 | ```js 603 | function test() { 604 | var a; // undefined 605 | function foo() { 606 | return 2; 607 | } 608 | 609 | console.log(a); 610 | console.log(foo()); 611 | 612 | a = 1; 613 | } 614 | 615 | test(); 616 | ``` 617 | - - - 618 | 619 | 📝 [https://blog.udemy.com/javascript-interview-questions/](JavaScript Interview Questions: A Not-So-Brief Overview To Help You Prepare) 620 | 621 | - - - 622 | 623 | 💬 **What is JavaScript?** 624 | > `#overview` 625 | 626 | 💡 JavaScript is a prototype-based, interpreted scripting language used in client-side web development to add interactivity to browser-based pages. 627 | 628 | - - - 629 | 630 | 💬 **How do you add JavaScript to a web page?** 631 | > `#overview` 632 | 633 | 💡 In `` and `` 634 | ```html 635 | /head> 636 | 637 | ``` 638 | - - - 639 | 640 | 💬 **How do you add comments in JavaScript?** 641 | > `#overview` 642 | 643 | 💡 There are two ways to add comments in JavaScript, as line comments and block comments. 644 | ```js 645 | // one line 646 | /* 647 | multi line 648 | multi line 649 | */ 650 | ``` 651 | - - - 652 | 653 | 💬 **Explain the difference between a local and a global variable, and how to declare each one.** 654 | > `#overview` `#variable` 655 | 656 | 💡 Global variable can acces every where, Local variable can be use on in their scope 657 | ```js 658 | // local 659 | var _local = "foo"; 660 | global = "bar"; 661 | ``` 662 | 663 | - - - 664 | 665 | 💬 **What are the different JavaScript data types?** 666 | > `#type` 667 | 668 | 💡 undefined, null, String, Number, Boolean, Symbol (new in ECMAScript 6), Object (Not primitive) 669 | 📝 [7 data types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures) 670 | - - - 671 | 672 | 💬 **What is the difference between a value that is undefined and a value that is null?** 673 | > `#undefined` `#null` 674 | 675 | 💡 A variable is undefined when it’s been declared without an assigned value. 676 | ```js 677 | var foo 678 | ``` 679 | - - - 680 | 681 | 💬 **Explain the `this` keyword in JavaScript.** 682 | > `#overview` `#this` 683 | 684 | 💡`this` used to reference the object in which the function is operating. 685 | 686 | - - - 687 | 688 | 💬 **What is the HTML DOM?** 689 | > `#overview` 690 | 691 | 💡 Once a web page loads, your browser generates something called a DOM, or Document Object Model, of the page. The DOM acts as as programming interface for HTML, which defines HTML properties, events, and methods. It also refers to HTML elements as objects. 692 | 693 | ![image](https://cloud.githubusercontent.com/assets/97060/9836599/e7b78410-5a49-11e5-8bee-fe58f4fac6a7.png) 694 | 695 | 📎 [DOM](http://www.w3schools.com/js/js_htmldom.asp) 696 | 697 | - - - 698 | 699 | 📝 [JavaScript interview questions and answers](http://www.techrepublic.com/blog/software-engineer/javascript-interview-questions-and-answers/) 700 | 701 | - - - 702 | 703 | 💬 **What is event bubbling?** 704 | > `#overview` `#event` 705 | 706 | 💡 Event bubbling describes the behavior of events in child and parent nodes in the Document Object Model (DOM) 707 | 708 | - - - 709 | 710 | 📝 [20 Must Know JavaScript Interview Q&As](http://www.skilledup.com/articles/20-must-know-javascript-interview-qa) 711 | 712 | - - - 713 | 714 | 💬 **What is the difference between `window.onload` and the jQuery `$(document).ready()` method? 715 | > `#overview` `#event` 716 | 717 | 💡 718 | * The `window.onload method` occurs after all the page elements have loaded(HTML, CSS, images), which can result in a delay. 719 | * The `$(document).ready()` method begins to run code as soon as the Document Object Model (DOM) is loaded, which should be faster and less prone to loading errors across different browsers. 720 | 721 | - - - 722 | 723 | 📝 [Functional JavaScript interview question](http://bahmutov.calepin.co/functional-javascript-interview-question.html) 724 | 725 | - - - 726 | 💬 **Fix this** 727 | ```js 728 | ['1', '2', '3'].map(parseFloat); 729 | //=> [1, 2, 3] 730 | ['1', '2', '3'].map(parseInt); 731 | //=> [ 1, NaN, NaN ] 732 | ``` 733 | > `#functional` 734 | 735 | 💡 It's failed because [parseInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt] function (takes string and radix)) , need to cover function. 736 | ```js 737 | ['1', '2', '3'].map(function (str) { 738 | return parseInt(str); 739 | }); 740 | ``` 741 | 742 | - - - 743 | 744 | 📝 [JavaScript Technical Interview Questions](https://www.interviewcake.com/javascript-interview-questions) 745 | 746 | - - - 747 | 💬 **If we execute this Javascript, what will the browser's console show?** 748 | ```js 749 | var text = 'outside'; 750 | function logIt(){ 751 | console.log(text); 752 | var text = 'inside'; 753 | }; 754 | logIt(); 755 | ``` 756 | > `#scope` 757 | 758 | 💡 It's `undefined` because what actually happen is 759 | ```js 760 | var text = 'outside'; 761 | function logIt(){ 762 | var text; // undefined 763 | console.log(text); 764 | text = 'inside'; 765 | }; 766 | logIt(); 767 | ``` 768 | 769 | 770 | - - - 771 | # References 772 | * http://bahmutov.calepin.co/functional-javascript-interview-question.html 773 | * http://www.skilledup.com/articles/20-must-know-javascript-interview-qa 774 | * https://www.interviewcake.com/javascript-interview-questions 775 | * https://blog.udemy.com/javascript-interview-questions/ 776 | * http://www.toptal.com/javascript/interview-questions 777 | * https://github.com/diegocard/js-questions/blob/master/questions%2FjQuery.md 778 | * http://www.sitepoint.com/5-typical-javascript-interview-exercises/ 779 | * http://www.w3schools.com/js/js_quiz.asp 780 | -------------------------------------------------------------------------------- /mozilla.md: -------------------------------------------------------------------------------- 1 | ## [MDN-JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) 2 | 3 | 📝 [Expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators) 4 | - - - 5 | ####Logical operators#### 6 | ```js 7 | var a5 = "Cat" && "Dog"; // t && t returns Dog 8 | var a7 = "Cat" && false; // t && f returns false 9 | var o5 = "Cat" || "Dog"; // t || t returns Cat 10 | var o6 = false || "Cat"; // f || t returns Cat 11 | var n3 = !"Cat"; // !t returns false 12 | ``` 13 | 📝 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model 14 | - - - 15 | ####Creating the hierarchy#### 16 | ```js 17 | function Employee() { 18 | this.name = ""; 19 | this.dept = "general"; 20 | } 21 | function Manager() { 22 | Employee.call(this); 23 | this.reports = []; 24 | } 25 | function Manager() { 26 | Employee.call(this); 27 | this.reports = []; 28 | } 29 | Manager.prototype = Object.create(Employee.prototype); 30 | 31 | function WorkerBee() { 32 | Employee.call(this); 33 | this.projects = []; 34 | } 35 | WorkerBee.prototype = Object.create(Employee.prototype); 36 | ``` 37 | ####Object properties#### 38 | ```js 39 | function Employee (name, dept) { 40 | this.name = name || ""; 41 | this.dept = dept || "general"; 42 | } 43 | function WorkerBee (projs) { 44 | this.projects = projs || []; 45 | } 46 | WorkerBee.prototype = new Employee; 47 | function Engineer (mach) { 48 | this.dept = "engineering"; 49 | this.machine = mach || ""; 50 | } 51 | Engineer.prototype = new WorkerBee; 52 | ``` 53 | ####Property inheritance revisited#### 54 | 💡 Maker every inherit name "Unknow" 55 | ```js 56 | function Employee () { 57 | this.dept = "general"; 58 | } 59 | Employee.prototype.name = ""; 60 | 61 | function WorkerBee () { 62 | this.projects = []; 63 | } 64 | WorkerBee.prototype = new Employee; 65 | 66 | var amy = new WorkerBee; 67 | 68 | Employee.prototype.name = "Unknown"; 69 | ``` 70 | **Determining instance relationships** 71 | ```js 72 | var f = new Foo(); 73 | var isTrue = (f instanceof Foo); 74 | ``` 75 | - - - 76 | 📝 [Introduction to Object-Oriented JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript) 77 | - - - 78 | ####Terminology#### 79 | **Namespace** 80 | * A container which lets developers bundle all functionality under a unique, application-specific name. 81 | 82 | **Class** 83 | * Defines the object's characteristics. A class is a template definition of an object's properties and methods. 84 | 85 | **Object** 86 | * An instance of a class. 87 | 88 | **Property** 89 | * An object characteristic, such as color. 90 | 91 | **Method** 92 | * An object capability, such as walk. It is a subroutine or function associated with a class. 93 | 94 | **Constructor** 95 | * A method called at the moment an object is instantiated. It usually has the same name as the class containing it. 96 | 97 | **Inheritance** 98 | * A class can inherit characteristics from another class. 99 | 100 | **Encapsulation** 101 | * A method of bundling the data and methods that use the data. 102 | 103 | **Abstraction** 104 | * The conjunction of an object's complex inheritance, methods, and properties must adequately reflect a reality model. 105 | 106 | **Polymorphism** 107 | * Poly means "many" and morphism means "forms". Different classes might define the same method or property. 108 | 109 | ####Custom objects#### 110 | ```js 111 | var Person = function (firstName) { 112 | this.firstName = firstName; 113 | }; 114 | 115 | Person.prototype.sayHello = function() { 116 | console.log("Hello, I'm " + this.firstName); 117 | }; 118 | 119 | var person1 = new Person("Alice"); 120 | var person2 = new Person("Bob"); 121 | 122 | // call the Person sayHello method. 123 | person1.sayHello(); // logs "Hello, I'm Alice" 124 | person2.sayHello(); // logs "Hello, I'm Bob" 125 | 126 | var helloFunction = person1.sayHello; 127 | // logs "Hello, I'm undefined" (or fails 128 | // with a TypeError in strict mode) 129 | helloFunction(); 130 | 131 | // logs "Hello, I'm Alice" 132 | helloFunction.call(person1); 133 | ``` 134 | 💡 Create empty `Student` by not call super for their `firstName` while construct 135 | ```js 136 | // Define the Person constructor 137 | var Person = function(firstName) { 138 | this.firstName = firstName; 139 | }; 140 | 141 | // Add a couple of methods to Person.prototype 142 | Person.prototype.walk = function(){ 143 | console.log("I am walking!"); 144 | }; 145 | 146 | Person.prototype.sayHello = function(){ 147 | console.log("Hello, I'm " + this.firstName); 148 | }; 149 | 150 | // Define the Student constructor 151 | function Student(firstName, subject) { 152 | // Call the parent constructor, making sure (using Function#call) 153 | // that "this" is set correctly during the call 154 | Person.call(this, firstName); 155 | 156 | // Initialize our Student-specific properties 157 | this.subject = subject; 158 | }; 159 | 160 | // Create a Student.prototype object that inherits from Person.prototype. 161 | // Note: A common error here is to use "new Person()" to create the 162 | // Student.prototype. That's incorrect for several reasons, not least 163 | // that we don't have anything to give Person for the "firstName" 164 | // argument. The correct place to call Person is above, where we call 165 | // it from Student. 166 | Student.prototype = Object.create(Person.prototype); // See note below 167 | 168 | // Set the "constructor" property to refer to Student 169 | Student.prototype.constructor = Student; 170 | 171 | // Replace the "sayHello" method 172 | Student.prototype.sayHello = function(){ 173 | console.log("Hello, I'm " + this.firstName + ". I'm studying " 174 | + this.subject + "."); 175 | }; 176 | 177 | // Add a "sayGoodBye" method 178 | Student.prototype.sayGoodBye = function(){ 179 | console.log("Goodbye!"); 180 | }; 181 | 182 | // Example usage: 183 | var student1 = new Student("Janet", "Applied Physics"); 184 | student1.sayHello(); // "Hello, I'm Janet. I'm studying Applied Physics." 185 | student1.walk(); // "I am walking!" 186 | student1.sayGoodBye(); // "Goodbye!" 187 | 188 | // Check that instanceof works correctly 189 | console.log(student1 instanceof Person); // true 190 | console.log(student1 instanceof Student); // true 191 | ``` 192 | 💡Create `Object` without `Object.create` for old browser by [polyfill/shim](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) 193 | ```js 194 | function createObject(proto) { 195 | function ctor() { } 196 | ctor.prototype = proto; 197 | return new ctor(); 198 | } 199 | 200 | // Usage: 201 | Student.prototype = createObject(Person.prototype); 202 | 203 | // Making sure that this points to the right thing regardless of how the object is instantiated can be difficult. 204 | // However, there is a simple idiom to make this easier. 205 | var Person = function(firstName) { 206 | if (this instanceof Person) { 207 | this.firstName = firstName; 208 | } else { 209 | return new Person(firstName); 210 | } 211 | } 212 | ``` 213 | --------------------------------------------------------------------------------