├── README.md ├── _config.yml ├── ajax.html ├── assets ├── console.error.png ├── console.log.png ├── console.warn.png ├── console_dir.png ├── console_log.png ├── console_table.png ├── css-dom-tree.png ├── deepcopy.png ├── html-dom-tree.png ├── javascript-stages.png ├── message.json ├── rendering-process.png ├── rendering.png └── star.png ├── browser-type.html ├── call-apply-bind.html ├── closures.html ├── create-html-elements.html ├── datatypes.html ├── dom-manipulation.html ├── es6-questions.md ├── es6 ├── async-in-es6.js └── es6-features.js ├── functions.html ├── iife-pattern.html ├── javascript-programs.md ├── miscellaneous.html ├── namespace.html ├── objects.html ├── problems ├── AllSubSetOfGivenSet.js ├── animateUsingVanillaJavascript.js ├── filterArrayBasedOnAnotherArray.js ├── flattenObject.js ├── graph.js ├── layout.md ├── lengthOfLongestSubString.js ├── maxSubArray.js ├── median_of_arr.js ├── mergeOverlappingInterval.js ├── overlapRectangle.js ├── secondLargestInArray.js ├── sequentialPromiseExecution.js ├── sortedArrayToBST.js ├── stringPermutations.js └── wordSquare.js ├── prototype.html └── regexp.html /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /ajax.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | AJAX Request in JavaScript 5 | 6 | 7 |

AJAX - Send a Request To a Server

8 | 9 |
10 | 11 | 47 | 48 | -------------------------------------------------------------------------------- /assets/console.error.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ayatoullah/javascript-interview-questions-1/1f1ef514998deb7329598f468511e72e80f33981/assets/console.error.png -------------------------------------------------------------------------------- /assets/console.log.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ayatoullah/javascript-interview-questions-1/1f1ef514998deb7329598f468511e72e80f33981/assets/console.log.png -------------------------------------------------------------------------------- /assets/console.warn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ayatoullah/javascript-interview-questions-1/1f1ef514998deb7329598f468511e72e80f33981/assets/console.warn.png -------------------------------------------------------------------------------- /assets/console_dir.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ayatoullah/javascript-interview-questions-1/1f1ef514998deb7329598f468511e72e80f33981/assets/console_dir.png -------------------------------------------------------------------------------- /assets/console_log.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ayatoullah/javascript-interview-questions-1/1f1ef514998deb7329598f468511e72e80f33981/assets/console_log.png -------------------------------------------------------------------------------- /assets/console_table.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ayatoullah/javascript-interview-questions-1/1f1ef514998deb7329598f468511e72e80f33981/assets/console_table.png -------------------------------------------------------------------------------- /assets/css-dom-tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ayatoullah/javascript-interview-questions-1/1f1ef514998deb7329598f468511e72e80f33981/assets/css-dom-tree.png -------------------------------------------------------------------------------- /assets/deepcopy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ayatoullah/javascript-interview-questions-1/1f1ef514998deb7329598f468511e72e80f33981/assets/deepcopy.png -------------------------------------------------------------------------------- /assets/html-dom-tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ayatoullah/javascript-interview-questions-1/1f1ef514998deb7329598f468511e72e80f33981/assets/html-dom-tree.png -------------------------------------------------------------------------------- /assets/javascript-stages.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ayatoullah/javascript-interview-questions-1/1f1ef514998deb7329598f468511e72e80f33981/assets/javascript-stages.png -------------------------------------------------------------------------------- /assets/message.json: -------------------------------------------------------------------------------- 1 | {"employees":[ 2 | {"name":"Shyam", "email":"shyamjaiswal@gmail.com"}, 3 | {"name":"Bob", "email":"bob32@gmail.com"}, 4 | {"name":"Jai", "email":"jai87@gmail.com"} 5 | ]} -------------------------------------------------------------------------------- /assets/rendering-process.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ayatoullah/javascript-interview-questions-1/1f1ef514998deb7329598f468511e72e80f33981/assets/rendering-process.png -------------------------------------------------------------------------------- /assets/rendering.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ayatoullah/javascript-interview-questions-1/1f1ef514998deb7329598f468511e72e80f33981/assets/rendering.png -------------------------------------------------------------------------------- /assets/star.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ayatoullah/javascript-interview-questions-1/1f1ef514998deb7329598f468511e72e80f33981/assets/star.png -------------------------------------------------------------------------------- /browser-type.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Detect Browser Type 5 | 6 | 36 | Checking browser type... 37 | 38 | -------------------------------------------------------------------------------- /call-apply-bind.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | call(), apply() and bind() function in JavaScript 5 | 6 | 78 | 79 | call(), apply() and bind() function in JavaScript 80 | 81 | 82 | -------------------------------------------------------------------------------- /closures.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Closures, Lexical Scope and Dynamic Scope 5 | 6 | 44 | 45 | Closures 46 | 47 | 48 | -------------------------------------------------------------------------------- /create-html-elements.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Dynamically creating HTML elements using Javascript 5 | 6 | 7 |
The text above has been created dynamically.
8 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /datatypes.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DataTypes in JS 5 | 6 | 72 | 73 | DataTypes in JavaScript 74 | 75 | 76 | -------------------------------------------------------------------------------- /dom-manipulation.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DOM Manipulation in JS 5 | 6 | 7 |
DOM Manipulation in JavaScript
8 |

9 | 10 |

11 | 12 | 13 | 14 |

15 | 16 | 17 | 18 | 125 | 126 | -------------------------------------------------------------------------------- /es6-questions.md: -------------------------------------------------------------------------------- 1 | # ES6 Interview Questions and Answers 2 | 3 | 4 | |Sl.No| Questions | 5 | |----|-----------------------------------------------------------------| 6 | | 01.|[Can you give an example for destructuring an object or an array?](#q-can-you-give-an-example-for-destructuring-an-object-or-an-array)| 7 | | 02.|[List out important features of es6?](#q-list-out-important-features-of-es6)| 8 | | 03.|[ES6 Template Literals offer a lot of flexibility in generating strings, can you give an example?](#q-es6-template-literals-offer-a-lot-of-flexibility-in-generating-strings-can-you-give-an-example)| 9 | | 04.|[What is the benefit of using the arrow syntax for a method in a constructor?](#q-what-is-the-benefit-of-using-the-arrow-syntax-for-a-method-in-a-constructor)| 10 | | 05.|[What are fat arrow functions? When you should not use arrow functions in ES6?](#q-what-are-fat-arrow-functions-when-you-should-not-use-arrow-functions-in-es6)| 11 | | 06.|[How does await and async works in es6?](#q-how-does-await-and-async-works-in-es6)| 12 | | 07.|[What are the benefits of using arrow function over es5 function?](#q-what-are-the-benefits-of-using-arrow-function-over-es5-function)| 13 | | 08.|[What are the differences between ES6 class and ES5 function constructors?](#q-what-are-the-differences-between-es6-class-and-es5-function-constructors)| 14 | | 09.|[What are the benefits of using spread syntax and how is it different from rest syntax?](#q-what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax)| 15 | | 10.|[What are the differences between variables created using `let`, `var` or `const`?](#q-what-are-the-differences-between-variables-created-using-let-var-or-const)|| 16 | | 11.|[What is the difference between for..in and for..of?](#q-what-is-the-difference-between-forin-and-forof)| 17 | | 12.|[What is the Temporal Dead Zone in ES6?](#q-what-is-the-temporal-dead-zone-in-es6)| 18 | | 13.|[What is the difference between ES6 Map and WeakMap?](#q-what-is-the-difference-between-es6-map-and-weakmap)| 19 | | 14.|[What are default values in destructuring assignment?](#q-what-are-default-values-in-destructuring-assignment)| 20 | | 15.|[How do you swap variables using Destructuring Assignment?](#q-how-do-you-swap-variables-using-destructuring-assignment)| 21 | | 16.|[What is the output of below spread operator array?](#q-what-is-the-output-of-below-spread-operator-array)| 22 | | 17.|[What is modules in ES6?](#q-what-is-modules-in-es6)| 23 | | 18.|[What is a trampoline function? What is it used for?](#q-what-is-a-trampoline-function-what-is-it-used-for)| 24 | | 19.|[What is the difference between Set and WeakSet in ES6?](#q-what-is-the-difference-between-set-and-weakset-in-es6)| 25 | | 20.|[What is difference between fetch() and XMLHttpRequest() in JavaScript?](#q-what-is-difference-between-fetch-and-xmlhttprequest-in-javascript)| 26 | | 21.|[What is the difference between Promise and AJAX?](#q-what-is-the-difference-between-promise-and-ajax)| 27 | | 22.|[What is use of Proxies in es6?](#q-what-is-use-of-proxies-in-es6)| 28 | | 23.|[How could you make sure a const value is garbage collected?](#q-how-could-you-make-sure-a-const-value-is-garbage-collected)| 29 | 30 |
31 | 32 | ## Q. Can you give an example for destructuring an object or an array? 33 | 34 | Destructuring is an expression available in ES6 which enables a succinct and convenient way to extract values of Objects or Arrays and place them into distinct variables. 35 | 36 | **Array Destructuring** 37 | 38 | ```javascript 39 | // Variable assignment. 40 | const foo = ['one', 'two', 'three']; 41 | const [one, two, three] = foo; 42 | 43 | console.log(one); // "one" 44 | console.log(two); // "two" 45 | console.log(three); // "three" 46 | ``` 47 | 48 | ```javascript 49 | // Swapping variables 50 | let a = 1; 51 | let b = 3; 52 | 53 | [a, b] = [b, a]; 54 | console.log(a); // 3 55 | console.log(b); // 1 56 | ``` 57 | 58 | **Object Destructuring** 59 | 60 | ```javascript 61 | // Variable assignment. 62 | const o = { p: 42, q: true }; 63 | const { p, q } = o; 64 | 65 | console.log(p); // 42 66 | console.log(q); // true 67 | ``` 68 | 69 |
70 | ↥ back to top 71 |
72 | 73 | ## Q1. List out important features of es6? 74 | 75 | **1. Template Strings** 76 | 77 | Template literals are string literals allowing embedded expressions. 78 | 79 | **Benefits** 80 | 81 | * String interpolation 82 | * Embedded expressions 83 | * Multiline strings without hacks 84 | * String formatting 85 | * String tagging for safe HTML escaping, localization and more 86 | 87 | ```javascript 88 | let greeting = `Hello World!`; 89 | 90 | // String Substitution 91 | let name = "Alex"; 92 | console.log(`Hi, ${name}!`); // Output: "Hi, Alex!" 93 | 94 | 95 | // Multiline Strings 96 | let greeting = "Hello \ 97 | World"; 98 | 99 | // Tagged Templates 100 | fn`Hello ${you}! You're looking ${adjective} today!` 101 | ``` 102 | 103 | **2. Spread Operator** 104 | Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. 105 | ```javascript 106 | function sum(x, y, z) { 107 | return x + y + z; 108 | } 109 | 110 | const numbers = [1, 2, 3]; 111 | 112 | console.log(sum(...numbers)); // 6 113 | 114 | console.log(sum.apply(null, numbers)); // 6 115 | ``` 116 | **2.1. Copying an array** 117 | 118 | ```javascript 119 | let fruits = ['Apple','Orange','Banana']; 120 | 121 | let newFruitArray = [...fruits]; 122 | 123 | console.log(copiedList); // ['Apple','Orange','Banana'] 124 | ``` 125 | **2.2. Concatenating arrays** 126 | ```javascript 127 | let arr1 = ['A', 'B', 'C']; 128 | 129 | let arr2 = ['X', 'Y', 'Z']; 130 | 131 | let result = [...arr1, ...arr2]; 132 | 133 | console.log(result); // ['A', 'B', 'C', 'X', 'Y', 'Z'] 134 | ``` 135 | **2.3. Spreading elements together with an individual element** 136 | ```javascript 137 | let fruits = ['Apple','Orange','Banana']; 138 | 139 | let newFruits = ['Cherry', ...names]; 140 | 141 | console.log(newFruits); // ['Cherry', 'Apple','Orange','Banana'] 142 | ``` 143 | **2.4. Spreading elements on function calls** 144 | ```javascript 145 | let fruits = ['Apple','Orange','Banana']; 146 | 147 | var getFruits = (f1, f2, f3) => { 148 | console.log(Fruits: ${f1}, ${f2} and ${f3}); }; 149 | 150 | getFruits(...fruits); // Fruits: Apple, Orange and Banana 151 | ``` 152 | **2.5. Spread syntax for object literals** 153 | ```javascript 154 | var obj1 = { id: 101, name: 'Jhon Doe' } 155 | var obj2 = { age: 25, country: 'USA'} 156 | 157 | const employee = { ...obj1, ...obj2 } 158 | 159 | console.log(employee); //{ "id": 101, "name": "Jhon Doe", "age": 25, "country": "USA" } 160 | ``` 161 | 162 | **3. Sets** 163 | 164 | Sets are a new object type with ES6 (ES2015) that allow to create collections of unique values. The values in a set can be either simple primitives like strings or integers, but more complex object types like object literals or arrays can also be part of a set. 165 | 166 | ```javascript 167 | let animals = new Set(); 168 | 169 | animals.add('🐷'); 170 | animals.add('🐼'); 171 | animals.add('🐢'); 172 | animals.add('🐿'); 173 | console.log(animals.size); // 4 174 | animals.add('🐼'); 175 | console.log(animals.size); // 4 176 | 177 | console.log(animals.has('🐷')); // true 178 | animals.delete('🐷'); 179 | console.log(animals.has('🐷')); // false 180 | 181 | animals.forEach(animal => { 182 | console.log(`Hey ${animal}!`); 183 | }); 184 | 185 | // Hey 🐼! 186 | // Hey 🐢! 187 | // Hey 🐿! 188 | 189 | animals.clear(); 190 | console.log(animals.size); // 0 191 | 192 | 193 | // Example 02: Pass-In Arrray 194 | let myAnimals = new Set(['🐷', '🐢', '🐷', '🐷']); 195 | 196 | myAnimals.add(['🐨', '🐑']); 197 | myAnimals.add({ name: 'Rud', type: '🐢' }); 198 | console.log(myAnimals.size); // 4 199 | 200 | myAnimals.forEach(animal => { 201 | console.log(animal); 202 | }); 203 | 204 | 205 | // 🐷 206 | // 🐢 207 | // ["🐨", "🐑"] 208 | // Object { name: "Rud", type: "🐢" } 209 | 210 | 211 | // Example 03: Strings are a valid iterable so they can also be passed-in to initialize a set 212 | console.log('Only unique characters will be in this set.'.length); // 43 213 | 214 | let sentence = new Set('Only unique characters will be in this set.'); 215 | console.log(sentence.size); // 18 216 | 217 | 218 | // Example 04: On top of using forEach on a set, for…of loops can also be used to iterate over sets 219 | let moreAnimals = new Set(['🐺', '🐴', '🐕', '🐇']); 220 | 221 | for (let animal of moreAnimals) { 222 | console.log(`Howdy ${ animal }`); 223 | } 224 | 225 | // Howdy 🐺 226 | // Howdy 🐴 227 | // Howdy 🐕 228 | // Howdy 🐇 229 | ``` 230 | **Sets: Keys and Values** 231 | 232 | Sets also have the `keys` and `values` methods, with keys being an alias for values, so both methods do exactly the same thing. Using either of these methods returns a new iterator object with the values of the set in the same order in which they were added to the set. 233 | 234 | ```javascript 235 | let partyItems = new Set(['🍕', '🍾', '🎊']); 236 | let items = partyItems.values(); 237 | 238 | console.log(items.next()); 239 | console.log(items.next()); 240 | console.log(items.next()); 241 | console.log(items.next().done); 242 | 243 | // Object { 244 | // done: false, 245 | // value: "🍕" 246 | // } 247 | 248 | // Object { 249 | // done: false, 250 | // value: "🍾" 251 | // } 252 | 253 | // Object { 254 | // done: false, 255 | // value: "🎊" 256 | // } 257 | 258 | // true 259 | ``` 260 | 261 | **4. Default Parametrs** 262 | ```javascript 263 | function add(x = 10, y = 20) { 264 | console.log(x + y); 265 | } 266 | add(30, 40); // 70 267 | ``` 268 | 269 | **5. repeat()** 270 | 271 | The `repeat()` method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. 272 | 273 | ```javascript 274 | var cat = { 275 | meow(times){ 276 | console.log("meow ".repeat(times)); 277 | } 278 | }; 279 | cat.meow(2); // meow meow 280 | ``` 281 | 282 | **6. Arrow Function (=>)** 283 | ```javascript 284 | var add = (x, y) => x + y; 285 | console.log(add(10, 20)); // 30; 286 | 287 | ``` 288 | **7. Arrow function with `this`** 289 | ```javascript 290 | var person = { 291 | first: "Alex", 292 | actions: ["bike", "hike", "ski", "surf"], 293 | printActions: function() { 294 | var _this = this; 295 | this.actions.forEach(function(action) { 296 | var str = _this.first + " likes to " + action; 297 | console.log(str); 298 | }); 299 | } 300 | }; 301 | person.printActions(); 302 | 303 | //ES-6 304 | var person = { 305 | first: "Alex", 306 | actions: ["bike", "hike", "ski", "surf"], 307 | printActions() { 308 | this.actions.forEach(action => { 309 | var str = this.first + " likes to " + action; 310 | console.log(str); 311 | }); 312 | } 313 | }; 314 | ``` 315 | 316 | **8. Destructing Assignment** 317 | ```javascript 318 | var phone = { 319 | title: "iPhone", 320 | price: 800, 321 | description: "The iPhone is a smartphone developed by Apple" 322 | }; 323 | console.log(phone.title); 324 | 325 | //ES-6 326 | var { title, price } = { 327 | title: "iPhone", 328 | price: 800, 329 | description: "The iPhone is a smartphone developed by Apple" 330 | }; 331 | console.log(title); // iPhone 332 | ``` 333 | **9. Generators** 334 | 335 | A generator is a function that can stop midway and then continue from where it stopped. In short, a generator appears to be a function but it behaves like an `iterator`. 336 | ```javascript 337 | function* generator(num) { 338 | yield num + 1; 339 | yield num + 2; 340 | yield num + 3; 341 | yield num + 4; 342 | yield num + 5; 343 | } 344 | var gen = generator(10); 345 | console.log(gen.next().value); // 11 346 | console.log(gen.next().value); // 12 347 | console.log(gen.next().value); // 13 348 | console.log(gen.next().value); // 14 349 | console.log(gen.next().value); // 15 350 | ``` 351 | 352 | **9.1. Implementing Iterables** 353 | ```javascript 354 | function * iterableObj() { 355 | yield 'This'; 356 | yield 'is'; 357 | yield 'iterable.' 358 | } 359 | for (const val of iterableObj()) { 360 | console.log(val); 361 | } 362 | 363 | // This 364 | // is 365 | // iterable. 366 | ``` 367 | **9.2 Infinite Data Streams** 368 | ```javascript 369 | function * naturalNumbers() { 370 | let num = 1; 371 | while (true) { 372 | yield num; 373 | num = num + 1 374 | } 375 | } 376 | const numbers = naturalNumbers(); 377 | console.log(numbers.next().value) // 1 378 | console.log(numbers.next().value) // 2 379 | ``` 380 | **Advantages of Generators** 381 | 382 | **a) Lazy Evaluation**: Lazy Evaluation is an evaluation model which delays the evaluation of an expression until its value is needed. 383 | **b) Memory Efficient**: We generate only the values that are needed. With normal functions, we needed to pre-generate all the values and keep them around in case we use them later. However, with generators, we can defer the computation till we need it. 384 | 385 | **10. Symbols()** 386 | 387 | They are tokens that serve as unique IDs. We create symbols via the factory function Symbol() 388 | ```javascript 389 | const symbol1 = Symbol(); 390 | const symbol2 = Symbol(42); 391 | const symbol3 = Symbol('foo'); 392 | 393 | console.log(typeof symbol1); // symbol 394 | console.log(symbol3.toString()); // Symbol(foo) 395 | console.log(Symbol('foo') === Symbol('foo')); // false 396 | ``` 397 | **Usage** 398 | 399 | Symbols primary use case is for making private object properties, which can be only of type String or Symbol (Numbers are automatically converted to Strings). 400 | 401 | ```javascript 402 | const sym = Symbol() 403 | 404 | const privateObject = { 405 | [sym]: 'Hello World' 406 | } 407 | 408 | privateObject[sym] // 'Hello World' 409 | ``` 410 | **10.1 Global Symbols** 411 | 412 | A Global Symbol Registry exists where we can store and access Global Symbols. We can use the `Symbol.for(key)` method to both create and access Global Symbols. 413 | ```javascript 414 | const sym1 = Symbol.for('hello') // If the Symbol does not exist, it's created 415 | 416 | const sym2 = Symbol.for('hello') // The Symbol exists, so it is returned 417 | 418 | sym1 === sym2 // true 419 | ``` 420 | **11. Iterator** 421 | 422 | The iterable is a interface that specifies that an object can be accessible if it implements a method who is key is `[symbol.iterator]`. 423 | ```javascript 424 | var title = 'ES6'; 425 | var iterateIt = title[Symbol.iterator](); 426 | 427 | console.log(iterateIt.next().value); //output: E 428 | console.log(iterateIt.next().value); //output: S 429 | console.log(iterateIt.next().value); //output: 6 430 | ``` 431 | 432 |
433 | ↥ back to top 434 |
435 | 436 | ## Q2. ES6 Template Literals offer a lot of flexibility in generating strings, can you give an example? 437 | 438 | Template literals help make it simple to do string interpolation, or to include variables in a string. Before ES2015, it was common to do something like this: 439 | 440 | ```javascript 441 | var person = { name: 'Tyler', age: 28 }; 442 | console.log('Hi, my name is ' + person.name + ' and I am ' + person.age + ' years old!'); 443 | // 'Hi, my name is Tyler and I am 28 years old!' 444 | ``` 445 | 446 | With template literals, you can now create that same output like this instead: 447 | 448 | ```javascript 449 | const person = { name: 'Tyler', age: 28 }; 450 | console.log(`Hi, my name is ${person.name} and I am ${person.age} years old!`); 451 | // 'Hi, my name is Tyler and I am 28 years old!' 452 | ``` 453 | 454 | Note that you use backticks, not quotes, to indicate that you are using a template literal and that you can insert expressions inside the `${}` placeholders. 455 | 456 | A second helpful use case is in creating multi-line strings. Before ES2015, you could create a multi-line string like this: 457 | 458 | ```javascript 459 | console.log('This is line one.\nThis is line two.'); 460 | // This is line one. 461 | // This is line two. 462 | ``` 463 | 464 | Or if you wanted to break it up into multiple lines in your code so you didn't have to scroll to the right in your text editor to read a long string, you could also write it like this: 465 | 466 | ```javascript 467 | console.log('This is line one.\n' + 468 | 'This is line two.'); 469 | // This is line one. 470 | // This is line two. 471 | ``` 472 | 473 | Template literals, however, preserve whatever spacing you add to them. For example, to create that same multi-line output that we created above, you can simply do: 474 | 475 | ```javascript 476 | console.log(`This is line one. 477 | This is line two.`); 478 | // This is line one. 479 | // This is line two. 480 | ``` 481 | 482 | Another use case of template literals would be to use as a substitute for templating libraries for simple variable interpolations: 483 | 484 | ```javascript 485 | const person = { name: 'Tyler', age: 28 }; 486 | document.body.innerHTML = ` 487 |
488 |

Name: ${person.name}

489 |

Name: ${person.age}

490 |
491 | ` 492 | ``` 493 | 494 |
495 | ↥ back to top 496 |
497 | 498 | ## Q3. What is the benefit of using the arrow syntax for a method in a constructor? 499 | 500 | The main advantage of using an arrow function as a method inside a constructor is that the value of `this` gets set at the time of the function creation and can't change after that. So, when the constructor is used to create a new object, `this` will always refer to that object. 501 | ```javascript 502 | const Person = function(firstName) { 503 | this.firstName = firstName; 504 | this.sayName1 = function() { console.log(this.firstName); }; 505 | this.sayName2 = () => { console.log(this.firstName); }; 506 | }; 507 | 508 | const john = new Person('John'); 509 | const dave = new Person('Dave'); 510 | 511 | john.sayName1(); // John 512 | john.sayName2(); // John 513 | 514 | // The regular function can have its 'this' value changed, but the arrow function cannot 515 | john.sayName1.call(dave); // Dave (because "this" is now the dave object) 516 | john.sayName2.call(dave); // John 517 | 518 | john.sayName1.apply(dave); // Dave (because 'this' is now the dave object) 519 | john.sayName2.apply(dave); // John 520 | 521 | john.sayName1.bind(dave)(); // Dave (because 'this' is now the dave object) 522 | john.sayName2.bind(dave)(); // John 523 | 524 | var sayNameFromWindow1 = john.sayName1; 525 | sayNameFromWindow1(); // undefined (because 'this' is now the window object) 526 | 527 | var sayNameFromWindow2 = john.sayName2; 528 | sayNameFromWindow2(); // John 529 | ``` 530 | The main takeaway here is that `this` can be changed for a normal function, but the context always stays the same for an arrow function. So even if you are passing around your arrow function to different parts of your application, you wouldn\'t have to worry about the context changing. 531 | 532 |
533 | ↥ back to top 534 |
535 | 536 | ## Q4. What are fat arrow functions? When you should not use arrow functions in ES6? 537 | 538 | An arrow function is a shorter syntax for a function expression and does not have its own **this, arguments, super, or new.target**. These function are best suited for non-method functions, and they cannot be used as constructors. 539 | 540 | 541 | **Arrow functions in ES6 has two limitations**: 542 | * Don't work with new 543 | * Fixed this bound to scope at initialisation 544 | 545 | **When should not use Arrow Functions** 546 | **1. Object methods** 547 | When you call cat.jumps, the number of lives does not decrease. It is because this is not bound to anything, and will inherit the value of this from its parent scope. 548 | ```javascript 549 | var cat = { 550 | lives: 9, 551 | jumps: () => { 552 | this.lives--; 553 | } 554 | } 555 | ``` 556 | **2. Callback functions with dynamic context** 557 | If we click the button, we would get a TypeError. It is because this is not bound to the button, but instead bound to its parent scope. 558 | ```javascript 559 | var button = document.getElementById('press'); 560 | button.addEventListener('click', () => { 561 | this.classList.toggle('on'); 562 | }); 563 | ``` 564 |
565 | ↥ back to top 566 |
567 | 568 | ## Q5. How does await and async works in es6? 569 | 570 | * **Promises** 571 | ```javascript 572 | const delay = seconds => { 573 | return new Promise(resolve => { 574 | setTimeout(resolve, seconds * 1000) 575 | }); 576 | }; 577 | 578 | console.log("Zero seconds wait"); 579 | delay(1).then(() => console.log('One seconds wait')); 580 | delay(5).then(() => console.log('Five seconds wait')); 581 | ``` 582 | * **Loading data with fetch()** 583 | ```javascript 584 | const getPeopleInSpace = () => 585 | fetch('http://api.open-notify.org/astros.json') 586 | .then(res => res.json()); 587 | 588 | getPeopleInSpace() 589 | .then(console.log); 590 | ``` 591 | * **Async() and await()** 592 | ```javascript 593 | const delay = seconds => { 594 | return new Promise( 595 | resolve => setTimeout(resolve, seconds * 1000) 596 | ) 597 | }; 598 | 599 | const countToFive = async() => { 600 | console.log('zero seconds wait'); 601 | await delay(2); 602 | console.log('Two seconds wait'); 603 | await delay(5); 604 | console.log('Five seconds wait'); 605 | } 606 | 607 | countToFive(); 608 | ``` 609 | * **Async with fetch** 610 | ```javascript 611 | const githubRequest = async(loginName) => { 612 | try{ 613 | var response = await fetch(`http://api.github.com/users/${loginName}/followers`); 614 | var json = await response.json(); 615 | var followerList = json.map(user => user.login); 616 | console.log(followerList); 617 | } catch(e){ 618 | console.log("Data didn't load", e); 619 | } 620 | }; 621 | 622 | //githubRequest('eveporcello'); 623 | githubRequest('pradeepkumar2'); 624 | ``` 625 | 626 |
627 | ↥ back to top 628 |
629 | 630 | ## Q6. What are the benefits of using arrow function over es5 function? 631 | 632 | **Arrow functions** 633 | Arrows is a new syntax for functions, which brings several benefits: 634 | 635 | * Arrow syntax automatically binds `this` to the surrounding code’s context 636 | * The syntax allows an implicit return when there is no body block, resulting in shorter and simpler code in some cases 637 | * Last but not least, `=>` is shorter and simpler than `function`, although stylistic issues are often subjective 638 | 639 | ```javascript 640 | //arrow function with no parameters 641 | var a1 = () => 1; 642 | 643 | //arrow with one parameter can be defined without parentheses 644 | var a2 = x => 1; 645 | var a3 = (x) => 1; 646 | 647 | //arrow with multiple params requires parentheses 648 | var a4 = (x, y) => 1; 649 | 650 | //arrow with body has no implicit return 651 | var a5 = x => { return 1; }; 652 | ``` 653 | 654 |
655 | ↥ back to top 656 |
657 | 658 | ## Q7. What are the differences between ES6 class and ES5 function constructors? 659 | 660 | ```javascript 661 | // ES5 Function Constructor 662 | function Person(name) { 663 | this.name = name; 664 | } 665 | 666 | // ES6 Class 667 | class Person { 668 | constructor(name) { 669 | this.name = name; 670 | } 671 | } 672 | ``` 673 | 674 | For simple constructors, they look pretty similar. 675 | 676 | The main difference in the constructor comes when using inheritance. If we want to create a `Student` class that subclasses `Person` and add a `studentId` field, this is what we have to do in addition to the above. 677 | 678 | ```javascript 679 | // ES5 Function Constructor 680 | function Student(name, studentId) { 681 | // Call constructor of superclass to initialize superclass-derived members. 682 | Person.call(this, name); 683 | 684 | // Initialize subclass's own members. 685 | this.studentId = studentId; 686 | } 687 | 688 | Student.prototype = Object.create(Person.prototype); 689 | Student.prototype.constructor = Student; 690 | 691 | // ES6 Class 692 | class Student extends Person { 693 | constructor(name, studentId) { 694 | super(name); 695 | this.studentId = studentId; 696 | } 697 | } 698 | ``` 699 | 700 | It's much more verbose to use inheritance in ES5 and the ES6 version is easier to understand and remember. 701 | 702 |
703 | ↥ back to top 704 |
705 | 706 | ## Q8. What are the benefits of using spread syntax and how is it different from rest syntax? 707 | 708 | ES6's spread syntax is very useful when coding in a functional paradigm as we can easily create copies of arrays or objects without resorting to `Object.create`, `slice`, or a library function. This language feature is used often in Redux and Rx.js projects. 709 | 710 | ```javascript 711 | function addCookiesInArray(arr) { 712 | return [...arr, 'Cookies']; 713 | } 714 | 715 | const result = addCookiesInArray(['I', 'really', "don't", 'like']); 716 | 717 | console.log(result); // ["I", "really", "don't", "like", "Cookies"] 718 | ``` 719 | 720 | ```javascript 721 | const person = { 722 | name: 'Todd', 723 | age: 29, 724 | }; 725 | 726 | const copyOfPerson = { ...person }; 727 | 728 | console.log(copyOfPerson); // {name: "Todd", age: 29} 729 | ``` 730 | 731 | ES6's rest syntax offers a shorthand for including an arbitrary number of arguments to be passed to a function. It is like an inverse of the spread syntax, taking data and stuffing it into an array rather than unpacking an array of data, and it works in function arguments, as well as in array and object destructuring assignments. 732 | 733 | ```javascript 734 | function addFiveToABunchOfNumbers(...numbers) { 735 | return numbers.map(x => x + 5); 736 | } 737 | 738 | const result = addFiveToABunchOfNumbers(4, 5, 6, 7, 8, 9, 10); // [9, 10, 11, 12, 13, 14, 15] 739 | 740 | const [a, b, ...rest] = [1, 2, 3, 4]; // a: 1, b: 2, rest: [3, 4] 741 | 742 | const { e, f, ...others } = { 743 | e: 1, 744 | f: 2, 745 | g: 3, 746 | h: 4, 747 | }; // e: 1, f: 2, others: { g: 3, h: 4 } 748 | ``` 749 |
750 | ↥ back to top 751 |
752 | 753 | ## Q9. What are the differences between variables created using `let`, `var` or `const`? 754 | 755 | Variables declared using the `var` keyword are scoped to the function in which they are created, or if created outside of any function, to the global object. `let` and `const` are _block scoped_, meaning they are only accessible within the nearest set of curly braces (function, if-else block, or for-loop). 756 | 757 | ```javascript 758 | function foo() { 759 | // All variables are accessible within functions. 760 | var bar = 'bar'; 761 | let baz = 'baz'; 762 | const qux = 'qux'; 763 | 764 | console.log(bar); // bar 765 | console.log(baz); // baz 766 | console.log(qux); // qux 767 | } 768 | 769 | console.log(bar); // ReferenceError: bar is not defined 770 | console.log(baz); // ReferenceError: baz is not defined 771 | console.log(qux); // ReferenceError: qux is not defined 772 | ``` 773 | 774 | ```javascript 775 | if (true) { 776 | var bar = 'bar'; 777 | let baz = 'baz'; 778 | const qux = 'qux'; 779 | } 780 | 781 | // var declared variables are accessible anywhere in the function scope. 782 | console.log(bar); // bar 783 | // let and const defined variables are not accessible outside of the block they were defined in. 784 | console.log(baz); // ReferenceError: baz is not defined 785 | console.log(qux); // ReferenceError: qux is not defined 786 | ``` 787 | 788 | `var` allows variables to be hoisted, meaning they can be referenced in code before they are declared. `let` and `const` will not allow this, instead throwing an error. 789 | 790 | ```javascript 791 | console.log(foo); // undefined 792 | 793 | var foo = 'foo'; 794 | console.log(baz); // ReferenceError: can't access lexical declaration 'baz' before initialization 795 | 796 | let baz = 'baz'; 797 | console.log(bar); // ReferenceError: can't access lexical declaration 'bar' before initialization 798 | 799 | const bar = 'bar'; 800 | ``` 801 | 802 | Redeclaring a variable with `var` will not throw an error, but 'let' and 'const' will. 803 | 804 | ```javascript 805 | var foo = 'foo'; 806 | var foo = 'bar'; 807 | console.log(foo); // "bar" 808 | 809 | let baz = 'baz'; 810 | let baz = 'qux'; // Uncaught SyntaxError: Identifier 'baz' has already been declared 811 | ``` 812 | 813 | `let` and `const` differ in that `let` allows reassigning the variable's value while `const` does not. 814 | 815 | ```javascript 816 | // This is fine. 817 | let foo = 'foo'; 818 | foo = 'bar'; 819 | 820 | // This causes an exception. 821 | const baz = 'baz'; 822 | baz = 'qux'; 823 | ``` 824 |
825 | ↥ back to top 826 |
827 | 828 | ## Q10. What is the difference between for..in and for..of? 829 | * **for in**: loops over enumerable property names of an object. 830 | * **for of**: (new in ES6) does use an object-specific iterator and loops over the values generated by that. 831 | 832 | Both `for..of` and `for..in` statements iterate over lists; the values iterated on are different though, `for..in` returns a **list of keys** on the object being iterated, whereas `for..of` returns a **list of values** of the numeric properties of the object being iterated. 833 | Example: 834 | ```javascript 835 | let list = [4, 5, 6]; 836 | 837 | for (let i in list) { 838 | console.log(i); // "0", "1", "2", 839 | } 840 | 841 | for (let i of list) { 842 | console.log(i); // "4", "5", "6" 843 | } 844 | ``` 845 |
846 | ↥ back to top 847 |
848 | 849 | ## Q11. What is the Temporal Dead Zone in ES6? 850 | In ES6, let bindings are not subject to Variable Hoisting, which means that let declarations do not move to the top of the current execution context. Referencing the variable in the block before the initialization results in a `ReferenceError` (contrary to a variable declared with var, which will just have the undefined value). The variable is in a “temporal dead zone” from the start of the block until the initialization is processed. 851 | 852 | ```javascript 853 | console.log(aVar); // undefined 854 | console.log(aLet); // causes ReferenceError: aLet is not defined 855 | var aVar = 1; 856 | let aLet = 2; 857 | ``` 858 | ## Q12. What is the difference between ES6 Map and WeakMap? 859 | **Map** 860 | It is used to associate a key to a value irrespective of the datatype such as strings, numbers, objects etc. To assign values to a map you need to use the set method: 861 | ```javascript 862 | window.obj = {} 863 | var map = new Map() 864 | map.set(window.obj, 123) 865 | ``` 866 | Then, to retrieve the object call get: 867 | ```javascript 868 | map.get(window.obj) // => 123 869 | ``` 870 | **WeakMap** 871 | WeakMap accepts only objects but not any primitive values (strings, numbers) 872 | ```javascript 873 | function Obj(){ 874 | this.val = new Array(10000000).join("---") 875 | } 876 | 877 | window.obj = new Obj(); 878 | var map = new WeakMap() 879 | map.set(window.obj, 123) 880 | delete window.obj 881 | ``` 882 | **Differences between Map and WeakMap** 883 | 1. A WeakMap accepts only objects as keys whereas a Map,in addition to objects, accepts primitive datatype such as strings, numbers etc. 884 | 2. WeakMap objects doesn't avert garbage collection if there are no references to the object which is acting like a key. Therefore there is no method to retrieve keys in WeakMap, whereas in Map there are methods such as Map.prototype.keys() to get the keys. 885 | 3. There is no size property exists in WeakMap. 886 | 887 | **Browser support for Map and WeakMap** 888 | The latest Chrome, Firefox, Edge and Safari support Map and WeakMap on desktop. There is no support in IE10. On mobile newer browsers also have support, but IE Mobile doesn\'t. 889 | 890 |
891 | ↥ back to top 892 |
893 | 894 | ## Q13. What are default values in destructuring assignment? 895 | 896 | A variable can be assigned a default value when the value unpacked from the array or object is undefined during destructuring assignment. It helps to avoid setting default values separately for each assignment. 897 | 898 | **Array Destructuring** 899 | ```javascript 900 | var x, y, z; 901 | 902 | [x=2, y=4, z=6] = [10]; 903 | console.log(x); // 10 904 | console.log(y); // 4 905 | console.log(z); // 6 906 | ``` 907 | 908 | **Object Destructuring** 909 | ```javascript 910 | var {x=2, y=4, z=6} = {x: 10}; 911 | 912 | console.log(x); // 10 913 | console.log(y); // 4 914 | console.log(z); // 6 915 | ``` 916 | ## Q14. How do you swap variables using Destructuring Assignment? 917 | ```javascript 918 | var x = 10, y = 20; 919 | 920 | [x, y] = [y, x]; 921 | console.log(x); // 20 922 | console.log(y); // 10 923 | ``` 924 | ## Q15. What is the output of below spread operator array? 925 | ```javascript 926 | [...'John'] 927 | ``` 928 | **Output**: ['J', 'o', 'h', 'n'] 929 | **Explanation**: The string is an iterable type and the spread operator with in an array maps every character of an iterable to one element. Hence, each character of a string becomes an element within an Array. 930 | 931 |
932 | ↥ back to top 933 |
934 | 935 | ## Q16. What is modules in ES6? 936 | 937 | To make objects, functions, classes or variables available to the outside world it’s as simple as exporting them and then importing them where needed in other files. 938 | 939 | **Benefits** 940 | 941 | * Code can be split into smaller files of self-contained functionality. 942 | * The same modules can be shared across any number of applications. 943 | * Ideally, modules need never be examined by another developer, because they’ve has been proven to work. 944 | * Code referencing a module understands it’s a dependency. If the module file is changed or moved, the problem is immediately obvious. 945 | * Module code (usually) helps eradicate naming conflicts. Function `x()` in module1 cannot clash with function x() in module2. Options such as namespacing are employed so calls become `module1.x()` and `module2.x()`. 946 | 947 | **Exporting** 948 | ```javascript 949 | export const myNumbers = [1, 2, 3, 4]; 950 | const animals = ['Panda', 'Bear', 'Eagle']; // Not available directly outside the module 951 | 952 | export function myLogger() { 953 | console.log(myNumbers, animals); 954 | } 955 | 956 | export class Alligator { 957 | constructor() { 958 | // ... 959 | } 960 | } 961 | ``` 962 | **Exporting with alias** 963 | ```javascript 964 | export { myNumbers, myLogger as Logger, Alligator } 965 | ``` 966 | **Default export** 967 | ```javascript 968 | export const myNumbers = [1, 2, 3, 4]; 969 | const animals = ['Panda', 'Bear', 'Eagle']; 970 | 971 | export default function myLogger() { 972 | console.log(myNumbers, pets); 973 | } 974 | 975 | export class Alligator { 976 | constructor() { 977 | // ... 978 | } 979 | } 980 | ``` 981 | 982 |
983 | ↥ back to top 984 |
985 | 986 | ## Q17. What is a trampoline function? What is it used for? 987 | 988 | The trampoline is just a technique to optimize **recursion** and prevent `stack-overflow` exceptions in languages that don't support tail call optimization like Javascript ES5 implementation. However, ES6 will probably have support for tail call optimization. 989 | 990 | The problem with regular recursion is that every recursive call adds a stack frame to the call stack, which you can visualize as a **pyramid** of calls. Here is a visualization of calling a factorial function recursively: 991 | ``` 992 | (factorial 3) 993 | (* 3 (factorial 2)) 994 | (* 3 (* 2 (factorial 1))) 995 | (* 3 (* 2 (* 1 (factorial 0)))) 996 | (* 3 (* 2 (* 1 1))) 997 | (* 3 (* 2 1)) 998 | (* 3 2) 999 | 6 1000 | ``` 1001 | Here is a visualization of the stack where each vertical dash is a stack frame: 1002 | ``` 1003 | ---|--- 1004 | ---| |--- 1005 | ---| |--- 1006 | --- --- 1007 | ``` 1008 | The problem is that the stack has limited size, and stacking up these stack frames can overflow the stack. Depending on the stack size, a calculation of a larger factorial would overflow the stack. That is why regular recursion in Javascript could be considered dangerous. 1009 | 1010 | An optimal execution model would be something like a **trampoline** instead of a **pyramid**, where each recursive call is executed in place, and does not stack up on the call stack. That execution in languages supporting tail call optimization could look like: 1011 | ``` 1012 | (fact 3) 1013 | (fact-tail 3 1) 1014 | (fact-tail 2 3) 1015 | (fact-tail 1 6) 1016 | (fact-tail 0 6) 1017 | 6 1018 | ``` 1019 | You can visualize the stack like a bouncing trampoline: 1020 | ``` 1021 | ---|--- ---|--- ---|--- 1022 | --- --- --- 1023 | ``` 1024 | This is clearly better since the stack has always only one frame, and from the visualization you can also see why it is called a trampoline. This prevents the stack from overflowing. 1025 | 1026 | Since we don't have the luxury of `tail call optimization` in Javascript, we need to figure out a way to turn regular recursion into an optimized version that will execute in trampoline-fashion. 1027 | 1028 | One obvious way is to **get rid of recursion**, and rewrite the code to be iterative. 1029 | 1030 | When that is not possible we need a bit more complex code where instead of executing directly the recursive steps, we will utilize `higher order functions` to return a wrapper function instead of executing the recursive step directly, and let another function control the execution. 1031 | 1032 | In your example, the **repeat** function wraps the regular recursive call with a function, and it returns that function instead of executing the recursive call: 1033 | ```javascript 1034 | function repeat(operation, num) { 1035 | return function() { 1036 | if (num <= 0) return 1037 | operation() 1038 | return repeat(operation, --num) 1039 | } 1040 | } 1041 | ``` 1042 | The returned function is the next step of recursive execution and the trampoline is a mechanism to execute these steps in a controlled and iterative fashion in the while loop: 1043 | ```javascript 1044 | function trampoline(fn) { 1045 | while(fn && typeof fn === 'function') { 1046 | fn = fn() 1047 | } 1048 | } 1049 | ``` 1050 | So the sole purpose of the trampoline function is to control the execution in an iterative way, and that ensures the stack to have only a single stack frame on the stack at any given time. 1051 | 1052 | Using a trampoline is obviously less performant than simple recursion, since you are "blocking" the normal recursive flow, but it is much safer. 1053 | 1054 |
1055 | ↥ back to top 1056 |
1057 | 1058 | ## Q18. What is the difference between Set and WeakSet in ES6? 1059 | 1060 | **Set** 1061 | 1062 | Using the `Set()` class we can create an array like heterogeneous iterable object, which will contain only unique values in it. Unique is not just unique by values but also by types. i.e. it will consider `"2"` and `2` separate or different. 1063 | 1064 | Syntax: 1065 | ```javascript 1066 | var mySet = new Set([iterable]); 1067 | ``` 1068 | Example: 1069 | ```javascript 1070 | var mySet= new Set([0,1]); 1071 | 1072 | mySet.add(2); // 0, 1, 2 1073 | mySet.add(2); // 0, 1, 2 1074 | mySet.add("Hello"); // 0, 1, 2, 'Hello' 1075 | mySet.add({a:1, b:2}); // 0, 1, 2, 'Hello', {a:1, b:2} 1076 | 1077 | mySet.add(function(){}); // 0, 1, 2, 'Hello', {a:1, b:2}, [Function] 1078 | 1079 | mySet.has("Hello"); // ture 1080 | mySet.delete("Hello"); // 'Hello' deleted 1081 | mySet.has("Hello"); // false 1082 | 1083 | mySet.size; // 5 1084 | mySet.clear(); // Set Cleared 1085 | ``` 1086 | **WeakSet** 1087 | 1088 | A `WeakSet()` is a collection similar to Set, which holds unique values; but it only holds Objects and nothing else. If an object which is there in your WeakSet object has no other reference variable left, it will automatically be deleted. 1089 | 1090 | Syntax: 1091 | ```javascript 1092 | var myWeakSet = new WeakSet([iterable with only objects]); 1093 | ``` 1094 | Example: 1095 | ```javascript 1096 | var myWeakSet = new WeakSet([{a:1}]); 1097 | var obj1 = {o:1}; 1098 | var obj2 = {o:2}; 1099 | 1100 | myWeakSet.add(obj1); 1101 | myWeakSet.has(obj1); // true 1102 | myWeakSet.has(obj2); // false 1103 | myWeakSet.add(obj2); 1104 | myWeakSet.has(obj2); // true 1105 | delete obj2; // don't take it literally. You cant delete object like that. Use scope to execute this. 1106 | myWeakSet.has(obj2); // false, cause you deleted obj2, so WeakSet releases it automatically 1107 | myWeakSet.delete(obj1); //obj1 deleted from the set 1108 | myWeakSet.add(2); // ERROR, no primitive value 1109 | ``` 1110 | |Set |WeakSet | 1111 | |-------------------------------|-------------------------------| 1112 | |Can contain any type of values | Can only contain objects | 1113 | |To find number of elements use .size |To find elements count use .length| 1114 | |.forEach() is available to iterate| No .forEach() to iterate | 1115 | |Nothing is auto destroyed |If an element object has no other reference left, it will be auto released to garbage collector| 1116 | 1117 |
1118 | ↥ back to top 1119 |
1120 | 1121 | ## Q19. What is difference between fetch() and XMLHttpRequest() in JavaScript? 1122 | 1123 | **XMLHttpRequest** 1124 | 1125 | `XMLHttpRequest()` is a built-in browser object that allows to make HTTP requests in JavaScript. XMLHttpRequest has two modes of operation: **synchronous** and **asynchronous**. 1126 | ```javascript 1127 | if (window.XMLHttpRequest) { 1128 | // code for IE7+, Firefox, Chrome, Opera, Safari 1129 | xhr = new XMLHttpRequest(); 1130 | } else { 1131 | // code for IE6, IE5 1132 | xhr = new ActiveXObject('Microsoft.XMLHTTP'); 1133 | } 1134 | 1135 | xhr.onreadystatechange = function() { 1136 | if (this.readyState == 4 && this.status == 200) { 1137 | console.log(this.responseText); 1138 | } 1139 | }; 1140 | xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true); // this makes asynchronous true or false 1141 | xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 1142 | xhr.send(); 1143 | ``` 1144 | **Fetch** 1145 | 1146 | Fetch allows to make network requests similar to `XMLHttpRequest`. Fetch makes it easier to make asynchronous requests and handle responses better than with the older XMLHttpRequest. It is an improvement over the `XMLHttpRequest` API. The main difference between `Fetch()` and `XMLHttpRequest()` is that the Fetch API uses Promises, hence avoiding **callback hell**. 1147 | 1148 | 1149 | **Fetch Interfaces** 1150 | 1151 | * **fetch()**: The fetch() method used to fetch a resource. 1152 | * **Headers**: Represents response/request headers, allows to query them and take different actions depending on the results. 1153 | * **Request**: Represents a resource request. 1154 | * **Response**: Represents the response to a request. 1155 | 1156 | **Making a request using fetch()** 1157 | 1158 | A `fetch()` function is available in the global window object. The fetch() function takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise, whether it is successful or not. If request is successful `.then()` function will receive Response object, if request fails then `.catch()` function will receive an error object 1159 | ```javascript 1160 | fetch('https://api.github.com/users/learning-zone') 1161 | .then(function (response) { 1162 | return response.json(); 1163 | }) 1164 | .then(function (data) { 1165 | console.log(data); 1166 | }) 1167 | .catch(function (err) { 1168 | console.log("Something went wrong!", err); 1169 | }); 1170 | ``` 1171 | **Headers Object** 1172 | 1173 | The Headers interface allows to create own headers object via the `Headers()` constructor. A headers object is a collection of name-value pairs. 1174 | ```javascript 1175 | let reqHeader = new Headers(); 1176 | reqHeader.append('Content-Type', 'text/json'); 1177 | let initObject = { 1178 | method: 'GET', headers: reqHeader, 1179 | }; 1180 | 1181 | fetch('https://api.github.com/users/learning-zone', initObject) 1182 | .then(function (response) { 1183 | return response.json(); 1184 | }) 1185 | .then(function (data) { 1186 | console.log(data); 1187 | }) 1188 | .catch(function (err) { 1189 | console.log("Something went wrong!", err); 1190 | }); 1191 | ``` 1192 | **Request Object** 1193 | 1194 | The Request Object represents a resource request. Instead of passing an URL of the resource into the fetch() call, you can create a request object using the Request() constructor, and pass that as an argument to fetch(). By passing Request object to the fetch(), you can make customised requests. 1195 | ```javascript 1196 | let reqHeader = new Headers(); 1197 | reqHeader.append('Content-Type', 'text/json'); 1198 | 1199 | let initObject = { 1200 | method: 'GET', headers: reqHeader, 1201 | }; 1202 | 1203 | var userRequest = new Request('https://api.github.com/users/learning-zone', initObject); 1204 | 1205 | fetch(userRequest) 1206 | .then(function (response) { 1207 | return response.json(); 1208 | }) 1209 | .then(function (data) { 1210 | console.log(data); 1211 | }) 1212 | .catch(function (err) { 1213 | console.log("Something went wrong!", err); 1214 | }); 1215 | ``` 1216 | 1217 |
1218 | ↥ back to top 1219 |
1220 | 1221 | ## Q20. What is the difference between Promise and AJAX? 1222 | 1223 | Promises are a tool for managing asynchronous operations. They keep track of when asynchronous operations complete and what their results are and let you coordinate that completion and those results (including error conditions) with other code or other asynchronous operations. They aren't actually asynchronous operations in themselves. An Ajax call is a specific asynchronous operation that can be used with with a traditional callback interface or wrapped in a promise interface. 1224 | 1225 | An Ajax call is a specific type of asynchronous operation. We can make an Ajax call either with a traditional callback using the `XMLHttpRequest()` interface or we can make an Ajax call (in modern browsers), using a promise with the `fetch()` interface. 1226 | 1227 |
1228 | ↥ back to top 1229 |
1230 | 1231 | ## Q21. What is use of Proxies in es6? 1232 | The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc). 1233 | 1234 | There are 3 key terms we need to define before we proceed: 1235 | 1236 | * **handler** — the placeholder object which contains the trap(s) 1237 | * **traps** — the method(s) that provide property access 1238 | * **target** — object which the proxy virtualizes 1239 | 1240 | Syntax 1241 | ```javascript 1242 | const p = new Proxy(target, handler) 1243 | ``` 1244 | Example: 1245 | ```javascript 1246 | const handler = { 1247 | get: function(obj, prop) { 1248 | return prop in obj ? 1249 | obj[prop] : 1250 | 37; 1251 | } 1252 | }; 1253 | 1254 | const p = new Proxy({}, handler); 1255 | p.a = 1; 1256 | p.b = undefined; 1257 | 1258 | console.log(p.a, p.b); 1259 | // 1, undefined 1260 | 1261 | console.log('c' in p, p.c); 1262 | // false, 37 1263 | ``` 1264 | 1265 | There are many real-world applications for Proxies 1266 | 1267 | * validation 1268 | * value correction 1269 | * property lookup extensions 1270 | * tracing property accesses 1271 | * revocable references 1272 | * implementing the DOM in javascript 1273 | 1274 | 1275 | #### Q22. How could you make sure a const value is garbage collected? 1276 | 1277 |
1278 | ↥ back to top 1279 |
1280 | -------------------------------------------------------------------------------- /es6/async-in-es6.js: -------------------------------------------------------------------------------- 1 | //01. Example:- Promises 2 | 3 | const delay = seconds => { 4 | return new Promise(resolve => { 5 | setTimeout(resolve, seconds * 1000) 6 | }); 7 | }; 8 | 9 | console.log("Zero seconds wait"); 10 | delay(1).then(() => console.log('One seconds wait')); 11 | delay(5).then(() => console.log('Five seconds wait')); 12 | 13 | //02. Loading data with fetch() 14 | 15 | const getPeopleInSpace = () => 16 | fetch('http://api.open-notify.org/astros.json') 17 | .then(res => res.json()); 18 | 19 | getPeopleInSpace() 20 | .then(console.log); 21 | 22 | //03. Async() and await() 23 | 24 | const delay = seconds => { 25 | return new Promise( 26 | resolve => setTimeout(resolve, seconds * 1000) 27 | ) 28 | }; 29 | 30 | const countToFive = async() => { 31 | console.log('zero seconds wait'); 32 | await delay(2); 33 | console.log('Two seconds wait'); 34 | await delay(5); 35 | console.log('Five seconds wait'); 36 | } 37 | 38 | countToFive(); 39 | 40 | //04. Async with fetch 41 | 42 | const githubRequest = async(loginName) => { 43 | try{ 44 | var response = await fetch(`http://api.github.com/users/${loginName}/followers`); 45 | var json = await response.json(); 46 | var followerList = json.map(user => user.login); 47 | console.log(followerList); 48 | } catch(e){ 49 | console.log("Data didn't load", e); 50 | } 51 | }; 52 | 53 | //githubRequest('eveporcello'); 54 | githubRequest('pradeepkumar2'); 55 | -------------------------------------------------------------------------------- /es6/es6-features.js: -------------------------------------------------------------------------------- 1 | //01. Template String 2 | 3 | function print(Name) { 4 | console.log("Hello " + Name); 5 | console.log(`Hello ${Name}`); 6 | } 7 | print("Pradeep"); 8 | 9 | 10 | //02. Spread Operators 11 | 12 | var firstGroup = ["C", "C++", "Java"]; 13 | var secondGroup = ["SQL", "MySQL", "BigData"]; 14 | var thirdGroup = ["Android", "Python", "Ruby", firstGroup, secondGroup]; 15 | var finalGroup = ["Android", "Python", "Ruby", ...firstGroup, ...secondGroup]; 16 | 17 | console.log(thirdGroup); 18 | console.log(finalGroup); 19 | 20 | 21 | //03. Sets 22 | 23 | const sets = new Set([1, 2, 3, 4, 5]); 24 | 25 | console.log(sets.has(1)); 26 | console.log(sets.has(0)); 27 | 28 | 29 | //04. Default Parametrs 30 | 31 | function add(x = 10, y = 20) { 32 | console.log(x + y); 33 | } 34 | add(30, 40); 35 | 36 | 37 | //05. repeat() 38 | 39 | var cat = { 40 | meow(times){ 41 | console.log("meow ".repeat(times)); 42 | } 43 | }; 44 | cat.meow(2); 45 | 46 | 47 | //06. Arrow Function 48 | 49 | var companyList = function(company) { 50 | console.log(company); 51 | }; 52 | 53 | //ES-6 54 | var companyList = company => console.log(company); //arraow function 55 | 56 | companyList(["Apple", "Microsoft", "Google"]); 57 | 58 | 59 | //07. Arrow function with 'this' 60 | 61 | var person = { 62 | first: "Pradeep", 63 | actions: ["bike", "hike", "ski", "surf"], 64 | printActions: function() { 65 | var _this = this; 66 | this.actions.forEach(function(action) { 67 | var str = _this.first + " likes to " + action; 68 | console.log(str); 69 | }); 70 | } 71 | }; 72 | person.printActions(); 73 | 74 | //ES-6 75 | var person = { 76 | first: "Pradeep", 77 | actions: ["bike", "hike", "ski", "surf"], 78 | printActions() { 79 | this.actions.forEach(action => { 80 | var str = this.first + " likes to " + action; 81 | console.log(str); 82 | }); 83 | } 84 | }; 85 | 86 | 87 | //08. Destructing Assignment 88 | 89 | var phone = { 90 | title: "iPhone", 91 | price: 800, 92 | description: "The iPhone is a smartphone developed by Apple" 93 | }; 94 | 95 | console.log(phone.title); 96 | //ES-6 97 | var { title, price } = { 98 | title: "iPhone", 99 | price: 800, 100 | description: "The iPhone is a smartphone developed by Apple" 101 | }; 102 | 103 | console.log(title); 104 | 105 | //09. Generators 106 | 107 | /*** Calling a generator function does not execute its body immediately ***/ 108 | 109 | function* generator(i) { 110 | yield i; 111 | yield i + 10; 112 | } 113 | var gen = generator(10); 114 | console.log(gen.next().value); 115 | console.log(gen.next().value); 116 | 117 | 118 | //10. Symbols 119 | 120 | /*** They are tokens that serve as unique IDs. We create symbols via the factory function Symbol() ***/ 121 | 122 | const symbol1 = Symbol(); 123 | const symbol2 = Symbol(42); 124 | const symbol3 = Symbol('foo'); 125 | 126 | console.log(typeof symbol1); 127 | 128 | console.log(symbol3.toString()); 129 | 130 | console.log(Symbol('foo') === Symbol('foo')); 131 | 132 | 133 | // 11. Iterator 134 | 135 | /** The iterable protocol allows JavaScript objects to define or customize their iteration behavior. **/ 136 | 137 | var title = 'ES6'; 138 | var iterateIt = title[Symbol.iterator](); 139 | 140 | console.log(iterateIt.next().value); //output: E 141 | console.log(iterateIt.next().value); //output: S 142 | console.log(iterateIt.next().value); //output: 6 -------------------------------------------------------------------------------- /functions.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Types of functions in JavaScript 5 | 6 | 99 | 100 |

Types of functions in JavaScript

101 | 102 | 103 | -------------------------------------------------------------------------------- /iife-pattern.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | IIFE Design Patterns in JS 5 | 6 | 46 | 47 | IIFE Design Patterns 48 | 49 | 50 | -------------------------------------------------------------------------------- /miscellaneous.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Miscellaneous features in JavaScript 5 | 6 | 7 |

8 | 9 | 366 | 367 | -------------------------------------------------------------------------------- /namespace.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Namespace in JS 5 | 6 | 19 | 20 | Namespace in JavaScript 21 | 22 | 23 | -------------------------------------------------------------------------------- /objects.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Objects in JS 5 | 6 | 112 | 113 | Objects in JavaScript 114 | 115 | 116 | -------------------------------------------------------------------------------- /problems/AllSubSetOfGivenSet.js: -------------------------------------------------------------------------------- 1 | const getAllSubset = arr => 2 | arr.reduce((subsets, value) => 3 | subsets.concat(subsets.map(set => [value, ...set])) 4 | , [[]] 5 | ); 6 | 7 | console.log(getAllSubsets([1,2,3])); // [[], [1], [2], [2, 1], [3], [3, 1], [3, 2], [3, 2, 1]] 8 | -------------------------------------------------------------------------------- /problems/animateUsingVanillaJavascript.js: -------------------------------------------------------------------------------- 1 | // https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/ 2 | // http://www.javascriptkit.com/javatutors/requestanimationframe.shtml 3 | // https://codepen.io/gohilumesh/pen/xjJyWq --- Use this 4 | //
5 | /* 6 | #animatedElem { 7 | position: absolute; 8 | width: 20px; 9 | height: 20px; 10 | background: #ff6600; 11 | } 12 | */ 13 | 14 | 15 | var elem = document.getElementById("animatedElem"), 16 | left = 0, 17 | lastFrame = +new Date, 18 | timer; 19 | // Move the element on the right at ~600px/s 20 | timer = setInterval(function() { 21 | var now = +new Date, 22 | deltaT = now - lastFrame; 23 | elem.style.left = ( left += 10 * deltaT / 16 ) + "px"; 24 | lastFrame = now; 25 | // clear the timer at 400px to stop the animation 26 | if ( left > 400 ) { 27 | clearInterval( timer ); 28 | } 29 | }, 16); 30 | -------------------------------------------------------------------------------- /problems/filterArrayBasedOnAnotherArray.js: -------------------------------------------------------------------------------- 1 | let items = [ 2 | {color: 'red', type: 'tv', age: 18}, 3 | {color: 'silver', type: 'phone', age: 20}, 4 | {color: 'blue', type: 'phone', age: 20}, 5 | {color: 'green', type: 'phone', age: 20} 6 | ]; 7 | 8 | let excludes = [ 9 | {k: 'color', v: 'silver'}, 10 | {k: 'type', v: 'tv'}, 11 | ]; 12 | 13 | 14 | let newItems = items.reduce((acc, item) => { 15 | let result = excludes.some(exclude => item[exclude['k']] === exclude['v']); 16 | if (!result) { 17 | acc.push(item); 18 | } 19 | return acc; 20 | }, []); 21 | 22 | console.log(newItems); 23 | -------------------------------------------------------------------------------- /problems/flattenObject.js: -------------------------------------------------------------------------------- 1 | let obj = { 2 | "a": { 3 | "b": { 4 | "c": 12, 5 | "d": "Hello World", 6 | "e": null 7 | }, 8 | "f": [1,2,3] 9 | } 10 | }; 11 | 12 | const flatten = (obj, parentkey) => { 13 | return Object.keys(obj).reduce((acc, key) => { 14 | if (Object.prototype.hasOwnProperty.call(obj, key)) { 15 | let val = obj[key]; 16 | if (typeof val === "object" && !Array.isArray(val) && val != null) { // != will catch undefined or null 17 | let flat = flatten(val, key); 18 | if (parentkey) { 19 | for (let i in flat) { 20 | let k = `${parentkey}/${i}`; 21 | acc[k] = flat[i]; 22 | } 23 | } else { 24 | acc = flat; 25 | } 26 | } else { 27 | let prop = parentkey ? `${parentkey}/${key}` : key; 28 | acc[prop] = val; 29 | } 30 | } 31 | return acc; 32 | }, {}); 33 | }; 34 | 35 | 36 | console.log(flatten(obj)); 37 | 38 | // { 39 | // a/b/c: 12, 40 | // a/b/d: "Hello World", 41 | // a/b/e: null, 42 | // a/f: [1, 2, 3] 43 | // } 44 | -------------------------------------------------------------------------------- /problems/graph.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor() { 3 | this.vertices = []; 4 | this.edges = {}; 5 | this.numberOfEdges = 0; 6 | } 7 | 8 | addVertex(vertex) { 9 | this.vertices.push(vertex); 10 | this.edges[vertex] = []; 11 | } 12 | 13 | addEdge(vertex1, vertex2) { 14 | this.edges[vertex1].push(vertex2); 15 | this.edges[vertex2].push(vertex1); 16 | this.numberOfEdges++; 17 | } 18 | 19 | removeVertex(vertex) { 20 | const index = this.vertices.indexOf(vertex); 21 | if(~index) { 22 | this.vertices.splice(index, 1); 23 | } 24 | while(this.edges[vertex].length) { 25 | const adjacentVertex = this.edges[vertex].pop(); 26 | this.removeEdge(adjacentVertex, vertex); 27 | } 28 | } 29 | 30 | removeEdge(vertex1, vertex2) { 31 | const index1 = this.edges[vertex1] ? this.edges[vertex1].indexOf(vertex2) : -1; 32 | const index2 = this.edges[vertex2] ? this.edges[vertex2].indexOf(vertex1) : -1; 33 | if(~index1) { 34 | this.edges[vertex1].splice(index1, 1); 35 | this.numberOfEdges--; 36 | } 37 | if(~index2) { 38 | this.edges[vertex2].splice(index2, 1); 39 | } 40 | } 41 | 42 | size() { 43 | return this.vertices.length; 44 | } 45 | 46 | relations() { 47 | return this.numberOfEdges; 48 | } 49 | 50 | traverseDFS(vertex, fn) { 51 | if(!~this.vertices.indexOf(vertex)) { 52 | return console.log('Vertex not found'); 53 | } 54 | const visited = {}; 55 | this._traverseDFS(vertex, visited, fn); 56 | } 57 | 58 | _traverseDFS(vertex, visited, fn) { 59 | visited[vertex] = true; 60 | if (typeof fn === "function") { 61 | fn(vertex); 62 | } 63 | this.edges[vertex].forEach(adjVertex => { 64 | if(!visited[adjVertex]) { 65 | this._traverseDFS(adjVertex, visited, fn); 66 | } 67 | }); 68 | } 69 | 70 | traverseBFS(vertex, fn) { 71 | if(!~this.vertices.indexOf(vertex)) { 72 | return console.log('Vertex not found'); 73 | } 74 | const queue = [vertex]; 75 | const visited = {[vertex] : true}; 76 | 77 | while(queue.length) { 78 | vertex = queue.shift(); 79 | if (typeof fn === "function") { 80 | fn(vertex); 81 | } 82 | this.edges[vertex].forEach(vEdge => { 83 | if(!visited[vEdge]) { 84 | visited[vEdge] = true; 85 | queue.push(vEdge); 86 | } 87 | }); 88 | } 89 | } 90 | 91 | pathFromTo(vertexSource, vertexDestination) { 92 | if(!~this.vertices.indexOf(vertexSource) || this.vertices.indexOf(vertexDestination) === -1) { 93 | return console.log('Vertex not found'); 94 | } 95 | const queue = [vertexSource]; 96 | const visited = {[vertexSource]: true }; 97 | const paths = {}; 98 | 99 | while(queue.length) { 100 | const vertex = queue.shift(); 101 | this.edges[vertex].forEach(vEdge => { 102 | if(!visited[vEdge]) { 103 | visited[vEdge] = true; 104 | queue.push(vEdge); 105 | // save paths between vertices 106 | paths[vEdge] = vertex; 107 | } 108 | }); 109 | } 110 | 111 | let current = vertexDestination; 112 | const path = []; 113 | while (current) { 114 | path.push(current); 115 | current = paths[current]; 116 | } 117 | return path.join('-'); 118 | } 119 | 120 | print() { 121 | console.log(this.vertices.map(function(vertex) { 122 | return (`${vertex} -> ${this.edges[vertex].join(', ')}`).trim(); 123 | }, this).join(' | ')); 124 | } 125 | } 126 | 127 | const graph = new Graph(); 128 | graph.addVertex(1); 129 | graph.addVertex(2); 130 | graph.addVertex(3); 131 | graph.addVertex(4); 132 | graph.addVertex(5); 133 | graph.addVertex(6); 134 | graph.print(); // 1 -> | 2 -> | 3 -> | 4 -> | 5 -> | 6 -> 135 | graph.addEdge(1, 2); 136 | graph.addEdge(1, 5); 137 | graph.addEdge(2, 3); 138 | graph.addEdge(2, 5); 139 | graph.addEdge(3, 4); 140 | graph.addEdge(4, 5); 141 | graph.addEdge(4, 6); 142 | graph.print(); // 1 -> 2, 5 | 2 -> 1, 3, 5 | 3 -> 2, 4 | 4 -> 3, 5, 6 | 5 -> 1, 2, 4 | 6 -> 4 143 | console.log('graph size (number of vertices):', graph.size()); // => 6 144 | console.log('graph relations (number of edges):', graph.relations()); // => 7 145 | graph.traverseDFS(1, vertex => { console.log(vertex); }); // => 1 2 3 4 5 6 146 | console.log('---'); 147 | graph.traverseBFS(1, vertex => { console.log(vertex); }); // => 1 2 5 3 4 6 148 | graph.traverseDFS(0, vertex => { console.log(vertex); }); // => 'Vertex not found' 149 | graph.traverseBFS(0, vertex => { console.log(vertex); }); // => 'Vertex not found' 150 | console.log('path from 6 to 1:', graph.pathFromTo(6, 1)); // => 6-4-5-1 151 | console.log('path from 3 to 5:', graph.pathFromTo(3, 5)); // => 3-2-5 152 | graph.removeEdge(1, 2); 153 | graph.removeEdge(4, 5); 154 | graph.removeEdge(10, 11); 155 | console.log('graph relations (number of edges):', graph.relations()); // => 5 156 | console.log('path from 6 to 1:', graph.pathFromTo(6, 1)); // => 6-4-3-2-5-1 157 | graph.addEdge(1, 2); 158 | graph.addEdge(4, 5); 159 | console.log('graph relations (number of edges):', graph.relations()); // => 7 160 | console.log('path from 6 to 1:', graph.pathFromTo(6, 1)); // => 6-4-5-1 161 | graph.removeVertex(5); 162 | console.log('graph size (number of vertices):', graph.size()); // => 5 163 | console.log('graph relations (number of edges):', graph.relations()); // => 4 164 | console.log('path from 6 to 1:', graph.pathFromTo(6, 1)); // => 6-4-3-2-1 165 | graph.traverseDFS(1, (v) => console.log(`traverse DFS ${v}`) ); 166 | graph.traverseBFS(1, (v) => console.log(`traverse BFS ${v}`) ); 167 | -------------------------------------------------------------------------------- /problems/layout.md: -------------------------------------------------------------------------------- 1 | [FlexBox](https://philipwalton.github.io/solved-by-flexbox/demos/holy-grail/) - Holy grail layout using FlexBox 2 | [Grid](https://bitsofco.de/holy-grail-layout-css-grid/) - Holy grail layout using grid 3 | [Learn flexbox](http://flexboxfroggy.com/) - flex box froggy 4 | [Learn CSS Grid](https://cssgridgarden.com/) - CSS grid garden 5 | -------------------------------------------------------------------------------- /problems/lengthOfLongestSubString.js: -------------------------------------------------------------------------------- 1 | const lengthOfLongestSubstring = function(s) { 2 | 3 | let map = {} 4 | let start = 0 5 | let maxLen = 0 6 | let arr = s.split('') 7 | 8 | for (let i=0; i < s.length; i++) { 9 | let current = map[arr[i]]; 10 | if (current != null && start <= current) { 11 | start = current + 1; 12 | } else { 13 | maxLen = Math.max(maxLen, i - start + 1) 14 | } 15 | map[arr[i]] = i; 16 | } 17 | 18 | return maxLen; 19 | }; 20 | 21 | console.log(lengthOfLongestSubstring("abcabcbb")); //3 22 | console.log(lengthOfLongestSubstring("cccc")); //1 23 | console.log(lengthOfLongestSubstring("umesh")); 5 24 | -------------------------------------------------------------------------------- /problems/maxSubArray.js: -------------------------------------------------------------------------------- 1 | const maxSubArray = (nums) => { 2 | let currentSum = 0; 3 | return nums.reduce((acc, item) => { 4 | currentSum = Math.max(currentSum+item, 0); 5 | return Math.max(acc, currentSum) 6 | }, 0); 7 | }; 8 | 9 | console.log(maxSubArray([-2,1,-3,4,-1,2,1,-5,4])) // 6 10 | console.log(maxSubArray([4,-1,3,1])) // 7 11 | -------------------------------------------------------------------------------- /problems/median_of_arr.js: -------------------------------------------------------------------------------- 1 | const median = (arr) => { 2 | if (!Array.isArray(arr)) { 3 | return null; // or throw error; 4 | } 5 | if (arr.length === 0) { 6 | return null; 7 | } 8 | 9 | let cloneArr = arr.slice(); 10 | let sortedArr = cloneArr.sort((a, b) => a - b); 11 | 12 | let mid = Math.floor((0, sortedArr.length - 1) / 2); 13 | if (sortedArr.length % 2 === 0) { 14 | return (sortedArr[mid] + sortedArr[mid + 1]) / 2; 15 | } 16 | return sortedArr[mid]; 17 | }; 18 | 19 | 20 | let arr = [3,8,9,1,5,7,9,21]; 21 | console.log(median(arr)); // 7.5 22 | 23 | let arr1 = [1,2,4,3,5]; 24 | console.log(median(arr1)); // 3 25 | -------------------------------------------------------------------------------- /problems/mergeOverlappingInterval.js: -------------------------------------------------------------------------------- 1 | const mergeIntervals = (arr) => { 2 | if (arr == null || arr.length < 2) { 3 | return arr; 4 | } 5 | 6 | arr.sort((a, b) => a[0] - b[0]); 7 | 8 | return arr.reduce((acc, cur) => { 9 | let last = acc.pop() 10 | if (last) { 11 | if (last[1] > cur[0]) { 12 | let newLast = [last[0], cur[1]]; 13 | acc.push(newLast); 14 | } else { 15 | acc.push(last, cur); 16 | } 17 | } else { 18 | acc.push(cur); 19 | } 20 | return acc; 21 | }, []); 22 | }; 23 | 24 | console.log(mergeIntervals( [[1,3],[2,6],[8,10],[15,18]])); //[[1, 6], [8, 10], [15, 18]] 25 | console.log(mergeIntervals([[1,4],[3,5],[2,4],[7,10]])); // [[1, 5], [7, 10]] 26 | -------------------------------------------------------------------------------- /problems/overlapRectangle.js: -------------------------------------------------------------------------------- 1 | class Rectangle { 2 | constructor(x, y, width, height) { 3 | this.x = x; 4 | this.y = y; 5 | this.width = width; 6 | this.height = height; 7 | } 8 | 9 | isOverlapping(rect2) { 10 | return (this.x < (rect2.x + rect2.width) && 11 | (this.x + this.width) > rect2.x && 12 | this.y < (rect2.y + rect2.height) && 13 | (this.y + this.height) > rect2.y 14 | ); 15 | } 16 | } 17 | 18 | const rect1 = new Rectangle(250, 250, 150,100); 19 | const rect2 = new Rectangle(100, 100, 300, 200); 20 | 21 | const rect3 = new Rectangle(450, 450, 150,100); 22 | 23 | 24 | console.log(rect1.isOverlapping(rect2)); // true 25 | 26 | console.log(rect2.isOverlapping(rect3)); // false 27 | -------------------------------------------------------------------------------- /problems/secondLargestInArray.js: -------------------------------------------------------------------------------- 1 | const secondLargest = (arr) => { 2 | //return arr.sort((a, b) => a - b)[arr.length -2]; // different solution 3 | let largest = -1; 4 | let secondLargest = -1; 5 | arr.forEach(el => { 6 | if (el > largest) { 7 | let temp = largest; 8 | largest = el; 9 | secondLargest = temp; 10 | } else if (el > secondLargest) { 11 | secondLargest = el; 12 | } 13 | }); 14 | 15 | return secondLargest; 16 | } 17 | 18 | console.log(secondLargest([1,10,2,9])) // 9 19 | -------------------------------------------------------------------------------- /problems/sequentialPromiseExecution.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | return tasks.reduce((promiseChain, currentTask) => { 4 | return promiseChain.then(chain => 5 | currentTask.then(result => [...chain, result]); 6 | ); 7 | }, Promise.resolve([])).then(arrayOfResults => { 8 | .... 9 | }); 10 | -------------------------------------------------------------------------------- /problems/sortedArrayToBST.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | class Node { 3 | constructor(value){ 4 | this.value = value; 5 | this.left = this.right = null; 6 | } 7 | } 8 | const sortedArrayToBST = (nums) => { 9 | let sortedArrayToBSTRec = (nums, start, end) => { 10 | if (start > end) { 11 | return null 12 | } 13 | let mid = Math.floor((start + end) / 2) 14 | let root = new Node(nums[mid]) 15 | root.left = sortedArrayToBSTRec(nums, start, mid - 1) 16 | root.right = sortedArrayToBSTRec(nums, mid + 1, end) 17 | return root 18 | } 19 | return sortedArrayToBSTRec(nums, 0, nums.length - 1) 20 | }; 21 | 22 | console.log(sortedArrayToBST([1,2,3,4,5,6,7])) 23 | -------------------------------------------------------------------------------- /problems/stringPermutations.js: -------------------------------------------------------------------------------- 1 | const strPermutations = str => { 2 | if (str.length < 2) { 3 | return str; // This is our break condition 4 | } 5 | 6 | let permutations = []; // This array will hold our permutations 7 | 8 | for (let i = 0, len = str.length; i < len; i++) { 9 | let char = str[i]; 10 | let remainingString = `${str.slice(0,i)}${str.slice(i+1)}`; 11 | for (let subPermutation of strPermutations(remainingString)) { 12 | permutations.push(char + subPermutation); 13 | } 14 | } 15 | return permutations; 16 | } 17 | 18 | console.log(strPermutations("abcd")); 19 | // ["abcd", "abdc", "acbd", "acdb", "adbc", "adcb", "bacd", "badc", "bcad", "bcda", "bdac", "bdca", "cabd", 20 | // "cadb", "cbad", "cbda", "cdab", "cdba", "dabc", "dacb", "dbac", "dbca", "dcab", "dcba"] 21 | 22 | // Permuation of an array 23 | 24 | function permutation(input) { 25 | let outputs = [[input[0]]]; 26 | for (let i = 1; i < input.length; i++) { 27 | let current = []; 28 | for (let j = 0; j < outputs.length; j++) { 29 | let base = outputs[j]; 30 | for (let k = 0; k <= base.length; k++) { 31 | let temp = base.slice(); 32 | temp.splice(k, 0, input[i]); 33 | current.push(temp); 34 | } 35 | } 36 | outputs = current; 37 | } 38 | return outputs; 39 | } 40 | 41 | console.log(permutation(["a", "b", "c", "d"])); 42 | //[["d", "c", "b", "a"], ["c", "d", "b", "a"], ["c", "b", "d", "a"], ["c", "b", "a", "d"], ["d", "b", "c", "a"], 43 | // ["b", "d", "c", "a"], ["b", "c", "d", "a"], ["b", "c", "a", "d"], ["d", "b", "a", "c"], ["b", "d", "a", "c"], 44 | // ["b", "a", "d", "c"], ["b", "a", "c", "d"], ["d", "c", "a", "b"], ["c", "d", "a", "b"], ["c", "a", "d", "b"], 45 | // ["c", "a", "b", "d"], ["d", "a", "c", "b"], ["a", "d", "c", "b"], ["a", "c", "d", "b"], ["a", "c", "b", "d"], 46 | // ["d", "a", "b", "c"], ["a", "d", "b", "c"], ["a", "b", "d", "c"], ["a", "b", "c", "d"]] 47 | -------------------------------------------------------------------------------- /problems/wordSquare.js: -------------------------------------------------------------------------------- 1 | const validWordSquare = (words) => { 2 | if (words == null || words.length === 0) { 3 | return false; 4 | } 5 | if (words.length !== words[0].length) { 6 | return false; 7 | } 8 | 9 | for (let i = 0; i < words.length; i++) { 10 | for (let j = 0; j < words[i].length; j++) { 11 | if (words[i][j] !== words[j][i]) { 12 | return false; 13 | } 14 | } 15 | } 16 | return true; 17 | }; 18 | 19 | let arr = [ 20 | ["b","a","l","l"], 21 | ["a","r","e","a"], 22 | ["r","e","a","d"], 23 | ["l","a","d","y"] 24 | ]; 25 | 26 | let arr1 = [ 27 | ["a","b","c","d"], 28 | ["b","n","r","t"], 29 | ["c","r","m","y"], 30 | ["d","t","y","e"] 31 | ]; 32 | 33 | 34 | console.log(validWordSquare(arr)); // false 35 | console.log(validWordSquare(arr1)); // true 36 | -------------------------------------------------------------------------------- /prototype.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Prototype in JS 5 | 6 | 35 | 36 | Prototype in JavaScript 37 | 38 | 39 | -------------------------------------------------------------------------------- /regexp.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Regular-Expression in JS 5 | 6 | 45 | 46 | Regular Expression in JavaScript 47 | 48 | 49 | --------------------------------------------------------------------------------