“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

I could have updated and finished all the interview questions this morning, but I was really busy this morning, so I didn’t have time until now. Please forgive me

140000 | 400 multichannel JavaScript 🎓 interview questions with answers 🌠 items (the first part 1-100)

140000 | 400 multichannel JavaScript 🎓 interview questions with answers 🌠 items part ii (101-200)

140000 | 400 multichannel JavaScript 🎓 interview questions with answers 🌠 items (third part 201-300)

140000 | 400 multichannel JavaScript 🎓 interview questions with answers 🌠 items (the fourth part 301-370)

140000 | 400 multichannel JavaScript 🎓 interview questions with answers 🌠 items (the fifth part 371-424)

Serial number The problem
1 What are some possible ways to create objects in JavaScript?
2 What is a prototype chain?
3 What is the difference between call, apply and bind?
4 What is JSON and its common operations?
5 What is the purpose of the array slice() method?
6 What is the purpose of the array splice() method?
7 What’s the difference between slice() and splice()?
8 How do you compare Object and Map
9 What’s the difference between the == and === operators?
10 What is a lambda or an arrow function?
11 What is a first class function?
12 What is a first order function?
13 What is a higher order function?
14 What is a function of one variable?
15 What is a Curryized function?
16 What is a pure function?
17 What is the let keyword used for?
18 What’s the difference between let and var?
19 Why did you choose the name let as the keyword?
20 How do you redeclare variables in a switch block without errors?
21 What is a temporary dead zone?
22 What is IIFE (Perform function expressions immediately)?
23 What are the benefits of using modules?
24 What is memoization?
25 What is a reactor-based power lift?
26 What are classes in ES6?
27 What are closures?
28 What is a module?
29 Why do you need modules?
30 What is scope in javascript?
31 What is a Service Worker?
32 How to manipulate the DOM using the Service Worker?
33 How do you reuse information when the Service Worker restarts?
34 What is IndexedDB?
35 What is Web Storage?
36 What is a Post message?
37 What is a Cookie?
38 Why do you need cookies?
39 What are the options in a cookie?
40 How do you delete cookies?
41 What’s the difference between cookies, local storage, and session storage?
42 What are the main differences between localStorage and sessionStorage?
43 How do you access web storage?
44 What methods are available for session storage?
45 What are stored events and their event handlers?
46 Why do you need Web storage?
47 How do you check Web storage browser support?
48 How do you check web Workers browser support?
49 Take the example of a Web worker
50 What are web Worker restrictions on DOM?
51 What is a promise?
52 Why do YOU need promises?
53 What are the three states of a promise?
54 What is a callback function?
55 Why do we need a callback?
56 What is callback hell?
57 What is a server send event?
58 How do you receive event notifications from the server?
59 How do you check browser support for server send events?
60 What events are available from the server?
61 What are promise’s main rules?
62 What is a callback within a callback?
63 What is promise chaining?
64 What is promise.all?
65 What is the purpose of the RACE method in promise?
66 What is strict mode in javascript?
67 Why is strict mode needed?
68 How do you declare strict mode?
69 What is the purpose of the double exclamation mark?
70 What is the purpose of the delete operator?
71 What is a Typeof operator?
72 What is an undefined attribute?
73 What is a null value?
74 What’s the difference between null and undefined?
75 What is eval?
76 What’s the difference between Window and Document?
77 How do you access history in javascript?
78 How do you check if caps lock is on?
79 What is isNaN?
80 What’s the difference between an undeclared variable and an undefined variable?
81 What is a global variable?
82 What’s wrong with global variables?
83 What is a NaN property?
84 What is the purpose of the isFinite function?
85 What is an Event flow?
86 What is event bubbling?
87 What is event capturing?
88 How do you submit forms using JavaScript?
89 How do you find operating system details?
90 What’s the difference between document Load and DOMContentLoaded events?
91 What are the differences between Native, Host, and User Objects?
92 What are the tools or techniques for debugging JavaScript code?
93 What are the pros and cons of promises versus callbacks?
94 What is the difference between attribute and property?
95 What is a same-origin policy?
96 What is the purpose of void 0?
97 Is JavaScript a compiled or interpreted language?
98 Is JavaScript a case sensitive language?
99 Is there a relationship between Java and JavaScript?
100 What is an event?
101 Who created JavaScript?
102 What’s the preventDefault method use?
103 What’s the use of stopPropagation?
104 What steps does return false involve?
105 What is a BOM(Browser Object Model)?
106 What’s the use of setTimeout?
107 What’s the use of setInterval?
108 Why is JavaScript considered single threaded?
109 What is event Delegation?
110 What is ECMAScript?
111 What is JSON?
112 What are the syntax rules for JSON?
113 What is the purpose of JSON stringization?
114 How do you parse JSON strings?
115 Why do YOU need JSON?
116 What is a PWA?
117 What is the purpose of the clearTimeout method?
118 What is the purpose of the clearInterval method?
119 How do you redirect new pages in javascript?
120 How do you check if a string contains a substring?
121 How do you validate email in javascript?
122 How do you use javascript to get the current URL?
123 What are the various URL properties of the Location object?
124 How do I get a query string value in javascript?
125 How do I check if an object has a key?
126 How do you loop through or enumerate javascript objects?
127 How do you test an empty object?
128 What is a parameter object?
129 How do you capitalize the first letter of a string?
130 What are the pros and cons of for loops?
131 How do you display the current date in javascript?
132 How do you compare two date objects?
133 How do you check if a string starts with another string?
134 How do you clip strings in javascript?
135 How do you add a key-value pair in javascript?
136 ‘! Does the — ‘symbol represent a special operator?
137 How do you assign default values to variables?
138 How do you define a multi-line string?
139 What is an App Shell Model?
140 Can we define properties for functions?
141 What’s the way to find the number of arguments that a function expects?
142 What is a polyfill?
143 What are break and continue statements?
144 What is a JS tag?
145 What’s the good of putting the statement first?
146 What are the benefits of initializing variables?
147 What are the suggestions for creating new objects?
148 How do you define JSON arrays?
149 How do you generate random integers?
150 Can you write a random integer function to print integers in a range?
151 What is tree shaking?
152 What does it take for tree shaking?
153 Is eval recommended?
154 What is a regular expression?
155 What are the string methods available in regular expressions?
156 What are the modifiers in regular expressions?
157 What is a regular expression pattern?
158 What is a RegExp object?
159 How do I search for patterns in a string?
160 What is the purpose of the exec method?
161 How do I change the style of an HTML element?
162 What’s 1+2+’3′?
163 What is a debugger statement?
164 What is the purpose of debugging breakpoints?
165 Can I use reserved words as identifiers?
166 How do you detect mobile browsers?
167 How to detect mobile browsers without regular expressions?
168 How do you use JS to get the width and height of an image?
169 How do I synchronize HTTP requests?
170 How do I make asynchronous HTTP requests?
171 How do you convert a date to another time zone in javascript?
172 What is the property used to get the window size?
173 What are conditional operators in javascript?
174 Can you apply chaining to conditional operators?
175 What are some ways to execute javascript after the page loads?
176 What’s the difference between proto and prototype?
177 For example, you really need a semicolon
178 What is the freeze method?
179 What is the purpose of the freeze method?
180 Why do I need to use the freeze method?
181 How do you detect browser language preferences?
182 How to convert a string to title case using javascript?
183 How do you detect disabled javascript in a page?
184 What are the various operators supported by javascript?
185 What are REST parameters?
186 What happens if you don’t use the REST parameter as the last parameter?
187 What are the bitwise operators available in JavaScript?
188 What is the spread operator?
189 How do you determine if an object is frozen?
190 How do you determine whether two values are the same or not using an object?
191 What is the purpose of using Object’s IS method?
192 How do I copy properties from one object to another?
193 What are the applications of assignment methods?
194 What is a Proxy object?
195 What is the purpose of the SEAL method?
196 What are the applications of the SEAL method?
197 What’s the difference between the freeze and SEAL methods?
198 How to tell if an object is SEAL?
199 How do I get an enumerable key-value pair?
200 What are the main differences between the object. values and object. entries methods?
201 How do I get a list of keys for any object?
202 How do you create an object using Prototype?
203 What is a WeakSet?
204 What’s the difference between a WeakSet and a Set?
205 List the set of methods available on a WeakSet?
206 What is a WeakMap?
207 What is the difference between WeakMap and Map?
208 List the collection of methods available on WeakMap?
209 What is the purpose of Uneval?
210 How do you encode a URL?
211 How do you decode (decode) a URL?
212 How do you print the content of a web page?
213 What’s the difference between uneval and eval?
214 What is the anonymous function?
215 What is the priority between local and global variables?
216 What is a javascript accessor?
217 How do you define properties on object constructors?
218 What’s the difference between get and defineProperty?
219 What are the advantages of getters and setters?
220 Can I add getters and setters using defineProperty methods?
221 What is the purpose of switch-case?
222 What conventions do I need to follow to use SWtich Case?
223 What is a primitive data type?
224 What are the different ways to access object properties?
225 What are function parameter rules?
226 What is an error object?
227 When you receive a syntax error
228 What are the different error names for error objects?
229 What are the various statements in error handling?
230 What are the two types of loops in javascript?
231 What is NodeJS?
232 What is an Intl object?
233 How do you perform language-specific date and time formatting?
234 What is an iterator?
235 How does synchronous iteration work?
236 What is an event loop?
237 What is a call stack?
238 What is an event queue?
239 What is a decorator?
240 What are the properties of the Intl object?
241 What is a unary operator?
242 How do I sort the elements in an array?
243 What is the purpose of compareFunction when sorting arrays?
244 How do you reverse an array?
245 How do you find the minimum and maximum values in an array?
246 How do I find the minimum and maximum values without the math function?
247 What is a null statement and its purpose?
248 How do I obtain module metadata?
249 What is a comma operator?
250 What are the advantages of the comma operator?
251 What is typescript?
252 What’s the difference between javascript and typescript?
253 What are typescript’s advantages over javascript?
254 What is an object initializer?
255 What is a constructor?
256 What happens if you write a constructor multiple times in a class?
257 How to call the constructor of a superclass?
258 How do you get a prototype of an object?
259 What happens if I pass a string type to the getPrototype method?
260 How do I set the prototype of one object to another?
261 How do you check if an object is extensible?
262 How do I prevent object extension?
263 What are the different ways to make an object non-extensible?
264 How do I define multiple properties on an object?
265 What is MEAN in JavaScript?
266 What is confusion in javascript?
267 Why the need for confusion?
268 What is Minification?
269 What are the benefits of shrinking?
270 What’s the difference between obfuscation and encryption?
271 What are the commonly used miniaturization tools?
272 How do you perform form validation using javascript?
273 How do I perform form validation without javascript?
274 What are the DOM methods available for constraint validation?
275 What are the available constraints to validate DOM properties?
276 What is a valid attribute list?
277 Example using the rangeOverflow property?
278 Is enumeration provided in javascript?
279 What is enumeration?
280 How do you list all the properties of an object?
281 How do I get a property descriptor for an object?
282 What are the properties provided by the property descriptor?
283 How do you extend classes?
284 How do I change the URL without reloading the page?
285 How do I check if an array contains a specific value?
286 How do you compare scalar arrays?
287 How do I get a value from a get parameter?
288 How do you print numbers with a comma as a thousand delimiter?
289 What’s the difference between Java and javascript?
290 Does javascript support namespaces?
291 How do you declare a namespace?
292 How do I call javascript code in an iframe from a parent page?
293 How do I get a time zone offset from a date?
294 How to dynamically load CSS and JS files?
295 What are the different ways to find HTML elements in the DOM?
296 What is jQuery?
297 What is the V8 JavaScript engine?
298 Why do we call javascript a dynamic language?
299 What is an air freight operator?
300 How do I set cursor waiting?
301 How do you create an infinite loop?
302 Why do I need to avoid with statements?
303 What is the output of the following for loop?
304 List some features of ES6?
305 What is ES6?
306 Can I redeclare let and const variables?
307 Does const make the value immutable?
308 What are the default parameters?
309 What are template literals?
310 How do I write a multi-line string in template text?
311 What is a nested template?
312 What is a tag template?
313 What is a raw string?
314 What is deconstructive assignment?
315 What is the default value in the destruct assignment?
316 How do you swap variables in a deconstructed assignment?
317 What are enhanced object literals?
318 What is dynamic import?
319 What are the use cases for dynamic imports?
320 What is typed arrays?
321 What are the advantages of module loaders?
322 What is collation?
323 What is a… Of the statement?
324 What is the output of the expansion operator array?
325 Is PostMessage safe?
326 What’s wrong with a PostMessage target source being a wildcard?
327 How do you avoid receiving postMessages from attackers?
328 Can I avoid postMessages altogether?
329 Are postMessages synchronized?
330 What is the Javascript paradigm?
331 What’s the difference between internal and external javascript?
332 Is JavaScript faster than server-side scripting?
333 How do you get the status of a checkbox?
334 What is the purpose of the double tilde operator?
335 How do you convert characters to ASCII?
336 What is an array buffer?
337 What is the output of the following string expression?
338 What is the purpose of an Error object?
339 What is the purpose of an EvalError object?
340 What is the list of case errors thrown from non-strict mode to strict mode?
341 Are all objects prototypes?
342 What’s the difference between arguments and arguments?
343 What is the purpose of the some method in an array?
344 How do you combine two or more arrays?
345 What’s the difference between a shallow copy and a deep copy?
346 How do you create a specific number of copies of a string?
347 How do you return all matched strings based on a regular expression?
348 How do you trim strings at the beginning or end?
349 What is the output of the following console statement with a unary operator?
350 Does javascript use mixins?
351 What is the thunk function?
352 What is asynchronous Thunk?
353 What is the output of the following function call?
354 How do I remove all newlines from a string?
355 What’s the difference between backflow and redraw?
356 What happens when you negate an array?
357 What happens if we add two arrays?
358 What is the output of adding an addition operator to a false value?
359 How to use special characters to create from a string?
360 How to remove false values from an array?
361 How do you get the unique value of an array?
362 What is a deconstructive alias?
363 How do I map array values without using the Map method?
364 How do you empty an array?
365 How do you round a number to some decimal number?
366 What’s the easiest way to turn an array into an object?
367 How do you create an array with some data?
368 What is the placeholder for the console object?
369 Is it possible to add CSS to console messages?
370 What is the purpose of the dir method on console objects?
371 Is it possible to debug HTML elements in the console?
372 How do I use console objects to display data in tabular format?
373 How do you verify that a parameter is a number?
374 How do you create a copy to clipboard button?
375 What’s the shortcut to getting a timestamp?
376 How do you flatten multidimensional arrays?
377 What is the simplest multiconditional check?
378 How do you capture the browser back button?
379 How do I disable right-click on a Web page?
380 What is a wrapper object?
381 What is AJAX?
382 What are the different ways to handle asynchronous code?
383 How do I cancel an extraction request?
384 What is voip API?
385 What is the minimum timeout limit?
386 How do you implement zero timeout in modern browsers?
387 What is the task in the event loop?
388 What is a microtask?
389 What are the different event loops?
390 What is the purpose of queueMicrotask?
391 How do you use javascript libraries in typescript files?
392 What’s the difference between promises and observables?
393 What is a heap?
394 What is an event table?
395 What is a microtask queue?
396 What’s the difference between a shim and a polyfill?
397 How do you detect raw or non-raw value types?
398 What is Babel?
399 Is Node.js completely single-threaded?
400 What are common use cases for observables?
401 What is RxJS?
402 What’s the difference between a function constructor and a function declaration?
403 What is the short circuit state?
404 What’s the easiest way to resize an array?
405 What is observable?
406 What’s the difference between a function declaration and a class declaration?
407 What is an asynchronous function?
408 How do you prevent promises swallowing errors?
409 What is deno?
410 How do you make objects iterable in javascript?
411 What is the correct tail call?
412 How do you check if an object is a promise?
413 How do I check if a function is called as a constructor?
414 What is the difference between the Arguments object and the REST parameter?
415 What is the difference between extension operators and REST parameters?
416 What are the different types of generators?
417 What is a built-in iterable?
418 for… Of and the for… What’s the difference between in statements?
419 How do I define instance and non-instance properties?
420 What’s the difference between isNaN and number. isNaN?
421 How do I call IIFE without any extra parentheses?
422 Can I use expressions in switch cases?
423 What’s the easiest way to ignore promise errors?
424 How to style console output using CSS?

371. Can I debug HTML elements in the console?

Yes, you can fetch and debug HTML elements in the console just as you can inspect them.

const element = document.getElementsByTagName("body") [0];
console.log(element);
Copy the code

It prints HTML elements in the console,

We go back to problem 350, we know what we know


372. How do I use console objects to display data in tabular format?

The console.table() is used to visualize a complex array or object of data that is displayed in a table form on the console.

const users = [{ "name":"Haiyong"."id": 1."city": "Beijing"}, { "name":"Max"."id": 2."city": "London"}, { "name":"CSDN"."id": 3."city": "Paris"}];console.table(users);
Copy the code

Data visualized in tabular form,

== Attention == : Please remember,console.table()IE does not support this.

We go back to problem 350, we know what we know


373. How do you verify that a parameter is a number?

The combination of the IsNaN and isFinite methods is used to verify that the parameter is a number.

function isNumber(n){
   return !isNaN(parseFloat(n)) && isFinite(n);
}
Copy the code

We go back to problem 350, we know what we know


374. How do you create a copy to Clipboard button?

You need to select the content of the input element (using the.select() method) and use execCommand to execute the copy command (i.e. ExecCommand (‘copy’)). You can also perform other system commands, such as cut and paste.

document.querySelector("#copy-button").onclick = function() {
 // Select the content
 document.querySelector("#copy-input").select();
 // Copy to clipboard
 document.execCommand('copy');
};
Copy the code

We go back to problem 350, we know what we know


375. What is the shortcut to get a timestamp?

You can use new Date().gettime () to get the current timestamp. There is an alternative shortcut to get the value.

console.log(+new Date());
console.log(Date.now());
Copy the code

We go back to problem 350, we know what we know


376. How do you flattens multidimensional arrays?

Flattening two-dimensional arrays using the Spread operator is trivial.

const biDimensionalArr = [11[22.33], [44.55], [66.77].88.99];
constflattenArr = [].concat(... biDimensionalArr);[11, 22, 33, 44, 55,
Copy the code

But you can make it work for multi-dimensional arrays with recursive calls,

function flattenMultiArray(arr) {
   constflattened = [].concat(... arr);return flattened.some(item= > Array.isArray(item)) ? flattenMultiArray(flattened) : flattened;
}
const multiDimensionalArr = [11[22.33], [44[55.66[77[88]], 99]]];
const flatArr = flattenMultiArray(multiDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
Copy the code

We go back to problem 350, we know what we know


377. What is the simplest multiconditional check?

Instead of checking each value as a condition, you can use indexOf to compare the input to multiple values.

// Verbose approach
if (input === 'first' || input === 1 || input === 'second' || input === 2) {
 someFunction();
}
// Shortcut
if (['first'.1.'second'.2].indexOf(input) ! = = -1) {
 someFunction();
}
Copy the code

We go back to problem 350, we know what we know


378. How do you capture the browser back button?

The window.onbeforeUnload method is used to capture browser back button events. This helps alert users to the loss of current data.

window.onbeforeunload = function() {
   alert("You work will be lost");
};
Copy the code

We go back to problem 350, we know what we know


379. How do I disable right-click on a Web page?

You can disable right-clicking on the page by returning false from the property on the OnContextMenuBody element.

<body oncontextmenu="return false;">
Copy the code

We go back to problem 350, we know what we know


380. What is a wrapper object?

Raw values such as strings, numbers, and Booles have no properties or methods, but they are temporarily converted or cast into objects (wrapped objects) when you try to perform operations on them. For example, if you apply the toUpperCase() method to a raw string value, it does not throw an error but returns uppercase of the string.

let name = "csdn";
console.log(name.toUpperCase());  Log (new String(name).toupperCase ());
Copy the code

That is, every primitive except null and undefined has a wrapper object, and the wrapper object list is String, Number, Boolean, Symbol, and BigInt.

We go back to problem 350, we know what we know


381. What is AJAX?

AJAX stands for Asynchronous JavaScript and XML, which is a set of related technologies for asynchronously displaying data (HTML, CSS, JavaScript, XMLHttpRequest API, and so on). That is, we can send data to and get data from the server without reloading the web page.

We go back to problem 350, we know what we know


382. What are the different ways to handle asynchronous code?

Below is a list of different ways to handle asynchronous code.

3. Asynchronous/wait 4. Third-party libraries such as Async.js, Bluebird, etc

We go back to problem 350, we know what we know


383. How do I cancel an extraction request?

Until a few days ago, one of the drawbacks of native Promises was the inability to cancel a FETCH request directly. But the js specification for the new AbortController allows you to use signals to abort one or more FETCH calls.

The basic process for canceling a obtain request is as follows,

1. Create an AbortController instance 2. Get the signal properties of the instance and pass the signal as an option 3. For example, letting us pass the same signal to multiple FETCH calls will cancel all requests using that signal,

const controller = new AbortController();
const { signal } = controller;

fetch("http://localhost:8000", { signal }).then(response= > {
   console.log(`Request 1 is complete! `);
}).catch(e= > {
   if(e.name === "AbortError") {
       // We know it has been cancelled!}}); fetch("http://localhost:8000", { signal }).then(response= > {
   console.log(`Request 2 is complete! `);
}).catch(e= > {
    if(e.name === "AbortError") {
        // We know it has been cancelled!}});// Wait 2 seconds to abort both requests
setTimeout(() = > controller.abort(), 2000);
Copy the code

We go back to problem 350, we know what we know


384. What is voip API?

The Web speech API is used to enable modern browsers to recognize and synthesize speech (that is, convert speech data into Web applications). The API was introduced by the W3C community in 2012. It has two main parts,

SpeechRecognition (asynchronous Speech recognition or speech-to-text) : It provides the ability to recognize Speech context from audio input and respond accordingly. This is accessed through the SpeechRecognition interface. The following example shows how to use the API to retrieve text from speech,

window.SpeechRecognition = window.webkitSpeechRecognition || window.SpeechRecognition;  // webkitSpeechRecognition for Chrome and SpeechRecognition for FF
const recognition = new window.SpeechRecognition();
recognition.onresult = (event) = > { // SpeechRecognitionEvent type
 const speechToText = event.results[0] [0].transcript;
 console.log(speechToText);
}
recognition.start();
Copy the code

In this API, the browser will ask you to grant permission to use the microphone

SpeechSynthesis (text to speech) : It provides the ability to recognize and respond to speech context from audio input. This is accessed through the SpeechSynthesis interface. For example, the following code is used to get speech/speech from text,

if('speechSynthesis' in window) {var speech = new SpeechSynthesisUtterance('Hello World! ');
   speech.lang = 'en-US';
   window.speechSynthesis.speak(speech);
}
Copy the code

The above example can be tested on the Developer’s console in chrome(33+).

== Note == : This API is still a working draft and only available in Chrome and Firefox (of course Chrome only implements the specification)

We go back to problem 350, we know what we know


385. What is the minimum timeout limit?

Both the browser and the NodeJS javascript environment are throttled with a minimum latency greater than 0 milliseconds. This means that even if a delay of 0 milliseconds is set, it will not happen immediately.

Browsers: They have a minimum latency of 4 milliseconds. This limitation occurs when sequential calls are triggered due to callback nesting (a certain depth) or after a certain number of sequential intervals.

== Note == : The minimum delay for older browsers is 10 milliseconds.

Nodejs: They have a minimum delay of 1 millisecond. This limitation occurs when the delay is greater than 2147483647 or less than 1. The best example to explain this timeout restriction behavior is the sequence of the following code snippets.

function runMeFirst() {
   console.log('My script is initialized');
}
setTimeout(runMeFirst, 0);
console.log('Script loaded');
Copy the code

And the output will be in

Script loaded
My script is initialized
Copy the code

If you do not use setTimeout, the order of the logs will be sequential.

function runMeFirst() {
  console.log('My script is initialized');
}
runMeFirst();
console.log('Script loaded');
Copy the code

The output is,

My script is initialized
Script loaded
Copy the code

We go back to problem 350, we know what we know


386. How do you implement zero timeout in modern browsers?

Because of a minimum delay greater than 0ms, you cannot use setTimeout(fn, 0) to execute the code immediately. But you can use window.postMessage() to implement this behavior.

We go back to problem 350, we know what we know


387. What is the task in the event loop?

A task is any javascript code/program that is scheduled to run through standard mechanisms such as initially starting the program, running event call-back, or firing intervals or timeouts. All of these tasks are arranged in a task queue.

Here is a list of use cases to add tasks to a task queue,

1. When a new javascript program is executed directly from the console or is run from a

We go back to problem 350, we know what we know


388. What is a microtask?

A microtask is javascript code that needs to be executed immediately after the task/microtask currently being executed completes. They are essentially a blockage. That is, the main thread is blocked until the microtask queue is empty.

The main sources of microtasks are promise. resolve, promise. reject, MutationObservers, IntersectionObservers, etc

== Note == : All of these microtasks are processed in the same round of the event loop.

We go back to problem 350, we know what we know


389. What are the different cycles of events?

We go back to problem 350, we know what we know


What is the purpose of queueMicrotask?

We go back to problem 350, we know what we know


How do you use javascript libraries in typescript files?

As you know, not all JavaScript libraries or frameworks have TypeScript declarations. But if you still want to use libraries or frameworks in our TypeScript files without compiling errors, the only solution is declare keywords and variable declarations. For example, suppose you have a library called customLibrary, which has no TypeScript declaration, and customLibrary calls a namespace in the global namespace. You can use this library in typescript code, as shown below,

declare var customLibrary;
Copy the code

At run time, typescript supplies the type customLibrary to the variable as the any type. An alternative to not using declarative keywords is as follows

var customLibrary: any;
Copy the code

We go back to problem 350, we know what we know


392. What’s the difference between promises and observables?

Some major differences in tabular form

promises observables
Only one value is emitted at a time Emit multiple values (streams of values from zero to multiple) over a period of time
Natural desire; They will be called immediately Lazy nature; They need to call a subscription
A Promise is always asynchronous, even if it is resolved immediately An Observable can be synchronous or asynchronous
No operators are provided Provides operators such as Map, forEach, Filter, Reduce, retry, and retryWhen
Cannot cancel Use the unsubscribe() method to cancel

We go back to problem 350, we know what we know


393. What is a heap?

The heap (or memory heap) is the memory location where we hold objects when we define variables. That is, this is where all memory allocation and unallocation takes place. The heap and the call stack are the two containers of the JS runtime.

Whenever the runtime encounters variable and function declarations in the code, it stores them in the heap.

We go back to problem 350, we know what we know


394. What is an event table?

An event table is a data structure used to store and track all events that will be executed asynchronously after a period of time or after some API request is resolved. That is, every time you call the setTimeout function or call an asynchronous operation, it is added to the event table.

It doesn’t perform functions on its own. The main purpose of the event table is to track events and send them to the event queue, as shown in the figure below.

We go back to problem 350, we know what we know


395. What is a microtask queue?

The Microtask Queue is a new Queue where all tasks initiated by promise objects are processed before the callback Queue.

The microtask queue is processed before the next render and draw job. However, if these microtasks run for a long time, they can lead to decreased visual quality.

We go back to problem 350, we know what we know


396. What’s the difference between a shim and a polyfill?

Shim is a library that brings new apis to an old environment, using only the means of that environment. It doesn’t have to be limited to Web applications. For example, ES5-shim.js is used to emulate ES5 functionality on older browsers (mostly pre-IE9).

A polyfill, on the other hand, is a piece of code (or plug-in) that provides the technology that you (the developer) want the browser to provide locally.

In short, a Polyfill is a spacer for the browser API.

We go back to problem 350, we know what we know


397. How do you detect raw or non-raw value types?

In JavaScript, primitive types include Boolean, string, number, BigInt, NULL, Symbol, and undefined. Non-primitive types include objects. But you can easily identify them using the following features,

var myPrimitive = 30;
var myNonPrimitive = {};
function isPrimitive(val) {
   return Object(val) ! == val; } isPrimitive(myPrimitive); isPrimitive(myNonPrimitive);Copy the code

If the value is a primitive data type, the Object constructor creates a new wrapper Object for the value. But if the value is of a non-primitive data type (an Object), the Object constructor will give the same Object.

We go back to problem 350, we know what we know


398. What is Babel?

Babel is a JavaScript translator for converting ECMAScript 2015+ code to backward compatible JavaScript versions in current and older browsers or environments. Some of the main features are listed below,

2. Missing Polyfill functionality in the target environment (using @babel/Polyfill) 3. Source code conversion (or Codemods)

We go back to problem 350, we know what we know


Is 399.Node.js fully single-threaded?

Node is single-threaded, but some functions included in the Node.js library (such as fs module functions) are not. That is, their logic runs outside of the node.js single thread to improve the speed and performance of the program.

We go back to problem 350, we know what we know


400. What are common use cases for observables?

Some of the most common Observable use cases are network sockets with push notifications, changes in user input, repeat intervals, and so on

We know what we know. We go back to problem 400


401. What is RxJS?

RxJS (Reactive Extensions for JavaScript) is a library that uses Observables to implement Reactive programming, making it easier to write asynchronous or callback-based code. It also provides utility functions for creating and using Observables.

We know what we know. We go back to problem 400


What is the difference between a function constructor and a function declaration?

The created Function constructor does not create closures for its creation context, but they are always created at global scope. That is, a function can only access its own local and global-scope variables. Function declarations can also access external function variables (closures).

Let’s look at this difference through an example,

Function constructor:

var a = 100;
function createFunction() {
   var a = 200;
   return new Function('return a; ');
}
console.log(createFunction()()); / / 100
Copy the code

Function declaration:

var a = 100;
function createFunction() {
   var a = 200;
   return function func() {
       returna; }}console.log(createFunction()()); / / 200
Copy the code

We know what we know. We go back to problem 400


403. What is the short circuit state?

The short circuit condition applies to the condensed way of writing simple if statements. Let’s illustrate this scenario with an example. If you want to log in to a portal with authentication criteria, the expression is as follows,

if (authenticate) {
  loginToPorta();
}
Copy the code

Since javascript logical operators evaluate from left to right, you can simplify the above expression by using the && logical operator

authenticate && loginToPorta();
Copy the code

We know what we know. We go back to problem 400


404. What is the easiest way to resize an array?

The length property of an array can be used to quickly resize or empty an array. Let’s apply the length attribute to the number array to change the number of elements from 5 to 2,

var array = [1.2.3.4.5];
console.log(array.length); / / 5

array.length = 2;
console.log(array.length); / / 2
console.log(array); / / [1, 2]
Copy the code

Arrays can also be cleared

var array = [1.2.3.4.5];
array.length = 0;
console.log(array.length); / / 0
console.log(array); / / []
Copy the code

We know what we know. We go back to problem 400


405. What is observable?

An Observable is basically a function that returns a stream of values to an observer, synchronously or asynchronously, over time. The consumer can get the value by calling the subscribe() method.

Let’s look at a simple example of an Observable

import { Observable } from 'rxjs';

const observable = new Observable(observer= > {
 setTimeout(() = > {
   observer.next('Message from a Observable! ');
 }, 3000);
});

observable.subscribe(value= > console.log(value));
Copy the code

Note: Observables are not part of the JavaScript language yet, but it is recommended to add them to the language

We know what we know. We go back to problem 400


406. What’s the difference between a function declaration and a class declaration?

The main difference between function declarations and class declarations is in the case of the reactories. function declarations are promoted, but not class declarations.

Classes:

const user = new User(); // ReferenceError

class User {}
Copy the code

Constructor:

const user = new User(); // No error

function User() {}Copy the code

We know what we know. We go back to problem 400


407. What is an asynchronous function?

An asynchronous function is a function declared with the async keyword that can write asynchronous, committ-based behavior in a more concise style by avoiding commitment chains. These functions can contain zero or more await expressions.

Let’s look at the following example of an asynchronous function,

async function logger() {

 let data = await fetch('http://someapi.com/users'); // Pause until the fetch returns
 console.log(data)
}
logger();
Copy the code

It’s basically syntactic sugar for ES2015 promises and generators.

We know what we know. We go back to problem 400


408. How do you prevent promises swallowing errors?

JavaScript’s ES6 promises to make your life easier when working with asynchronous code without the need for callback pyramids and error handling on every two lines. But Promises have some pitfalls. One of the biggest is to swallow mistakes by default.

Suppose you want to print an error to the console in all of the following cases,

Promise.resolve('promised value').then(function() {
      throw new Error('error');
});

Promise.reject('error value').catch(function() {
      throw new Error('error');
});

new Promise(function(resolve, reject) {
      throw new Error('error');
});
Copy the code

But there are many modern JavaScript environments that don’t print any errors. You can solve this problem in different ways,

1. Add a catch block at the end of each chain: You can add a catch block at the end of each promise chain

Promise.resolve('promised value').then(function() {
   throw new Error('error');
}).catch(function(error) {
 console.error(error.stack);
});
Copy the code

But it’s hard to type for each commitment chain, and it’s lengthy.

2. Add completion methods: You can replace the THEN and catch blocks for the first solution with completion methods

Promise.resolve('promised value').done(function() {
   throw new Error('error');
});
Copy the code

Suppose you want to get the data using HTTP and then process the resulting data asynchronously. You can write done in the following block,

getDataFromHttp()
 .then(function(result) {
   return processDataAsync(result);
 })
 .done(function(processed) {
   displayData(processed);
 });
Copy the code

In the future, if the processing library API changes to synchronous, you can delete the done block, as shown below,

getDataFromHttp()
  .then(function(result) {
    return displayData(processDataAsync(result));
  })
Copy the code

Then you forget to add the done block to the THEN block resulting in a no-hint error.

ES6 Promises: Bluebird extends the ES6 Promises API to avoid the problems in the second solution. This library has a “default” onRejection handler that prints all errors from the rejected Promise to stderr. After installation, you can handle unhandled rejections

Promise.onPossiblyUnhandledRejection(function(error){
   throw error;
});
Copy the code

And discard the rejection, just process it with an empty capture

Promise.reject('error value').catch(function() {});
Copy the code

We know what we know. We go back to problem 400


409. What is deno?

Deno is a simple, modern, and secure JavaScript and TypeScript runtime that uses the V8 JavaScript engine and Rust programming language.

We know what we know. We go back to problem 400


410. How do you make objects iterable in javascript?

By default, normal objects are not iterable. But you can make an object iterable by defining attributes on it through symbol.iterator.

Let’s use an example to prove this,

const collection = {
 one: 1.two: 2.three: 3[Symbol.iterator]() {
   const values = Object.keys(this);
   let i = 0;
   return {
     next: () = > {
       return {
         value: this[values[i++]],
         done: i > values.length } } }; }};const iterator = collection[Symbol.iterator]();

console.log(iterator.next());    // → {value: 1, done: false}
console.log(iterator.next());    // → {value: 2, done: false}
console.log(iterator.next());    // → {value: 3, done: false}
console.log(iterator.next());    // → {value: undefined, done: true}
Copy the code

You can simplify this process by using generator functions,

const collection = {
  one: 1.two: 2.three: 3[Symbol.iterator]: function * () {
    for (let key in this) {
      yield this[key]; }}};const iterator = collection[Symbol.iterator]();
console.log(iterator.next());    // {value: 1, done: false}
console.log(iterator.next());    // {value: 2, done: false}
console.log(iterator.next());    // {value: 3, done: false}
console.log(iterator.next());    // {value: undefined, done: true}
Copy the code

We know what we know. We go back to problem 400


411. What is the correct tail call?

First, before we talk about “proper tail calls,” we should first understand tail calls. A tail call is a subroutine or function call that is executed as the final action of the calling function. While proper tail call (PTC) is a technique where the program or code does not create additional stack frames for recursion when a function call is tail call.

For example, the following header recursion of classical or factorial functions relies on the stack for each step. At each step, we have to deal with n times factorial of n minus 1.

function factorial(n) {
 if (n === 0) {
   return 1
 }
 return n * factorial(n - 1)}console.log(factorial(5)); / / 120
Copy the code

However, if you use tail-recursive functions, they continue to pass all the data they need into the recursion without relying on the stack.

function factorial(n, acc = 1) {
 if (n === 0) {
   return acc
 }
 return factorial(n - 1, n * acc)
}
console.log(factorial(5)); / / 120
Copy the code

The above pattern returns the same output as the first one. But the accumulator keeps track of total as a parameter, rather than using stack memory in the recursive call.

We know what we know. We go back to problem 400


412. How do you check if an object is a promise?

If you don’t know if a value is a Promise, wrap the value as promise.resolve (value), which returns a Promise

   function isPromise(object){
      if(Promise && Promise.resolve){
      return Promise.resolve(object) == object;
      }else{
      throw "Promise not supported in your environment"}}var i = 1;
   var promise = new Promise(function(resolve,reject){
      resolve()
   });

   console.log(isPromise(i)); // false
   console.log(isPromise(p)); // true
Copy the code

Another way is to check the.then() handler type

function isPromise(value) {
   return Boolean(value && typeof value.then === 'function');
}
var i = 1;
var promise = new Promise(function(resolve,reject){
   resolve()
});

console.log(isPromise(i)) // false
console.log(isPromise(promise)); // true
Copy the code

We know what we know. We go back to problem 400


413. How do I check if a function is called as a constructor?

You can use the new.target pseudo-property to check whether a function is called as a constructor (using the new operator) or as a regular function call.

New.target returns a reference to the constructor or function if it is called using the new operator. For function calls, new.target is undefined.

function Myfunc() {
   if (new.target) {
      console.log('called with new');
   } else {
      console.log('not called with new'); }}new Myfunc(); // called with new
Myfunc(); // not called with new
Myfunc.call({}); not called with new
Copy the code

We know what we know. We go back to problem 400


What is the difference between arguments objects and REST arguments?

There are three main differences between the Arguments object and the REST parameter

The arguments object is an array-like object, but not an array. The REST parameter is an array instance. 2. The arguments object does not support the sort, map, forEach, or pop methods. These methods can be used for REST parameters. 3. Rest arguments are just those that are not given separate names, and the argument object contains all the arguments passed to the function

We know what we know. We go back to problem 400


415. What is the difference between extended operators and REST parameters?

The Rest parameter collects all remaining elements into an array. The Spread operator, on the other hand, allows an iterable (array/object/string) to be extended to a single parameter/element. That is, Rest parameters are the opposite of extension operators.

We know what we know. We go back to problem 400


416. What are the different types of generators?

There are five types of generators,

1. Generator function declaration:

function* myGenFunc() {
    yield 1;
    yield 2;
    yield 3;
}
const genObj = myGenFunc();
Copy the code

2. Generator function expression:

const myGenFunc = function* () {
    yield 1;
    yield 2;
    yield 3;
};
const genObj = myGenFunc();
Copy the code

3. Generator method definitions in object literals:

const myObj = {
  * myGeneratorMethod() {
     yield 1;
     yield 2;
     yield 3; }};const genObj = myObj.myGeneratorMethod();
Copy the code

4. Generator method definition in class:

class MyClass {*myGeneratorMethod() {
     yield 1;
     yield 2;
     yield 3; }}const myObject = new MyClass();
const genObj = myObject.myGeneratorMethod();
Copy the code

5. Generator as computational property:

const SomeObj = {
*[Symbol.iterator] () {
 yield 1;
 yield 2;
 yield 3; }}console.log(Array.from(SomeObj)); // [1, 2, 3]
Copy the code

We know what we know. We go back to problem 400


417. What is a built-in iterable?

Here is a list of iterable objects built into javascript,

2. Strings: iterate over each character or Unicode code point. 3.Maps: iterate over its key-value pair 4. Sets: iterates over their elements 5. Parameters: special variables in a function that resemble arrays 6. DOM sets such as NodeList

We know what we know. We go back to problem 400


418. The for… Of and the for… What’s the difference between in statements?

for… In and for… The of statement iterates over js data structures. The only difference is what they iterate over:

for.. In All enumerable property keys of an iterator for.. Of Specifies the value of an iterable. Let’s use an example to explain this difference,

let arr = ['a'.'b'.'c'];

arr.newProp = 'newVlue';

// Key is the attribute key
for (let key in arr) {
console.log(key);
}

// value is the attribute value
for (let value of arr) {
console.log(value);
}
Copy the code

Because of the for… The in loop iterates over the keys of the object, and the first loop records 0, 1, 2, and newProp as it iterates over the array of objects. for.. The of loop iterates through the values of the ARR data structure and records a, B, and C in the console.

We know what we know. We go back to problem 400


419. How do I define instance and non-instance properties?

The Instance attribute must be defined in the class method. For example, the name and age attributes define internal constructors as follows,

class Person {
constructor(name, age) {
  this.name = name;
  this.age = age; }}Copy the code

However, you must define Static(class) and stereotype data properties outside of the ClassBody declaration. Let’s assign an age to the Person class as follows,

Person.staticAge = 30;
Person.prototype.prototypeAge = 40;
Copy the code

We know what we know. We go back to problem 400


420. What’s the difference between isNaN and Number. IsNaN?

1. IsNaN: the global function isNaN converts arguments to numbers and returns true if the resulting value isNaN. 2.Number.isNaN: This method does not convert parameters. But it returns true when the type is Number and the value is NaN. Let’s see the difference through an example,

isNaN(" hello ");// true
Number.isNaN('hello'); // false
Copy the code

We know what we know. We go back to problem 400


421. How do I call IIFE without any extra parentheses?

Calling a function expression immediately (IIFE) requires a pair of parentheses to wrap the function containing the statement set.

(function(dt) { 
 console.log(dt.toLocaleTimeString()); }) (new Date());
Copy the code

Since both IIFE and void operators discard the result of an expression, you can avoid the extra parentheses of void operatorfor IIFE, as shown below,

void function(dt) { 
 console.log(dt.toLocaleTimeString()); } (new Date());
Copy the code

We know what we know. We go back to problem 400


422. Can I use expressions in switch Cases?

You may have seen the expression used in the Switch condition, but you can also use it in the Switch case by assigning a truth value to the switch condition. Let’s take weather conditions based on temperature,

const weather = function getWeather(temp) {
 switch(true) {
     case temp < 0: return 'freezing';
     case temp < 10: return 'cold';
     case temp < 24: return 'cool';
     default: return 'unknown';
 }
 }(10);
Copy the code

We know what we know. We go back to problem 400


423. What’s the easiest way to ignore promise errors?

The easiest and safest way to ignore a Promise error is to invalidate it. This method is also ESLint friendly.

await promise.catch(e= > void e);
Copy the code

We know what we know. We go back to problem 400


424. How do I style console output using CSS?

You can use the CSS Formatting content specifier %c to add CSS styles to the console output. Console string messages can be attached to another parameter after the specifier and CSS style. Let’s use console.log and the CSS specifier to print red text, as shown below,

console.log("%cThis is a red text"."color:red");
Copy the code

You can also add more variety to the content. For example, you can change the font-size of the text above

console.log("%cThis is a red text with bigger font"."color:red; font-size
Copy the code

We know what we know. We go back to problem 400


I’ve been writing a tech blog for a long time, and this is one of my interview questions. Hope you like it!

More related articles and my contact information I put here:

Github.com/wanghao221 gitee.com/haiyongcsdn…

If you do learn something new from this post, like it, bookmark it and share it with your friends. 🤗 Finally, don’t forget ❤ or 📑 for support