├── .gitignore
├── JS
├── .parcel-cache
│ ├── data.mdb
│ └── lock.mdb
├── Readme.md
├── babel.config.json
├── jest.config.js
├── package-lock.json
├── package.json
├── polyfills
│ ├── apply.functions.polyfill.js
│ ├── bind.functions.polyfill.js
│ ├── call.functions.polyfill.js
│ ├── filter.array.polyfill.js
│ ├── map.array.polyfill.js
│ ├── reduce.array.polyfill.js
│ └── split.string.polyfill.js
├── recursion
│ ├── FlatArray.js
│ ├── RECUR_EASY_Q1_YT.js
│ ├── __data__
│ │ └── Q1_mock_data.json
│ └── __tests__
│ │ ├── FlatArray.test.js
│ │ └── RECUR_EASY_Q1_YT.test.js
├── utils.js
└── webworkers
│ ├── index.html
│ ├── webworker.q1.js
│ └── webworker.worker.js
├── LICENSE
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | lerna-debug.log*
8 |
9 | # Diagnostic reports (https://nodejs.org/api/report.html)
10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
11 |
12 | # Runtime data
13 | pids
14 | *.pid
15 | *.seed
16 | *.pid.lock
17 |
18 | # Directory for instrumented libs generated by jscoverage/JSCover
19 | lib-cov
20 |
21 | # Coverage directory used by tools like istanbul
22 | coverage
23 | *.lcov
24 |
25 | # nyc test coverage
26 | .nyc_output
27 |
28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
29 | .grunt
30 |
31 | # Bower dependency directory (https://bower.io/)
32 | bower_components
33 |
34 | # node-waf configuration
35 | .lock-wscript
36 |
37 | # Compiled binary addons (https://nodejs.org/api/addons.html)
38 | build/Release
39 |
40 | # Dependency directories
41 | node_modules/
42 | jspm_packages/
43 |
44 | # TypeScript v1 declaration files
45 | typings/
46 |
47 | # TypeScript cache
48 | *.tsbuildinfo
49 |
50 | # Optional npm cache directory
51 | .npm
52 |
53 | # Optional eslint cache
54 | .eslintcache
55 |
56 | # Microbundle cache
57 | .rpt2_cache/
58 | .rts2_cache_cjs/
59 | .rts2_cache_es/
60 | .rts2_cache_umd/
61 |
62 | # Optional REPL history
63 | .node_repl_history
64 |
65 | # Output of 'npm pack'
66 | *.tgz
67 |
68 | # Yarn Integrity file
69 | .yarn-integrity
70 |
71 | # dotenv environment variables file
72 | .env
73 | .env.test
74 |
75 | # parcel-bundler cache (https://parceljs.org/)
76 | .cache
77 | .parcel-cache
78 | # Next.js build output
79 | .next
80 |
81 | # Nuxt.js build / generate output
82 | .nuxt
83 | dist
84 |
85 | # Gatsby files
86 | .cache/
87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js
88 | # https://nextjs.org/blog/next-9-1#public-directory-support
89 | # public
90 |
91 | # vuepress build output
92 | .vuepress/dist
93 |
94 | # Serverless directories
95 | .serverless/
96 |
97 | # FuseBox cache
98 | .fusebox/
99 |
100 | # DynamoDB Local files
101 | .dynamodb/
102 |
103 | # TernJS port file
104 | .tern-port
105 |
106 |
--------------------------------------------------------------------------------
/JS/.parcel-cache/data.mdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anarchymonkey/frontend-developer-interview-questions/b8a8f60f503bfe05306821442ba78fe3497c1a62/JS/.parcel-cache/data.mdb
--------------------------------------------------------------------------------
/JS/.parcel-cache/lock.mdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anarchymonkey/frontend-developer-interview-questions/b8a8f60f503bfe05306821442ba78fe3497c1a62/JS/.parcel-cache/lock.mdb
--------------------------------------------------------------------------------
/JS/Readme.md:
--------------------------------------------------------------------------------
1 | # 🚀 Front End Interview Questions - JavaScript Basics
2 |
3 | Welcome to my GitHub repository, where I have compiled a list of front end interview questions related to JavaScript basics that will help you prepare for your next interview. As we all know, JavaScript is one of the most essential programming languages for front end developers. Therefore, it is crucial to have a good understanding of the basics before going for an interview.
4 |
5 | This repository contains a list of theoretical questions related to JavaScript basics that are commonly asked in front end interviews. These questions cover topics such as data types, variables, operators, functions, loops, and more. By going through these questions and understanding the concepts behind them, you will be able to enhance your knowledge and confidence in the subject.
6 |
7 | Feel free to use this repository as a resource to prepare for your next front end interview. Good luck!
8 |
9 | ## Contents
10 |
11 | - [🚀 Front End Interview Questions - JavaScript Basics](#-front-end-interview-questions---javascript-basics)
12 | - [Contents](#contents)
13 | - [Basics](#basics)
14 | - [What is JavaScript?](#what-is-javascript)
15 | - [What are the data types in JavaScript?](#what-are-the-data-types-in-javascript)
16 | - [What is the difference between undefined and null?](#what-is-the-difference-between-undefined-and-null)
17 | - [What is the difference between == and ===?](#what-is-the-difference-between--and-)
18 | - [What is the difference between var, let, and const?](#what-is-the-difference-between-var-let-and-const)
19 | - [What is hoisting in JavaScript?](#what-is-hoisting-in-javascript)
20 | - [What is the this keyword in JavaScript?](#what-is-the-this-keyword-in-javascript)
21 | - [What is event bubbling in JavaScript?](#what-is-event-bubbling-in-javascript)
22 | - [What is a closure in JavaScript?](#what-is-a-closure-in-javascript)
23 | - [Functions](#functions)
24 | - [What is a higher-order function in JavaScript?](#what-is-a-higher-order-function-in-javascript)
25 | - [What is a callback function in JavaScript?](#what-is-a-callback-function-in-javascript)
26 | - [What is a pure function in JavaScript?](#what-is-a-pure-function-in-javascript)
27 | - [What is the difference between function declaration and function expression?](#what-is-the-difference-between-function-declaration-and-function-expression)
28 | - [What is a recursive function in JavaScript?](#what-is-a-recursive-function-in-javascript)
29 | - [What is a generator function in JavaScript?](#what-is-a-generator-function-in-javascript)
30 | - [What is the difference between .call() and .apply()?](#what-is-the-difference-between-call-and-apply)
31 | - [What is the difference between .bind() and .call()?](#what-is-the-difference-between-bind-and-call)
32 | - [What is the arguments object in JavaScript?](#what-is-the-arguments-object-in-javascript)
33 | - [What is a rest parameter in JavaScript?](#what-is-a-rest-parameter-in-javascript)
34 | - [Objects](#objects)
35 | - [What is an object in JavaScript?](#what-is-an-object-in-javascript)
36 | - [What is the difference between an object and an array in JavaScript?](#what-is-the-difference-between-an-object-and-an-array-in-javascript)
37 | - [What is prototypal inheritance in JavaScript?](#what-is-prototypal-inheritance-in-javascript)
38 | - [What is the Object.create() method in JavaScript?](#what-is-the-objectcreate-method-in-javascript)
39 | - [What is the new keyword in JavaScript?](#what-is-the-new-keyword-in-javascript)
40 | - [What is a constructor function in JavaScript?](#what-is-a-constructor-function-in-javascript)
41 | - [Arrays](#arrays)
42 | - [What is an array in JavaScript?](#what-is-an-array-in-javascript)
43 | - [What is the difference between .forEach() and .map()?](#what-is-the-difference-between-foreach-and-map)
44 | - [What is the difference between .slice() and .splice()?](#what-is-the-difference-between-slice-and-splice)
45 | - [What is the difference between .shift() and .pop()?](#what-is-the-difference-between-shift-and-pop)
46 | - [What is the Array.prototype.filter() method in JavaScript?](#what-is-the-arrayprototypefilter-method-in-javascript)
47 | - [What is the Array.prototype.reduce() method in JavaScript?](#what-is-the-arrayprototypereduce-method-in-javascript)
48 | - [ES6 Features](#es6-features)
49 | - [What are template literals in JavaScript?](#what-are-template-literals-in-javascript)
50 | - [What are default parameters in JavaScript?](#what-are-default-parameters-in-javascript)
51 | - [What are destructuring assignments in JavaScript?](#what-are-destructuring-assignments-in-javascript)
52 | - [What is the spread operator in JavaScript?](#what-is-the-spread-operator-in-javascript)
53 | - [What is the class keyword in JavaScript?](#what-is-the-class-keyword-in-javascript)
54 | - [What is the super keyword in JavaScript?](#what-is-the-super-keyword-in-javascript)
55 | - [What is the Symbol data type in JavaScript?](#what-is-the-symbol-data-type-in-javascript)
56 | - [Promises](#promises)
57 | - [What are promises in JavaScript?](#what-are-promises-in-javascript)
58 | - [What is the difference between a promise and a callback?](#what-is-the-difference-between-a-promise-and-a-callback)
59 | - [What is the .then() method in promises?](#what-is-the-then-method-in-promises)
60 | - [What is the .catch() method in promises?](#what-is-the-catch-method-in-promises)
61 | - [What is the .finally() method in promises?](#what-is-the-finally-method-in-promises)
62 | - [What is the Promise.all() method in JavaScript?](#what-is-the-promiseall-method-in-javascript)
63 | - [What is the Promise.race() method in JavaScript?](#what-is-the-promiserace-method-in-javascript)
64 | - [What is the Promise.allSettled() method in Javascript?](#what-is-the-promiseallsettled-method-in-javascript)
65 | - [What is the async keyword in JavaScript?](#what-is-the-async-keyword-in-javascript)
66 | - [What is the await keyword in JavaScript?](#what-is-the-await-keyword-in-javascript)
67 | - [What is the difference between async/await and promises?](#what-is-the-difference-between-asyncawait-and-promises)
68 | - [How do you handle errors in async/await?](#how-do-you-handle-errors-in-asyncawait)
69 | - [What is the try/catch block in JavaScript?](#what-is-the-trycatch-block-in-javascript)
70 | - [How do you use async/await with Promise.all()?](#how-do-you-use-asyncawait-with-promiseall)
71 | - [DOM (Document Object Model) Manupulation](#dom-document-object-model-manupulation)
72 | - [What is the Document Object Model (DOM) in JavaScript?](#what-is-the-document-object-model-dom-in-javascript)
73 | - [What is the difference between innerHTML and textContent?](#what-is-the-difference-between-innerhtml-and-textcontent)
74 | - [What is the querySelector() method in JavaScript?](#what-is-the-queryselector-method-in-javascript)
75 | - [What is the addEventListener() method in JavaScript?](#what-is-the-addeventlistener-method-in-javascript)
76 | - [What is event delegation in JavaScript?](#what-is-event-delegation-in-javascript)
77 | - [Browser APIs](#browser-apis)
78 | - [What are browser APIs in JavaScript?](#what-are-browser-apis-in-javascript)
79 | - [What is the localStorage API in JavaScript?](#what-is-the-localstorage-api-in-javascript)
80 | - [What is the sessionStorage API in JavaScript?](#what-is-the-sessionstorage-api-in-javascript)
81 | - [What is the window object in JavaScript?](#what-is-the-window-object-in-javascript)
82 | - [What is the setTimeout() method in JavaScript?](#what-is-the-settimeout-method-in-javascript)
83 | - [Performance \& Event Loop:](#performance--event-loop)
84 | - [What is event loop in JavaScript?](#what-is-event-loop-in-javascript)
85 | - [What is the requestAnimationFrame() method in JavaScript?](#what-is-the-requestanimationframe-method-in-javascript)
86 | - [What is memoization in JavaScript?](#what-is-memoization-in-javascript)
87 | - [What is lazy loading in JavaScript?](#what-is-lazy-loading-in-javascript)
88 | - [What is tree shaking in JavaScript?](#what-is-tree-shaking-in-javascript)
89 | - [Security](#security)
90 | - [What is Cross-Site Scripting (XSS) in JavaScript?](#what-is-cross-site-scripting-xss-in-javascript)
91 | - [What is Cross-Site Request Forgery (CSRF) in JavaScript?](#what-is-cross-site-request-forgery-csrf-in-javascript)
92 | - [What is the Same-Origin Policy in JavaScript?](#what-is-the-same-origin-policy-in-javascript)
93 | - [What is Content Security Policy (CSP) in JavaScript?](#what-is-content-security-policy-csp-in-javascript)
94 | - [What is the difference between encryption and hashing in JavaScript?](#what-is-the-difference-between-encryption-and-hashing-in-javascript)
95 |
96 | # Basics
97 |
98 | ### What is JavaScript?
99 |
100 | JavaScript is a high-level programming language used to create dynamic and interactive web pages. It is mainly used for creating client-side web applications that can run on a web browser. JavaScript is a powerful language that can manipulate web page elements, handle events, and interact with servers.
101 |
102 | ### What are the data types in JavaScript?
103 | JavaScript has six primitive data types:
104 |
105 | * `string`: represents a sequence of characters.
106 | * `number`: represents a numerical value, including integers and floating-point numbers.
107 | * `boolean`: represents a logical value of either true or false.
108 | * `null`: represents a deliberate non-value or empty value.
109 | * `undefined`: represents a variable that has been declared but has not been assigned a value.
110 | * `symbol`: represents a unique identifier.
111 | JavaScript also has a non-primitive data type called object, which includes arrays, functions, and objects.
112 |
113 | ### What is the difference between undefined and null?
114 |
115 | In JavaScript, undefined means a variable has been declared but has not been assigned a value. On the other hand, null represents a deliberate non-value or empty value that a programmer assigns to a variable.
116 |
117 | ```js
118 | let x; // x is undefined
119 | let y = null; // y is null
120 | ```
121 |
122 | ### What is the difference between == and ===?
123 |
124 | The double equals (==) and triple equals (===) are comparison operators in JavaScript. The main difference between the two is that the double equals only compares the values of two operands, while the triple equals compares both the values and the types of the operands.
125 |
126 | ```js
127 | console.log(5 == "5"); // true
128 | console.log(5 === "5"); // false
129 | ```
130 |
131 | ### What is the difference between var, let, and const?
132 |
133 | In JavaScript, var, let, and const are used to declare variables. However, they have different scopes and behaviors.
134 |
135 | * var: Declares a variable with function scope or global scope.
136 | * let: Declares a variable with block scope, which means it can only be accessed within the block it was declared in.
137 | * const: Declares a constant variable that cannot be reassigned after initialization.
138 |
139 | ```js
140 | function example() {
141 | var x = 10; // function scope
142 | if (true) {
143 | let y = 20; // block scope
144 | const z = 30; // block scope
145 | }
146 | console.log(x); // 10
147 | console.log(y); // ReferenceError: y is not defined
148 | console.log(z); // ReferenceError: z is not defined
149 | }
150 | ```
151 |
152 | ### What is hoisting in JavaScript?
153 |
154 | Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their respective scopes during the compilation phase. This means that a variable or function can be used before it has been declared.
155 |
156 | ```js
157 | x = 5; // Assign 5 to x
158 | console.log(x); // Output: 5
159 | var x; // Declare x
160 | ```
161 |
162 | ### What is the this keyword in JavaScript?
163 | The this keyword refers to the current object that is executing the current function. The value of this depends on how a function is called. When a function is called as a method of an object, this refers to that object. When a function is called alone, this refers to the global object.
164 |
165 | ```js
166 | const person = {
167 | name: "John",
168 | age: 30,
169 | greet() {
170 | console.log(`Hello, my name is ${this.name}`);
171 | },
172 | };
173 |
174 | person.greet(); // Output: Hello, my name is John
175 | ```
176 |
177 | ### What is event bubbling in JavaScript?
178 | Event bubbling is a phenomenon where an event that occurs on an element in the DOM tree will also be propagated to its parent elements in a hierarchy. This means that if an event occurs on a child element, it will also be triggered on all of its parent elements.
179 |
180 | HTML:
181 | ```html
182 |
183 |
186 | ```
187 |
188 | Javascript:
189 | ```js
190 | const parent = document.querySelector("#parent");
191 | const child = document.querySelector("#child");
192 |
193 | child.addEventListener("click", function () {
194 | console.log("Child clicked!");
195 | });
196 |
197 | parent.addEventListener("click", function () {
198 | console.log("Parent clicked!");
199 | });
200 | ```
201 |
202 | If you click the child element, both the child and parent event listeners will be triggered, resulting in the following output:
203 |
204 | ```cmd
205 | Child clicked!
206 | Parent clicked!
207 | ```
208 |
209 | ### What is a closure in JavaScript?
210 | A closure is a function that has access to variables in its outer lexical scope, even after that scope has been destroyed. In other words, a closure allows a function to access and manipulate variables from its parent function, even after the parent function has returned.
211 |
212 | ```js
213 | function outer() {
214 | const name = "John";
215 | function inner() {
216 | console.log(`Hello, ${name}!`);
217 | }
218 | return inner;
219 | }
220 |
221 | const greet = outer(); // assign inner function to a variable
222 | greet(); // Output: Hello, John!
223 |
224 | ```
225 | In the above example, the inner function has access to the name variable from its parent function, outer. Even after outer has returned and its local variables have been destroyed, greet can still access and use the name variable.
226 |
227 | * Bonus (In Depth)
228 |
229 | ```sql
230 | +---------------------------------------+
231 | | Outer Function Scope |
232 | | |
233 | | +-----------------------------+ |
234 | | | Inner Function Scope | |
235 | | | | |
236 | | | +---------+ +---------+ | |
237 | | | | | | | | |
238 | | | | Var | | Var | | |
239 | | | | x: 5 | | y: 10 | | |
240 | | | | | | | | |
241 | | | +---------+ +---------+ | |
242 | | | | |
243 | | | +---------------------+ | |
244 | | | | Inner Function | | |
245 | | | | | | |
246 | | | | Return x + y | | |
247 | | | +---------------------+ | |
248 | | | | |
249 | | +-----------------------------+ |
250 | | |
251 | +---------------------------------------+
252 | ```
253 |
254 | 1. The outer function **outer()** is called, creating its own scope.
255 | 2. Within the outer function, the inner function **inner()** is defined.
256 | 3. The inner function has access to the outer function's variables (in this case, x and y).
257 | 4. When the inner function is returned, it forms a closure with its parent scope, preserving the values of x and y.
258 | 5. The closure is returned and assigned to the variable **greet**.
259 | 6. When **greet()** is called, it has access to the variables x and y, even though the outer function has already completed execution.
260 |
261 | # Functions
262 |
263 |
264 | ### What is a higher-order function in JavaScript?
265 | A higher-order function is a function that takes one or more functions as arguments or returns a function as its result. In other words, a higher-order function is a function that operates on other functions, either by taking them as arguments or by returning them.
266 |
267 | ```js
268 | function higherOrderFunction(callback) {
269 | callback();
270 | }
271 |
272 | function callbackFunction() {
273 | console.log('This is a callback function');
274 | }
275 |
276 | higherOrderFunction(callbackFunction); // Output: 'This is a callback function'
277 | ```
278 | ### What is a callback function in JavaScript?
279 | A callback function is a function that is passed as an argument to another function and is executed after the parent function has completed. In other words, a callback function is a function that is called back by another function.
280 |
281 | ```js
282 | function greeting(name) {
283 | console.log('Hello ' + name);
284 | }
285 |
286 | function processUserInput(callback) {
287 | var name = prompt('Please enter your name:');
288 | callback(name);
289 | }
290 |
291 | processUserInput(greeting); // Output: 'Hello '
292 | ```
293 |
294 | ### What is a pure function in JavaScript?
295 | A pure function is a function that always returns the same result when given the same inputs, and does not have any observable side effects. In other words, a pure function does not modify the values of its arguments or any other global state, and it does not rely on external input or output.
296 |
297 | ```js
298 | function sum(a, b) {
299 | return a + b;
300 | }
301 |
302 | console.log(sum(2, 3)); // Output: 5
303 | console.log(sum(2, 3)); // Output: 5
304 |
305 | ```
306 |
307 | ### What is the difference between function declaration and function expression?
308 | A function declaration is a statement that declares a function with a name and a block of code. A function expression is an expression that defines an anonymous function and assigns it to a variable. The main difference between the two is that function declarations are hoisted to the top of the scope, while function expressions are not.
309 |
310 | ```js
311 | // Function Declaration
312 | function sum(a, b) {
313 | return a + b;
314 | }
315 |
316 | // Function Expression
317 | var sum = function(a, b) {
318 | return a + b;
319 | };
320 | ```
321 |
322 | ### What is a recursive function in JavaScript?
323 | A recursive function is a function that calls itself repeatedly until it reaches a base case, which is a condition that causes the function to stop calling itself. Recursive functions are useful for solving problems that can be broken down into smaller, similar problems.
324 |
325 | ```js
326 | function factorial(n) {
327 | if (n === 0) {
328 | return 1;
329 | } else {
330 | return n * factorial(n - 1);
331 | }
332 | }
333 |
334 | console.log(factorial(5)); // Output: 120
335 | ```
336 |
337 | ### What is a generator function in JavaScript?
338 | A generator function is a special type of function that can pause and resume its execution using the yield keyword. Generator functions are useful for generating sequences of values on-the-fly, without having to precompute all the values at once.
339 |
340 | ```js
341 | function* fibonacci() {
342 | var a = 0, b = 1;
343 | while (true) {
344 | yield a;
345 | [a, b] = [b, a + b];
346 | }
347 | }
348 |
349 | var generator = fibonacci();
350 |
351 | console.log(generator.next().value); // Output: 0
352 | console.log(generator.next().value); // Output: 1
353 | console.log(generator.next().value); // Output: 1
354 | console.log(generator.next().value); // Output: 2
355 | ```
356 |
357 | ### What is the difference between .call() and .apply()?
358 | Both .call() and .apply() are methods that can be used to call a function with a specific this value and a set of arguments.
359 | The main difference between them is in how the arguments are passed. With .call(), the arguments are passed as a comma-separated list, whereas with .apply(), the arguments are passed as an array.
360 |
361 | Here's an example:
362 |
363 | ```js
364 | function greet(name) {
365 | console.log(`Hello, ${name}!`);
366 | }
367 |
368 | greet.call(null, 'Alice'); // Hello, Alice!
369 | greet.apply(null, ['Bob']); // Hello, Bob!
370 | ```
371 | In this example, both call and apply are used to call the greet function with a null this value and a single argument.
372 |
373 | ### What is the difference between .bind() and .call()?
374 | .bind(), like .call() and .apply(), can be used to call a function with a specific this value and a set of arguments. However, instead of immediately invoking the function, it returns a new function that, when called, will have the specified this value and arguments.
375 |
376 | Here's an example:
377 |
378 | ```js
379 | const person = {
380 | name: 'Alice',
381 | greet() {
382 | console.log(`Hello, my name is ${this.name}.`);
383 | }
384 | };
385 |
386 | const greetAlice = person.greet.bind(person);
387 | greetAlice(); // Hello, my name is Alice.
388 |
389 | ```
390 |
391 | ### What is the arguments object in JavaScript?
392 | The arguments object is a special object that is available inside every function in JavaScript. It contains an array-like list of the arguments that were passed to the function.
393 |
394 | Here's an example:
395 |
396 | ```js
397 | function sum() {
398 | let total = 0;
399 | for (let i = 0; i < arguments.length; i++) {
400 | total += arguments[i];
401 | }
402 | return total;
403 | }
404 |
405 | console.log(sum(1, 2, 3, 4)); // 10
406 | ```
407 | In this example, the sum function uses the arguments object to calculate the sum of all its arguments.
408 |
409 | ### What is a rest parameter in JavaScript?
410 | A rest parameter is a special parameter in a function that allows for an arbitrary number of arguments to be passed to the function as an array
411 |
412 | ```js
413 | function sum(...numbers) {
414 | let total = 0;
415 | for (let num of numbers) {
416 | total += num;
417 | }
418 | return total;
419 | }
420 |
421 | console.log(sum(1, 2, 3)); // Output: 6
422 | console.log(sum(4, 5, 6, 7)); // Output: 22
423 | console.log(sum(10)); // Output: 10
424 | console.log(sum()); // Output: 0
425 | ```
426 |
427 | In this example, the sum function accepts any number of arguments using the rest parameter syntax (...numbers). Inside the function, the rest parameter numbers is treated as an array that contains all the arguments passed to the function.
428 |
429 | The function then uses a for loop to iterate through the array and calculate the total sum of all the numbers. Finally, the function returns the total sum.
430 |
431 | This allows us to call the sum function with any number of arguments, and it will calculate the sum correctly.
432 |
433 | # Objects
434 |
435 | ### What is an object in JavaScript?
436 | In JavaScript, an object is a collection of properties and methods, represented as key-value pairs. Properties can be any value, including other objects, and methods are functions that are associated with the object.
437 |
438 | Objects can be created using object literals, constructor functions, and the Object.create() method.
439 |
440 | ```js
441 | // Object literal syntax
442 | const person = {
443 | name: 'John',
444 | age: 30,
445 | sayHello: function() {
446 | console.log(`Hello, my name is ${this.name}`);
447 | }
448 | };
449 |
450 | // Constructor function
451 | function Person(name, age) {
452 | this.name = name;
453 | this.age = age;
454 | this.sayHello = function() {
455 | console.log(`Hello, my name is ${this.name}`);
456 | }
457 | }
458 |
459 | // Object.create() method
460 | const personProto = {
461 | sayHello: function() {
462 | console.log(`Hello, my name is ${this.name}`);
463 | }
464 | };
465 |
466 | const person = Object.create(personProto);
467 | person.name = 'John';
468 | person.age = 30;
469 | ```
470 |
471 |
472 | ### What is the difference between an object and an array in JavaScript?
473 | In JavaScript, an object is a collection of properties and methods, represented as key-value pairs. Properties can be any value, including other objects, and methods are functions that are associated with the object.
474 |
475 | On the other hand, an array is a collection of values, stored in a specific order and accessed using a numeric index.
476 |
477 | ```js
478 | // Object example
479 | const person = {
480 | name: 'John',
481 | age: 30,
482 | sayHello: function() {
483 | console.log(`Hello, my name is ${this.name}`);
484 | }
485 | };
486 |
487 | // Array example
488 | const numbers = [1, 2, 3, 4, 5];
489 | ```
490 |
491 | ### What is prototypal inheritance in JavaScript?
492 | Prototypal inheritance is a mechanism in JavaScript that allows objects to inherit properties and methods from other objects. Each object in JavaScript has an internal property called `[[Prototype]]`, which refers to another object from which it inherits its properties.
493 |
494 | If an object doesn't have a particular property or method, JavaScript looks for it in its prototype object, and if it's still not found, it looks in the prototype's prototype and so on, until it reaches the top of the prototype chain.
495 |
496 | ```js
497 | // Example of prototypal inheritance
498 | const personProto = {
499 | sayHello: function() {
500 | console.log(`Hello, my name is ${this.name}`);
501 | }
502 | };
503 |
504 | const person = Object.create(personProto);
505 | person.name = 'John';
506 | person.age = 30;
507 | person.sayHello(); // Output: "Hello, my name is John"
508 | ```
509 |
510 | In this example, personProto is an object that contains a sayHello method. We then create a new object person using Object.create(), and set it `[[Prototype]]` to personProto. This means that person inherits the sayHello method from
511 |
512 | ### What is the Object.create() method in JavaScript?
513 | The Object.create() method in JavaScript creates a new object with a specified prototype object and any additional properties you want to add to the object.
514 |
515 | ```js
516 | const personProto = {
517 | sayHello: function() {
518 | console.log(`Hello, my name is ${this.name}`);
519 | }
520 | };
521 |
522 | const person = Object.create(personProto, {
523 | name: { value: 'John' },
524 | age: { value: 30 }
525 | });
526 |
527 | person.sayHello(); // Output: "Hello, my name is John"
528 | ```
529 | ### What is the new keyword in JavaScript?
530 | In JavaScript, the new keyword is used to create an instance of a constructor function. When a function is defined with the function keyword and intended to be used as a constructor, the convention is to capitalize the first letter of the function name. This is not a requirement, but a convention that makes it easier to identify constructors in code.
531 |
532 | When a constructor function is invoked with the new keyword, several things happen:
533 |
534 | A new empty object is created.
535 | The this keyword is set to point to the new object.
536 | The function body is executed with the this keyword referring to the new object.
537 | The newly created object is returned by default, unless the function explicitly returns another object.
538 | Here's an example of a constructor function and how to use it with the new keyword:
539 |
540 | ```js
541 | function Person(name, age) {
542 | this.name = name;
543 | this.age = age;
544 | }
545 |
546 | const person1 = new Person("Alice", 30);
547 | const person2 = new Person("Bob", 25);
548 |
549 | console.log(person1); // Output: Person { name: 'Alice', age: 30 }
550 | console.log(person2); // Output: Person { name: 'Bob', age: 25 }
551 | ```
552 |
553 | In this example, Person is a constructor function that takes two arguments: name and age. When the new keyword is used with Person, two new objects are created (person1 and person2), and the name and age properties are set for each object.
554 |
555 | ### What is a constructor function in JavaScript?
556 | A constructor function in JavaScript is a special type of function that is used to create and initialize objects created with the new keyword. A constructor function is similar to a regular function, but it is intended to be used as a blueprint for creating objects with the same properties and methods.
557 |
558 | When a constructor function is invoked with the new keyword, a new object is created and the this keyword is set to point to the new object. The properties and methods defined inside the constructor function can be used to initialize the new object.
559 |
560 | Here's an example of a constructor function:
561 |
562 | ```js
563 | function Car(make, model, year) {
564 | this.make = make;
565 | this.model = model;
566 | this.year = year;
567 | this.start = function() {
568 | console.log("Starting the " + this.make + " " + this.model);
569 | };
570 | }
571 |
572 | const myCar = new Car("Toyota", "Corolla", 2022);
573 | console.log(myCar); // Output: Car { make: 'Toyota', model: 'Corolla', year: 2022, start: [Function] }
574 | myCar.start(); // Output: Starting the Toyota Corolla
575 | ```
576 | In this example, Car is a constructor function that takes three arguments: make, model, and year. The properties make, model, and year are set on the new object created with the new keyword. The start method is also defined on the new object, and can be invoked to start the car.
577 |
578 | Constructor functions are a powerful tool for creating reusable code and encapsulating related properties and methods. They are often used in object-oriented programming to define classes and create instances of those classes.
579 |
580 | # Arrays
581 |
582 | ### What is an array in JavaScript?
583 | An array is a special type of object used to store multiple values in a single variable. Arrays can hold values of any data type, including other arrays. The values in an array are referred to as elements, and each element has a unique index number that represents its position in the array.
584 |
585 | ### What is the difference between .forEach() and .map()?
586 | The forEach() and map() methods are both used to iterate over an array and perform a function on each element. However, there are some differences between the two methods:
587 |
588 | forEach() modifies the original array, while map() returns a new array with the modified elements.
589 | forEach() does not return anything, while map() returns an array.
590 | map() is more suitable when you want to create a new array with the same number of elements as the original array, but with each element transformed in some way.
591 | Here's an example to illustrate the differences between `forEach()` and `map()`:
592 |
593 | ```js
594 | const numbers = [1, 2, 3, 4, 5];
595 |
596 | // forEach
597 | numbers.forEach((num, index) => {
598 | numbers[index] = num * 2;
599 | });
600 | console.log(numbers); // [2, 4, 6, 8, 10]
601 |
602 | // map
603 | const doubledNumbers = numbers.map(num => num * 2);
604 | console.log(doubledNumbers); // [4, 8, 12, 16, 20]
605 | console.log(numbers); // [2, 4, 6, 8, 10]
606 |
607 | ```
608 |
609 | ### What is the difference between .slice() and .splice()?
610 | The slice() and splice() methods are both used to extract a portion of an array, but they have some differences:
611 |
612 | slice() returns a new array containing the extracted elements, while splice() modifies the original array by removing or replacing elements.
613 | slice() does not modify the original array, while splice() does.
614 | Here's an example to illustrate the differences between `slice()` and `splice()`:
615 |
616 | ```js
617 | const numbers = [1, 2, 3, 4, 5];
618 |
619 | // slice
620 | const slicedNumbers = numbers.slice(1, 4);
621 | console.log(slicedNumbers); // [2, 3, 4]
622 | console.log(numbers); // [1, 2, 3, 4, 5]
623 |
624 | // splice
625 | const splicedNumbers = numbers.splice(1, 3);
626 | console.log(splicedNumbers); // [2, 3, 4]
627 | console.log(numbers); // [1, 5]
628 | ```
629 |
630 | ### What is the difference between .shift() and .pop()?
631 | The shift() and pop() methods are both used to remove elements from an array, but they have some differences:
632 |
633 | shift() removes the first element of the array and returns it, while pop() removes the last element of the array and returns it.
634 | shift() modifies the original array, while pop() does.
635 |
636 | Here's an example to illustrate the differences between `shift()` and `pop()`:
637 |
638 | ```js
639 | const numbers = [1, 2, 3, 4, 5];
640 |
641 | // shift
642 | const shiftedNumber = numbers.shift();
643 | console.log(shiftedNumber); // 1
644 | console.log(numbers); // [2, 3, 4, 5]
645 |
646 | // pop
647 | const poppedNumber = numbers.pop();
648 | console.log(poppedNumber); // 5
649 | console.log(numbers); // [2, 3, 4]
650 |
651 | ```
652 |
653 | ### What is the Array.prototype.filter() method in JavaScript?
654 | The `filter()` method creates a new array with all elements that pass the test implemented by the provided function. It takes a callback function as its argument, which is used to test each element of the array. The callback function takes three arguments: the current element being processed, its index, and the array on which the filter() method was called.
655 |
656 | Here is an example that filters out all even numbers from an array:
657 |
658 | ```js
659 | const numbers = [1, 2, 3, 4, 5, 6];
660 | const evenNumbers = numbers.filter(number => number % 2 === 0);
661 | console.log(evenNumbers); // [2, 4, 6]
662 |
663 | ```
664 |
665 | In the example above, the callback function number => number % 2 === 0 tests whether each element of the numbers array is even. The filter() method then creates a new array evenNumbers that only contains the even numbers from the original array.
666 |
667 | ### What is the Array.prototype.reduce() method in JavaScript?
668 | The reduce() method is used to reduce the elements of an array to a single value. It takes a callback function as its argument, which is executed on each element of the array. The callback function takes two arguments: an accumulator and the current element being processed. The accumulator is the value returned from the previous iteration of the callback function, or the initial value passed to the `reduce()` method.
669 |
670 | Here is an example that uses the `reduce()` method to calculate the sum of an array of numbers:
671 |
672 | ```js
673 | const numbers = [1, 2, 3, 4, 5];
674 | const sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
675 | console.log(sum); // 15
676 | ```
677 |
678 | In the example above, the initial value of the accumulator is 0, and the callback function (accumulator, current) => accumulator + current adds each element of the numbers array to the accumulator, returning the sum of all elements. Finally, the reduce() method returns the final value of the accumulator, which is the sum of all elements of the array.
679 |
680 | # ES6 Features
681 |
682 | ### What are template literals in JavaScript?
683 | Template literals, introduced in ES6, are a new way of creating strings in JavaScript that allow for more dynamic and flexible string creation. They use backticks (`) instead of single or double quotes, and allow for the embedding of expressions and variables directly within the string using ${}.
684 |
685 | Example:
686 |
687 | ```js
688 | const name = "John";
689 | console.log(`Hello, ${name}!`);
690 | // Output: "Hello, John!"
691 |
692 | ```
693 |
694 | ### What are default parameters in JavaScript?
695 | Default parameters allow us to provide a default value for a function parameter if none is provided when the function is called. This makes our code more robust and helps us avoid common bugs caused by missing or undefined parameters.
696 |
697 | Example:
698 |
699 | ```js
700 | function greet(name = "World") {
701 | console.log(`Hello, ${name}!`);
702 | }
703 |
704 | greet(); // Output: "Hello, World!"
705 | greet("John"); // Output: "Hello, John!"
706 | ```
707 |
708 | ### What are destructuring assignments in JavaScript?
709 | Destructuring assignments allow us to extract values from arrays or objects and assign them to variables in a single line of code. This makes our code more concise and easier to read.
710 |
711 | Example:
712 |
713 | ```js
714 | // Destructuring an array
715 | const numbers = [1, 2, 3];
716 | const [a, b, c] = numbers;
717 | console.log(a, b, c); // Output: 1 2 3
718 |
719 | // Destructuring an object
720 | const person = {name: "John", age: 30};
721 | const {name, age} = person;
722 | console.log(name, age); // Output: John 30
723 | ```
724 |
725 |
726 | ### What is the spread operator in JavaScript?
727 | The spread operator is a way of expanding an array or object into individual elements. It allows us to concatenate arrays, pass arrays as arguments to functions, and create new arrays or objects with modified values.
728 |
729 | Example:
730 |
731 | ```js
732 | // Concatenating arrays
733 | const arr1 = [1, 2, 3];
734 | const arr2 = [4, 5, 6];
735 | const arr3 = [...arr1, ...arr2];
736 | console.log(arr3); // Output: [1, 2, 3, 4, 5, 6]
737 |
738 | // Passing arrays as arguments
739 | function sum(a, b, c) {
740 | return a + b + c;
741 | }
742 | const numbers = [1, 2, 3];
743 | const result = sum(...numbers);
744 | console.log(result); // Output: 6
745 |
746 | // Creating new arrays with modified values
747 | const arr = [1, 2, 3];
748 | const newArr = [...arr, 4];
749 | console.log(newArr); // Output: [1, 2, 3, 4]
750 |
751 | ```
752 |
753 | ### What is the class keyword in JavaScript?
754 | The class keyword in JavaScript was introduced in ECMAScript 2015 (ES6) as a way to create objects using a syntax similar to class definitions in object-oriented programming. It allows us to define a blueprint for creating objects with specific properties and methods.
755 |
756 | A class definition consists of a constructor method and any number of additional methods. The constructor method is called when a new instance of the class is created and is used to set initial values for the object's properties. The other methods define the behavior of the class and can be used by instances of the class to perform actions.
757 |
758 | Here is an example of a class definition for a simple Person object:
759 |
760 | ```js
761 |
762 | class Person {
763 | constructor(name, age) {
764 | this.name = name;
765 | this.age = age;
766 | }
767 |
768 | sayHello() {
769 | console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
770 | }
771 | }
772 | ```
773 |
774 | In this example, the Person class has a constructor method that sets the name and age properties for each instance of the class. It also has a sayHello method that logs a message to the console.
775 |
776 | To create a new instance of the Person class, we can use the new keyword:
777 |
778 | ```js
779 |
780 | const john = new Person('John', 30);
781 | john.sayHello(); // Output: Hello, my name is John and I am 30 years old.
782 |
783 | ```
784 |
785 | ### What is the super keyword in JavaScript?
786 | The super keyword in JavaScript is used inside a subclass constructor to call the constructor of its parent class. It is used to inherit the properties and methods of the parent class in the subclass.
787 |
788 | Here is an example of a parent `class Person` and a `child class Employee` that inherits from Person using the super keyword:
789 |
790 | ```js
791 | class Person {
792 | constructor(name, age) {
793 | this.name = name;
794 | this.age = age;
795 | }
796 | }
797 |
798 | class Employee extends Person {
799 | constructor(name, age, jobTitle) {
800 | super(name, age); // Call the constructor of the parent class
801 | this.jobTitle = jobTitle;
802 | }
803 |
804 | getJobTitle() {
805 | console.log(`My job title is ${this.jobTitle}.`);
806 | }
807 | }
808 |
809 | ```
810 |
811 | In this example, the Employee class extends the `Person` class using the extends keyword. The constructor method of Employee calls the constructor of `Person` using the `super` keyword, passing in the name and age arguments. The jobTitle property is then added to the Employee instance.
812 |
813 | The `getJobTitle` method is defined on the `Employee` class and can be called on an instance of the `Employee` class:
814 |
815 | ```js
816 | const john = new Employee('John', 30, 'Software Engineer');
817 | john.getJobTitle(); // Output: My job title is Software Engineer.
818 |
819 | ```
820 |
821 | ### What is the Symbol data type in JavaScript?
822 | The Symbol data type in JavaScript was introduced in ECMAScript 2015 (ES6) as a way to create unique, non-enumerable properties on objects. A Symbol is an immutable primitive value that can be used as a property key for an object.
823 |
824 | Here is an example of using a Symbol as a property key:
825 |
826 | ```js
827 | const mySymbol = Symbol('mySymbol');
828 | const myObj = {};
829 |
830 | myObj[mySymbol] = 'Hello, world!';
831 |
832 | console.log(myObj[mySymbol]); // Output: Hello, world!
833 | ```
834 |
835 | Symbols are useful for creating unique keys in objects, since each symbol is guaranteed to be unique. They are often used in APIs or libraries where there is a need to create keys for internal use that will not conflict with keys created by the user.
836 |
837 | For example, let's say we want to create a library with a method that accepts an object and a callback function. We want to store the object in a map, with a unique identifier that we can use to retrieve it later. We can use a symbol as the key, to ensure that there is no chance of the key conflicting with any keys the user might create:
838 |
839 | ```js
840 | const objectMap = new Map();
841 |
842 | function storeObject(obj, callback) {
843 | const id = Symbol();
844 | objectMap.set(id, obj);
845 | callback(id);
846 | }
847 |
848 | function getObject(id) {
849 | return objectMap.get(id);
850 | }
851 |
852 | const myObject = {name: 'John', age: 30};
853 | storeObject(myObject, (id) => {
854 | console.log(`Object stored with id: ${id.toString()}`);
855 | });
856 |
857 | const retrievedObject = getObject(mySymbol);
858 | console.log(retrievedObject); // {name: 'John', age: 30}
859 | ```
860 | In the example above, we create a new symbol as the key for each object that is stored in the objectMap using the set() method. The getObject() function retrieves the object from the map using the symbol as the key. The user of the library does not need to worry about generating unique keys themselves, since the library uses symbols to ensure uniqueness.
861 |
862 | # Promises
863 |
864 | ### What are promises in JavaScript?
865 | Promises are a feature in JavaScript that allow us to handle asynchronous operations. They represent a value that may not be available yet, but will be resolved in the future. A promise can either be resolved successfully or be rejected with an error.
866 |
867 | ### What is the difference between a promise and a callback?
868 | Callbacks and promises are both used to handle asynchronous operations. However, promises provide a more elegant and structured way to handle asynchronous code than callbacks. Promises allow us to chain asynchronous operations, handle errors more easily, and avoid the callback hell problem.
869 |
870 | ### What is the .then() method in promises?
871 | The .then() method is used to handle the successful completion of a promise. It takes one or two callbacks as arguments. The first callback is called when the promise is resolved successfully, and it receives the resolved value as its argument. The second callback is an optional error handler, which is called when the promise is rejected.
872 |
873 | ```js
874 | // Example usage of .then() method
875 | somePromise.then(
876 | function(result) {
877 | // Handle successful result
878 | },
879 | function(error) {
880 | // Handle error
881 | }
882 | );
883 |
884 | ```
885 |
886 | ### What is the .catch() method in promises?
887 | The .catch() method is used to handle errors that occur during the execution of a promise. It takes one callback as an argument, which is called when the promise is rejected. The .catch() method is a shorthand way of handling errors in promises, and is equivalent to calling `.then(undefined, errorhandler).`
888 |
889 | ```js
890 | // Example usage of .catch() method
891 | somePromise.catch(function(error) {
892 | // Handle error
893 | });
894 | ```
895 |
896 | ### What is the .finally() method in promises?
897 | The .finally() method is used to execute code regardless of whether a promise is resolved or rejected. It takes one callback as an argument, which is called when the promise is settled (either resolved or rejected).
898 |
899 | ```js
900 | // Example usage of .finally() method
901 | somePromise.finally(function() {
902 | // Execute this code regardless of whether the promise was resolved or rejected
903 | });
904 | ```
905 |
906 | ### What is the Promise.all() method in JavaScript?
907 | The Promise.all() method is used to execute multiple promises in parallel and wait for all of them to complete. It takes an array of promises as an argument and returns a new promise that resolves when all of the input promises have resolved, or rejects when any of the input promises rejects.
908 |
909 | ```js
910 | // Example usage of Promise.all() method
911 | Promise.all([promise1, promise2, promise3])
912 | .then(function(results) {
913 | // Handle results
914 | })
915 | .catch(function(error) {
916 | // Handle error
917 | });
918 | ```
919 |
920 | Here is a flowchart for better explanation:
921 |
922 | ```js
923 | +---(resolve)---+
924 | | |
925 | Promise.all | +---(resolve)---+
926 | | | |
927 | +--| +---(resolve)---+
928 | | | |
929 | +--| +---(resolve)---+
930 | | |
931 | +---(resolve)---+
932 |
933 | ```
934 |
935 | ### What is the Promise.race() method in JavaScript?
936 | The Promise.race() method is used to execute multiple promises in parallel and wait for the first one to complete, regardless of whether it resolves or rejects. It takes an array of promises as an argument and returns a new promise that resolves or rejects with the result of the first promise that completes.
937 |
938 | ```js
939 | // Example usage of Promise.race() method
940 | Promise.race([promise1, promise2, promise3])
941 | .then(function(result) {
942 | // Handle result
943 | })
944 | .catch(function(error) {
945 | // Handle error
946 | });
947 |
948 | ```
949 |
950 | Here is a flowchart for `Promise.race()`
951 |
952 | ```js
953 | +---(resolve/reject)---+
954 | | |
955 | Promise.race | +---(resolve/reject)---+
956 | | | |
957 | +--| +---(resolve/reject)---+
958 | | | |
959 | +--| +---(resolve/reject)---+
960 | | |
961 | +---(resolve/reject)---+
962 |
963 | ```
964 |
965 | ### What is the Promise.allSettled() method in Javascript?
966 |
967 | `Promise.allSettled()` is a method in JavaScript that returns a `promise` that resolves after all of the given promises have either `fulfilled or rejected`, with an array of objects that each describe the outcome of each promise. It was introduced in ES2020.
968 |
969 | The objects returned by Promise.allSettled() will have the following shape:
970 |
971 | status: A string indicating whether the promise was fulfilled or rejected.
972 | value or reason: Depending on the status, either the fulfillment value or the rejection reason of the promise.
973 | Here is an example code snippet that demonstrates the usage of Promise.allSettled():
974 |
975 | ```js
976 | const promises = [
977 | Promise.resolve('Success!'),
978 | Promise.reject('Error!'),
979 | Promise.resolve('Another success!'),
980 | ];
981 |
982 | Promise.allSettled(promises)
983 | .then(results => {
984 | console.log(results);
985 | });
986 | ```
987 |
988 | In this example, we are passing an array of three promises to Promise.allSettled(). The first and third promises will be fulfilled with the strings 'Success!' and 'Another success!', respectively. The second promise will be rejected with the string 'Error!'. After all promises have settled, the .then() callback will be called with an array of three objects describing the outcome of each promise. Here is the expected output:
989 |
990 | ```js
991 | [
992 | { status: 'fulfilled', value: 'Success!' },
993 | { status: 'rejected', reason: 'Error!' },
994 | { status: 'fulfilled', value: 'Another success!' },
995 | ]
996 | ```
997 |
998 | Here is a flowchart that visualizes the process of using Promise.allSettled():
999 |
1000 | ```js
1001 | ┌──────────────────────────┐
1002 | │ Promise.allSettled │
1003 | │ │
1004 | └──────────────────────────┘
1005 | │
1006 | │
1007 | ┌────────┴────────┐
1008 | │ │
1009 | Promise.resolve Promise.reject
1010 | │ │
1011 | ▼ ▼
1012 | ┌────────────────┐ ┌─────────────────┐
1013 | │ Fulfilled │ │ Rejected │
1014 | └────────────────┘ └─────────────────┘
1015 | │ │
1016 | │ │
1017 | ┌──────────┴────────┐ ┌───────┴───────┐
1018 | │ │ │ │
1019 | ┌─────────┐ ┌─────────┐ ┌─────────┐
1020 | │ Value: │ │ Reason: │ │ Value: │
1021 | │ 'Success!' │ │ 'Error!'│ │'Another'│
1022 | └─────────┘ └─────────┘ │ 'success!' │
1023 | └─────────┘
1024 | ```
1025 |
1026 | As we can see from the flowchart, Promise.allSettled() creates a new promise that waits for all of the input promises to either fulfill or reject. Once all of the input promises have settled, Promise.allSettled() resolves with an array of objects describing the outcome of each promise.
1027 |
1028 |
1029 | ### What is the async keyword in JavaScript?
1030 |
1031 | The async keyword is used to declare an asynchronous function in JavaScript. It allows a function to be executed asynchronously by returning a promise, and lets you use the await keyword inside the function to wait for the completion of a promise before continuing with the execution of the function.
1032 |
1033 | ### What is the await keyword in JavaScript?
1034 |
1035 | The await keyword is used to wait for the completion of a promise before continuing with the execution of an async function. It can only be used inside an async function, and it pauses the execution of the function until the promise is resolved or rejected. Once the promise is resolved, the result of the promise is returned, and if the promise is rejected, an error is thrown.
1036 |
1037 | Here's an example of using async and await:
1038 |
1039 | ```js
1040 | async function getUserData(userId) {
1041 | try {
1042 | const response = await fetch(`https://api.example.com/users/${userId}`);
1043 | const userData = await response.json();
1044 | return userData;
1045 | } catch (error) {
1046 | console.error(error);
1047 | }
1048 | }
1049 | ```
1050 |
1051 | In this example, the getUserData function is declared as async, which allows us to use the await keyword inside the function. The function makes a GET request to the `https://api.example.com/users/${userId}` endpoint, and waits for the response using the await keyword. Once the response is received, the function waits for the response body to be parsed as JSON using await response.json(). Finally, the function returns the user data. If any errors occur during the execution of the function, they are caught and logged to the console using a try...catch block.
1052 |
1053 | ### What is the difference between async/await and promises?
1054 | Async/await is a syntactical sugar on top of Promises, and they both work together to handle asynchronous operations in JavaScript. The main difference is that async/await allows for more concise and readable code, especially when dealing with complex chains of asynchronous operations.
1055 |
1056 | ### How do you handle errors in async/await?
1057 | You can handle errors in async/await using the try/catch block. Any errors that occur within the try block will be caught and handled by the catch block. You can also use `.catch()` on the Promise returned by the async function to handle errors.
1058 |
1059 | ### What is the try/catch block in JavaScript?
1060 | The try/catch block is a mechanism in JavaScript that allows you to handle errors in a more controlled and structured way. The try block contains the code that may throw an error, and the catch block contains the code to handle the error if it occurs. This helps to prevent the entire program from crashing due to unhandled errors.
1061 |
1062 | ### How do you use async/await with Promise.all()?
1063 | You can use async/await with Promise.all() to wait for all promises to resolve before continuing with the code. Here's an example:
1064 |
1065 | ```js
1066 | async function fetchData() {
1067 | const [data1, data2, data3] = await Promise.all([
1068 | fetch('https://api.example.com/data1'),
1069 | fetch('https://api.example.com/data2'),
1070 | fetch('https://api.example.com/data3')
1071 | ]);
1072 | // Code to handle the fetched data
1073 | }
1074 | ```
1075 |
1076 | In the above example, Promise.all() is used to fetch data from three different APIs. The await keyword is used to wait for all three promises to resolve before destructuring the results into data1, data2, and data3 variables.
1077 |
1078 | # DOM (Document Object Model) Manupulation
1079 |
1080 | ### What is the Document Object Model (DOM) in JavaScript?
1081 | The Document Object Model, or DOM for short, is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript.
1082 |
1083 | Here's a flowchart that summarizes the basics of the DOM:
1084 |
1085 | ```yaml
1086 | Start
1087 | |
1088 | v
1089 | Load Page
1090 | |
1091 | v
1092 | DOM is built
1093 | |
1094 | v
1095 | JavaScript can access and modify the DOM
1096 | |
1097 | v
1098 | User sees changes
1099 | |
1100 | v
1101 | End
1102 | ```
1103 |
1104 | ### What is the difference between innerHTML and textContent?
1105 | `innerHTML` and `textContent` are both properties of DOM elements in JavaScript.
1106 |
1107 | `innerHTML` sets or returns the HTML content inside an element, including any tags and their attributes. For example, if you have an HTML element
1108 | ```js
1109 | Hello world!
1110 | ```
1111 | then `document.getElementById("myParagraph").innerHTML` would return
1112 |
1113 | ```"Hello world!".```
1114 |
1115 | `textContent` sets or returns only the text content of an element, without any **HTML tags or attributes**. In the above example, document.getElementById("myParagraph").textContent would return `"Hello world!"`.
1116 |
1117 | Here's a flowchart that illustrates the difference between innerHTML and textContent:
1118 |
1119 | ```yaml
1120 | Start
1121 | |
1122 | v
1123 | Select Element
1124 | |
1125 | v
1126 | innerHTML or textContent?
1127 | |
1128 | | innerHTML
1129 | v
1130 | Modify HTML content
1131 | |
1132 | v
1133 | User sees changes
1134 | |
1135 | v
1136 | End
1137 | ```
1138 |
1139 | ### What is the querySelector() method in JavaScript?
1140 | querySelector() is a method of the document object in JavaScript. It allows you to select and manipulate DOM elements using CSS selector syntax.
1141 |
1142 | For example, document.querySelector("#myButton") would select the first element on the page with an id of myButton. You can also use other CSS selectors like class names, element types, and attribute values to select elements.
1143 |
1144 | Here's a flowchart that shows how to use querySelector():
1145 |
1146 | ```sql
1147 | Start
1148 | |
1149 | v
1150 | Select Element(s) with querySelector()
1151 | |
1152 | v
1153 | Manipulate Selected Element(s)
1154 | |
1155 | v
1156 | User sees changes
1157 | |
1158 | v
1159 | End
1160 | ```
1161 | ### What is the addEventListener() method in JavaScript?
1162 | addEventListener() is a method of DOM elements in JavaScript. It allows you to attach an event handler function to an element, which will be executed when the specified event occurs.
1163 |
1164 | For example, document.getElementById("myButton").addEventListener("click", myFunction) would attach the function myFunction to the click event of the element with id of myButton.
1165 |
1166 | Here's a flowchart that shows how to use addEventListener():
1167 |
1168 | ```vbnet
1169 | Start
1170 | |
1171 | v
1172 | Select Element to Add Event Listener to
1173 | |
1174 | v
1175 | Specify Event Type and Handler Function
1176 | |
1177 | v
1178 | User Performs Action to Trigger Event
1179 | |
1180 | v
1181 | Event Occurs, Handler Function is Executed
1182 | |
1183 | v
1184 | End
1185 | ```
1186 |
1187 | ### What is event delegation in JavaScript?
1188 | Event delegation is a technique in JavaScript where instead of attaching an event listener to every single child element in a parent element, you attach a single event listener to the parent element itself. When the event occurs on a child element, the event bubbles up the DOM tree until it reaches the parent element, which can then handle the event.
1189 |
1190 | This can be useful for performance reasons, as attaching event listeners to a large number of child elements can be slow and inefficient. It can also simplify your code, as you only need to write one event listener instead of many.
1191 |
1192 | Here's a flowchart that shows how event delegation works:
1193 |
1194 | ```vbnet
1195 | Start
1196 | |
1197 | v
1198 | Select Parent Element
1199 | |
1200 | v
1201 | Attach Event Listener to Parent Element
1202 | |
1203 | v
1204 | User Performs Action on Child Element
1205 | |
1206 | | Event Bubbles Up to Parent Element?
1207 | |<---------------------- Yes
1208 | v
1209 | Event is Handled by Parent Element
1210 | |
1211 | v
1212 | End
1213 | ```
1214 |
1215 | In summary, the Document Object Model (DOM) is a programming interface for web documents that can be modified with JavaScript. innerHTML and textContent are properties of DOM elements that allow you to modify their content. querySelector() allows you to select elements using CSS selectors, and addEventListener() allows you to attach event handlers to elements. Event delegation is a technique that can improve performance and simplify code by attaching a single event listener to a parent element instead of many child elements.
1216 |
1217 | # Browser APIs
1218 |
1219 | ### What are browser APIs in JavaScript?
1220 | Browser APIs (Application Programming Interfaces) are built-in interfaces in web browsers that allow JavaScript code to interact with the browser and perform tasks such as modifying the DOM, making HTTP requests, and storing data locally. Examples of browser APIs include the DOM API, the Fetch API, and the Web Storage API.
1221 |
1222 | Here's a flowchart that illustrates the relationship between JavaScript, the browser, and browser APIs:
1223 |
1224 | ```sql
1225 | Start
1226 | |
1227 | v
1228 | Write JavaScript Code
1229 | |
1230 | v
1231 | JavaScript Interacts with Browser APIs
1232 | |
1233 | v
1234 | Browser APIs Interact with Browser
1235 | |
1236 | v
1237 | User Sees Changes in Browser
1238 | |
1239 | v
1240 | End
1241 | ```
1242 |
1243 | ### What is the localStorage API in JavaScript?
1244 | The localStorage API is a web storage API in JavaScript that allows you to store data locally in a user's web browser. The data is stored as key-value pairs, and persists even after the user closes and reopens their browser.
1245 |
1246 | Here's a flowchart that shows how to use the localStorage API:
1247 |
1248 | ```js Start
1249 | |
1250 | v
1251 | Store Data with localStorage.setItem()
1252 | |
1253 | v
1254 | Retrieve Data with localStorage.getItem()
1255 | |
1256 | v
1257 | End
1258 | ```
1259 |
1260 | ### What is the sessionStorage API in JavaScript?
1261 | The sessionStorage API is another web storage API in JavaScript that allows you to store data locally in a user's web browser, but the data only persists for the duration of the user's browser session. Once the user closes their browser, the data is cleared.
1262 |
1263 | Here's a flowchart that shows how to use the sessionStorage API:
1264 |
1265 | ```sql
1266 | Start
1267 | |
1268 | v
1269 | Store Data with sessionStorage.setItem()
1270 | |
1271 | v
1272 | Retrieve Data with sessionStorage.getItem()
1273 | |
1274 | v
1275 | End
1276 | ```
1277 |
1278 | ### What is the window object in JavaScript?
1279 | The window object is a built-in object in JavaScript that represents the browser window or tab that the JavaScript code is running in. It provides access to browser APIs, as well as global functions and properties like setTimeout() and console.log().
1280 |
1281 | Here's a flowchart that shows some of the things you can do with the window object:
1282 |
1283 | ```js
1284 | Start
1285 | |
1286 | v
1287 | Access Browser APIs with window.API()
1288 | |
1289 | v
1290 | Use Global Functions and Properties like window.setTimeout() and window.console.log()
1291 | |
1292 | v
1293 | Manipulate Browser Window with window.open() and window.close()
1294 | |
1295 | v
1296 | End
1297 |
1298 | ```
1299 |
1300 | ### What is the setTimeout() method in JavaScript?
1301 | The setTimeout() method is a function in JavaScript that allows you to schedule a function to be executed after a specified amount of time has elapsed. It takes two arguments: a function to execute, and the number of milliseconds to wait before executing the function.
1302 |
1303 | Here's a flowchart that shows how to use setTimeout():
1304 |
1305 | ```sql
1306 |
1307 | Start
1308 | |
1309 | v
1310 | Call setTimeout() with a Function and a Delay
1311 | |
1312 | v
1313 | Wait for Delay to Elapse
1314 | |
1315 | v
1316 | Execute Function
1317 | |
1318 | v
1319 | End
1320 |
1321 | ```
1322 | In summary, browser APIs in JavaScript provide a way to interact with the browser and perform tasks such as modifying the DOM, making HTTP requests, and storing data locally. The localStorage and sessionStorage APIs allow you to store data locally in the user's browser, the window object provides access to browser APIs and global functions and properties, and setTimeout() allows you to schedule a function to be executed after a delay.
1323 |
1324 |
1325 | # Performance & Event Loop:
1326 |
1327 | ### What is event loop in JavaScript?
1328 | The event loop is a fundamental concept in JavaScript that allows for asynchronous operations to be executed in a non-blocking way. It continuously listens for events and runs queued tasks, allowing the JavaScript engine to perform other operations in the meantime.
1329 |
1330 | Here's a flowchart that illustrates how the event loop works:
1331 |
1332 | ```vbnet
1333 | Start
1334 | |
1335 | v
1336 | Execute Synchronous Code
1337 | |
1338 | v
1339 | Handle Asynchronous Callbacks and Events with the Event Loop
1340 | |
1341 | v
1342 | Run Next Task in the Event Queue
1343 | |
1344 | v
1345 | End
1346 | ```
1347 |
1348 | ### What is the requestAnimationFrame() method in JavaScript?
1349 | The requestAnimationFrame() method is a built-in function in JavaScript that is used to schedule animations and other visual updates in a way that maximizes performance and reduces unnecessary CPU usage.
1350 |
1351 | Here's a code snippet that shows how to use requestAnimationFrame():
1352 |
1353 | ```js
1354 |
1355 | function animate() {
1356 | // Do something here
1357 | requestAnimationFrame(animate);
1358 | }
1359 | requestAnimationFrame(animate);
1360 | ```
1361 |
1362 | Here's a flowchart that illustrates how requestAnimationFrame() works:
1363 |
1364 | ```sql
1365 | Start
1366 | |
1367 | v
1368 | Call requestAnimationFrame() with Animation Function
1369 | |
1370 | v
1371 | Wait for Browser to Render Next Frame
1372 | |
1373 | v
1374 | Execute Animation Function
1375 | |
1376 | v
1377 | Repeat
1378 | |
1379 | v
1380 | End
1381 | ```
1382 |
1383 | ### What is memoization in JavaScript?
1384 | Memoization is a technique in JavaScript that involves caching the results of expensive function calls so that they can be quickly retrieved the next time the function is called with the same arguments. This can significantly improve performance in certain scenarios.
1385 |
1386 | Here's a code snippet that shows how to implement memoization in JavaScript:
1387 |
1388 | ```js
1389 | function memoize(func) {
1390 | const cache = {};
1391 | return function(...args) {
1392 | const key = JSON.stringify(args);
1393 | if (cache[key]) {
1394 | return cache[key];
1395 | } else {
1396 | const result = func.apply(this, args);
1397 | cache[key] = result;
1398 | return result;
1399 | }
1400 | };
1401 | }
1402 | ```
1403 | Here's a flowchart that illustrates how memoization works:
1404 |
1405 | ```sql
1406 | Start
1407 | |
1408 | v
1409 | Call Memoized Function with Arguments
1410 | |
1411 | v
1412 | Check Cache for Result
1413 | |
1414 | v
1415 | If Result is Cached, Return Result
1416 | |
1417 | v
1418 | If Result is Not Cached, Compute Result and Cache it
1419 | |
1420 | v
1421 | Return Result
1422 | |
1423 | v
1424 | End
1425 | ```
1426 |
1427 | ### What is lazy loading in JavaScript?
1428 | Lazy loading is a technique in JavaScript that involves delaying the loading of certain resources (such as images, videos, or scripts) until they are actually needed. This can improve the initial loading time of a web page and reduce unnecessary network usage.
1429 |
1430 | Here's a code snippet that shows how to implement lazy loading of images in JavaScript:
1431 |
1432 | ```js
1433 |
1434 |
17 |