This is the 30th day of my participation in the More Text Challenge. For more details, see more text Challenge

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)

I was going to finish the questions 301-424 in this essay, but the number of words is too much, about nineteen thousand to the upper limit, and at least twenty-three thousand words are needed, so I can only wait for the end of the next essay, please forgive me.

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?

301. How do you create an infinite loop?

You can use for and while loops to create infinite loops without using any expressions. As far as ESLint and code optimizer tools are concerned, the for loop construct, or syntax, is the better approach,

for (;;) {}
while(true) {}Copy the code

We know what we know. We go back to problem 300. Siko siko


302. Why do I need to avoid the with statement?

The WITH statement in JavaScript is intended to provide shorthand for writing repeated access to an object. Therefore, it can help reduce file size without degrading performance by reducing the need for repeated lengthy object references. Let’s take an example that is used to avoid redundancy when an object is accessed multiple times.

a.b.c.greeting = 'welcome';
a.b.c.age = 32;
Copy the code

Using with it becomes:

with(a.b.c) {
greeting = "welcome";
age = 32;
}
Copy the code

But this with statement can cause performance problems because one cannot predict whether a parameter refers to a real variable or to a property in the with parameter.

We know what we know. We go back to problem 300. Siko siko


303. What is the output of the following for loop?

for (var i = 0; i < 4; i++) { // Global scope
setTimeout(() = > console.log(i));
}

for (let i = 0; i < 4; i++) { // Block scope
setTimeout(() = > console.log(i));
}
Copy the code

The output of the above for loop is 4, 4, 4, 4 and 0, 1, 2, 3

Note: Due to javascript event queues/loops, the callback function is called after the setTimeout loop completes. Since the variable I is declared with the var keyword, it becomes a global variable and is iterated with a value equal to 4 when the time function is called by setTimeout. So the output of the first loop is 4, 4, 4, 4.

In the second loop, the variable I is declared as the let keyword, which becomes a block-scoped variable and holds a new value (0, 1,2, 3) for each iteration. So the output of the first loop is 0, 1, 2, 3.

We know what we know. We go back to problem 300. Siko siko


304. List some features of ES6?

Here’s a list of some of the new ES6 features,

Support for constant or immutable variables. 2. Support for block ranges of variables, constants, and functions. Arrow function 4. Default parameters 5.Rest and Spread parameters 6. 10.Promises 11.Classes 12.Modules

We know what we know. We go back to problem 300. Siko siko


305. What is ES6?

ES6 is the sixth version of the javascript language, which was released in June 2015. It was originally called ECMAScript 6 (ES6) and later renamed ECMAScript 2015. Almost all modern browsers support ES6, but for older browsers there are many translators, such as Babel.js, etc.

We know what we know. We go back to problem 300. Siko siko


306. Can I redeclare let and const variables?

No, you cannot redeclare lets and const variables. If you do, it throws the following error

Uncaught SyntaxError: Identifier 'someVariable' has already been declared
Copy the code

Note: a variable declaration with the var keyword refers to a function scope and is considered to be declared at the top of the enclosing scope due to the promotion feature. Therefore, all multiple declarations that contribute to the same promoted variable do not have any errors. Let’s take an example of redeclaring variables for var and let/const in the same scope.

var name = 'Haiyong';
function myFunc() {
var name = 'Nick';
var name = 'Abraham'; // Reallocate within the same function block
alert(name); // Abraham
}
myFunc();
alert(name); // Haiyong
Copy the code

Block scoped multiple declarations throw a syntax error,

let name = 'Haiyong';
function myFunc() {
let name = 'Nick';
let name = 'Abraham'; // Uncaught syntax error: identifier "name" has been declared
alert(name);
}

myFunc();
alert(name);
Copy the code

We know what we know. We go back to problem 300. Siko siko


307. Does const make the value immutable?

No, a const variable does not make the value immutable. But it does not allow subsequent assignments (that is, you can use assignment declarations but not later assignments)

const userList = [];
userList.push('juejin'); // It can be mutated even if it cannot be redistributed
console.log(userList); // ['juejin']
Copy the code

We know what we know. We go back to problem 300. Siko siko


308. What are the default parameters?

In E5, we rely on the logical OR operator to handle the default values of function arguments. In ES6, the default function arguments feature allows parameters to be initialized with default values when no value is passed or defined. Let’s compare the behavior to the example,

//ES5
var calculateArea = function(height, width) {
height = height || 50;
width = width || 60;

return width * height;
}
console.log(calculateArea()); //
300
Copy the code

Default parameters make initialization easier,

//ES6
var calculateArea = function(height = 50, width = 60) {
return width * height;
}

console.log(calculateArea()); //
300
Copy the code

We know what we know. We go back to problem 300. Siko siko


309. What are template literals?

Template literals or template strings are string literals that allow expressions to be embedded. They are enclosed by backquote (‘) characters rather than double or single quotes. In E6, this feature allows the use of dynamic expressions such as

var greeting = `Welcome to JS World, Mr. ${firstName} ${lastName}. `
Copy the code

In ES5, you need an interrupt string like this,

var greeting = 'Welcome to JS World, Mr.' + firstName + ' ' + lastName.
Copy the code

== Note == : You can use multi-line strings and string interpolation capabilities with template literals.

We know what we know. We go back to problem 300. Siko siko


310. How to write a multi-line string in template text?

In ES5, you must use a newline character (‘\n’) and a linker (+) to get a multi-line string.

 console.log('This is string sentence 1\n' +
 'This is string sentence 2');
Copy the code

In ES6, you don’t need to mention any newline sequence characters,

 console.log(`This is string sentence 'This is string sentence 2`);
Copy the code

We know what we know. We go back to problem 300. Siko siko


311. What is a nested template?

Nested templates are a feature supported in the template literal syntax that allows the use of internal backquotes within the placeholder ${} within the template. For example, the nested template below is used to display ICONS according to user permissions, while the external template checks for platform type,

 const iconStyles = `icon ${ isMobilePlatform() ? ' ' :
  `icon-${user.isAuthorized ? 'submit' : 'disabled'}` }`;
Copy the code

You can also write the above use case without the nested template capability. However, the nested template feature is more compact and readable.

 // No nested templates
  const iconStyles = `icon ${ isMobilePlatform() ? ' ' :
   (user.isAuthorized ? 'icon-submit' : 'icon-disabled'}`;
Copy the code

We know what we know. We go back to problem 300. Siko siko


312. What is a marked template?

A tag template is an advanced form of a template, where tags allow you to parse template text using functions. The tag function takes the first argument as an array of strings and the rest as expressions. This function can also return an manipulated string based on the argument. Let’s look at the use of this markup template behavior for the IT professional skill set in an organization,

 var user1 = 'Haiyong';
 var skill1 = 'JavaScript';
 var experience1 = 15;

 var user2 = 'juejin';
 var skill2 = 'JavaScript';
 var experience2 = 5;

 function myInfoTag(strings, userExp, experienceExp, skillExp) {
   var str0 = strings[0]; // "Mr/Ms. "
   var str1 = strings[1]; // " is a/an "
   var str2 = strings[2]; // "in"

   var expertiseStr;
   if (experienceExp > 10){
     expertiseStr = 'expert developer';
   } else if(skillExp > 5 && skillExp <= 10) {
     expertiseStr = 'senior developer';
   } else {
     expertiseStr = 'junior developer';
   }

   return ${str0}${userExp}${str1}${expertiseStr}${str2}${skillExp};
 }

 var output1 = myInfoTag`Mr/Ms. ${ user1 } is a/an ${ experience1 } in ${skill1}`;
 var output2 = myInfoTag`Mr/Ms. ${ user2 } is a/an ${ experience2 } in ${skill2}`;

 console.log(output1);// Mr/Ms. Haiyong is a/an expert developer in JavaScript
 console.log(output2);// Mr/Ms. Juejin is a/an junior developer in JavaScript
Copy the code

We know what we know. We go back to problem 300. Siko siko


313. What is a raw string?

ES6 provides a raw String feature that uses the string.raw () method to get the raw String form of a template String. This feature allows you to access raw strings as you enter them without having to deal with escape sequences. For example,

  var calculationString = String.raw `The sum of numbers is \nThe ${1+2+3+4}! `;
  console.log(calculationString); // The sum of numbers is 10
Copy the code

If you do not use raw strings, the sequence of newlines is processed by displaying the output in multiple lines

  var calculationString = `The sum of numbers is \nThe ${1+2+3+4}! `;
  console.log(calculationString);
  // The sum of numbers is
  / / 10
Copy the code

In addition, the original attribute can be used to mark the first argument of a function

  function tag(strings) {
     console.log(strings.raw[0]);
  }
Copy the code

We know what we know. We go back to problem 300. Siko siko


314. What is deconstructive assignment?

A destruct assignment is a JavaScript expression that unpacks the values in an array or the properties in an object into different variables. Let’s get the month values from the array using deconstructive assignment

 var [one, two, three] = ['JAN'.'FEB'.'MARCH'];

 console.log(one); // "JAN"
 console.log(two); // "FEB"
 console.log(three); // "MARCH"
Copy the code

And you can use destruct assignment to get the user properties of an object,

 var {name, age} = {name: 'Haiyong'.age: 22};

 console.log(name); // Haiyong
 console.log(age); / / 22
Copy the code

We know what we know. We go back to problem 300. Siko siko


315. What is the default value in the destruct assignment?

A default value can be assigned to a variable if the value extracted from an array or object during destruction-assignment is undefined. It helps to avoid setting a separate default value for each assignment. Let’s take the array and object use case,

Array deconstruction:

var x, y, z;

[x=2, y=4, z=6] = [10];
console.log(x); / / 10
console.log(y); / / 4
console.log(z); / / 6
Copy the code

Object deconstruction:

var {x=2, y=4, z=6} = {x: 10};

console.log(x); / / 10
console.log(y); / / 4
console.log(z); / / 6
Copy the code

We know what we know. We go back to problem 300. Siko siko


316. How do you swap variables in a deconstructed assignment?

If you do not use destruct assignment, swapping two values requires a temporary variable. With deconstruction, you can exchange the values of two variables in a deconstructed expression. Let’s swap two numeric variables in the array destruct assignment,

var x = 10, y = 20;

[x, y] = [y, x];
console.log(x); / / 20
console.log(y); / / 10
Copy the code

We know what we know. We go back to problem 300. Siko siko


317. What are enhanced object literals?

Object literals make it easy to quickly create objects with attributes in curly braces. For example, it provides shorter syntax for public object property definitions, as shown below.

//ES6
var x = 10, y = 20
obj = { x, y }
console.log(obj); // {x: 10, y:20}
//ES5
var x = 10, y = 20
obj = { x : x, y : y}
console.log(obj); // {x: 10, y:20}
Copy the code

318. What is dynamic import?

Dynamic imports using the import() function syntax allow us to load modules on demand using Promise or async/await syntax. This feature is currently in the Stage4 proposal. The main benefits of dynamic imports are the reduced size of our bundle, the size/payload response of our request, and the overall improvement in the user experience.

The syntax for dynamic import is as follows.

import('./Module').then(Module= > Module.method());
Copy the code

We know what we know. We go back to problem 300. Siko siko


319. What is the use case for dynamic import?

Here are some use cases for using dynamic imports instead of static imports,

Import modules on demand or conditionally. For example, if you want to load a Polyfill on an older browser

 if (isLegacyBrowser()) {
     import(...). Then (...); }Copy the code

Compute the module specifier at run time. For example, you can use it for internationalization.

 import(`messages_${getLocale()}.js`). Then (...);Copy the code

Import modules from regular scripts instead of modules.

We know what we know. We go back to problem 300. Siko siko


320. What is typed arrays?

Typed arrays are array-like objects from the ECMAScript 6 API for handling binary data. JavaScript provides 8 Typed array types.

3. Uint8Array: an array of 8-bit unsigned integers 3. Uint8Array: an array of 8-bit unsigned integers 3. Uint32Array: an array of 32-bit unsigned integers 7.Float32Array: a group of 32-bit floating points 8.Float64Array: a group of 64-bit floating points 6

For example, you can create an array of 8-bit signed integers, as shown below

 const a = new Int8Array(a);// You can pre-allocate n bytes
 const bytes = 1024
 const a = new Int8Array(bytes)
Copy the code

We know what we know. We go back to problem 300. Siko siko


321. What are the advantages of module loaders?

The module loader provides the following functions,

1. Dynamic loading 2. State isolation 3. Global namespace isolation 4. Nested virtualization

We know what we know. We go back to problem 300. Siko siko


322. What is collation?

Collation rules are used to sort a set of strings and search within a set of strings. It is parameterized by locale and knows Unicode. Let’s look at the compare and sort function,

Comparison:

 var list = [ "ä"."a"."z" ]; // In German, "a" is ordered together with "a", while in Swedish, "a" is ordered after "z"
 var l10nDE = new Intl.Collator("de");
 var l10nSV = new Intl.Collator("sv");
 console.log(l10nDE.compare("ä"."z") = = = -1); // true
 console.log(l10nSV.compare("ä"."z") = = = +1); // true
Copy the code

Sorting:

 var list = [ "ä"."a"."z" ]; // In German, "a" is ordered together with "a", while in Swedish, "a" is ordered after "z"
 var l10nDE = new Intl.Collator("de");
 var l10nSV = new Intl.Collator("sv");
 console.log(list.sort(l10nDE.compare)) // ["a", "a", "z"]
 console.log(list.sort(l10nSV.compare)) // ["a", "z", "a"]
Copy the code

We know what we know. We go back to problem 300. Siko siko


323. What is… Of the statement?

for… The of statement creates a loop that iterates iterables or elements, such as built-in strings, arrays, array-like objects (such as arguments or nodelists), TypedArray, Map, Set, and user-defined iterables. Array on the for… The basic use of the “of” statement is as follows,

 let arrayIterable = [10.20.30.40.50];

 for (let value of arrayIterable) {
   value ++;
   console.log(value); // 11 21 31 41 51
 }
Copy the code

We know what we know. We go back to problem 300. Siko siko


324. What is the output of the following expansion operator array?

 [...'John Resig']
Copy the code

Array output for [‘ J ‘, ‘o’, ‘h’, ‘n’, ‘, ‘R’, ‘e’, ‘s’, ‘I’, ‘g’]

Note: Strings are an iterable type, and the extension operators in arrays map each iterable character to an element. Thus, each character in the string becomes an element in the array.

We know what we know. We go back to problem 300. Siko siko


325. Is PostMessage safe?

Yes, postMessages can be considered very safe as long as the programmer/developer carefully checks the source and source of the incoming message. However, if you try to send/receive messages without verifying the source of the message, a cross-site scripting attack can occur.

We know what we know. We go back to problem 300. Siko siko


326. What’s the problem with a PostMessage target source being a wildcard?

The second argument to the postMessage method specifies which source is allowed to receive the message. If you use the wildcard “*” as an argument, any source is allowed to receive the message. In this case, the sender window has no way of knowing whether the target window is at the target source when it sends the message. If the target window has navigated to another origin, the other origin will receive the data. Therefore, this can lead to XSS vulnerabilities.

 targetWindow.postMessage(message, The '*');
Copy the code

We know what we know. We go back to problem 300. Siko siko


327. How do you avoid receiving postMessages from attackers?

Since a listener listens for any message, an attacker can trick an application by sending messages from the attacker’s source, giving the impression that the receiver received the message from the actual sender’s window. You can avoid this problem by using the “message.origin” property to verify the source of the message on the receiver side. For example, let’s check the source of the sender http://www.some-sender.com on the receiver www.some-receiver.com,

 // The listener opens http://www.some-receiver.com/
 window.addEventListener("message".function(message){
     if(/^http://www\.some-sender\.com$/.test(message.origin)){
          console.log('You received the data from valid sender', message.data); }});Copy the code

We know what we know. We go back to problem 300. Siko siko


328. Can I avoid using postMessages entirely?

You cannot completely (or 100%) avoid using postMessages. Although your application does not use postMessage because of the risk, many third-party scripts use postMessage to communicate with third-party services. As a result, your application may be using postMessage without your knowledge.

We know what we know. We go back to problem 300. Siko siko


329. Are postMessages synchronized?

PostMessages are synchronous in IE8, but they are asynchronous in IE9 and all other modern browsers (IE9+, Firefox, Chrome, Safari). Because of this asynchronous behavior, we use a callback mechanism when postMessage returns.

We know what we know. We go back to problem 300. Siko siko


330. What is the Javascript paradigm?

JavaScript is a multi-paradigm language that supports imperative/procedural programming, object-oriented programming, and functional programming. JavaScript supports object-oriented programming with prototype inheritance.

We know what we know. We go back to problem 300. Siko siko


331. What’s the difference between internal and external javascript?

Internal JavaScript: This is the source code inside the script tag. External JavaScript: Source code is stored in an external file (with the.js extension) and referenced in tags.

We know what we know. We go back to problem 300. Siko siko


332. Is JavaScript faster than server-side scripting?

Yes, JavaScript is faster than server-side scripting. Because JavaScript is a client-side script, it does not require any help from a Web server to perform calculations or calculations. So JavaScript is always faster than any server-side script (ASP, PHP, etc.).

We know what we know. We go back to problem 300. Siko siko


333. How do you get the status of a check box?

You can check to apply this property to the check box selected in the DOM. If the value is True, the check box is selected; otherwise, it is not selected. For example, the following HTML checkbox element can be accessed using javascript, as shown below,

   <input type="checkbox" name="checkboxname" value="Agree">Agreed to conditions<br>
Copy the code
 console.log(documentDocument.getelementbyid (' checkboxname). Checked);// true or false
Copy the code

We know what we know. We go back to problem 300. Siko siko


334. What is the purpose of the double tilde operator?

The double tilde operator (~~) is called the double non-bitwise operator. This operator will be a faster alternative to math.floor ().

We know what we know. We go back to problem 300. Siko siko


335. How do you convert characters to ASCII?

You can use this String. The prototype. CharCodeAt () method will be converted to ASCII String characters. For example, let’s find the ASCII code for the first letter of the string ‘ABC’,

 "ABC".charCodeAt(0) // returns 65
Copy the code

The string.fromCharcode () method converts numbers to equal ASCII characters.

 String.fromCharCode(65.66.67); // returns 'ABC'
Copy the code

We know what we know. We go back to problem 300. Siko siko


336. What is an array buffer?

An ArrayBuffer object is used to represent a generic, fixed-length buffer of raw binary data. You can create it as follows,

 let buffer = new ArrayBuffer(16); // Create a buffer of length 16
 alert(buffer.byteLength); / / 16
Copy the code

To manipulate the ArrayBuffer, we need to use the “view” object.

 // Create a DataView that references the buffer
  let view = new DataView(buffer);
Copy the code

We know what we know. We go back to problem 300. Siko siko


337. What is the output of the following string expression?

 console.log("Welcome to JS world"[0])
Copy the code

The output of the above expression is “W”.

Description: The parenthesis notation on a string with a specific index returns the character at a specific position. Therefore, it returns the character “W” of the string. Since this feature is not supported in IE7 and below, you may need to use the.charat () method to get the desired results.

We know what we know. We go back to problem 300. Siko siko


338. What is the purpose of the Error object?

The Error constructor creates an Error object and throws an instance of the Error object when a runtime Error occurs. The Error object can also be used as the base object for user-defined exceptions. The syntax for the error object is as follows,

 new Error([message[, fileName[, lineNumber]]])
Copy the code

You can use the try… An Error object is used in a catch block to throw a user-defined exception or Error, as shown below.

 try {
   if(withdraw > balance)
   throw new Error("Oops! You don't have enough balance");
 } catch (e) {
   console.log(e.name + ':' + e.message);
 }
Copy the code

We know what we know. We go back to problem 300. Siko siko


What is the purpose of the EvalError object?

The EvalError object indicates an error about the global eval() function. Although JavaScript no longer throws this exception, the EvalError object remains compatible. The syntax for this expression is as follows,

 new EvalError([message[, fileName[, lineNumber]]])
Copy the code

You can try… An EvalError is thrown in a catch block, as shown below,

 try {
   throw new EvalError('Eval function error'.'someFile.js'.100);
 } catch (e) {
   console.log(e.message, e.name, e.fileName);              // "Eval function error", "EvalError", "someFile.js"
Copy the code

We know what we know. We go back to problem 300. Siko siko


340. What is the list of case errors thrown from non-strict mode to strict mode?

When you apply Strict; Syntax, the following cases will raise a SyntaxError before executing the script

When using octal syntax

 var n = 022;
Copy the code

1. Using the with statement 2. Using the delete operator on the variable name 3. Use eval or arguments for variable or function parameter names 4. When you use newly reserved keywords 5. When you declare a function in a block

 if (someCondition) { function f() {}}Copy the code

Therefore, the errors in the above cases help to avoid errors in the development/production environment.

We know what we know. We go back to problem 300. Siko siko


341. Are all objects prototypes?

It isn’t. All objects have prototypes, except for basic objects created by the user or objects created using the new keyword.

We know what we know. We go back to problem 300. Siko siko


342. What’s the difference between parameter and argument?

Arguments are the names of variables defined by the function, and arguments represent the values assigned to the function when it is called. Let’s explain this with a simple function

 function myFunction(parameter1, parameter2, parameter3) {
   console.log(arguments[0]) // "argument1"
   console.log(arguments[1]) // "argument2"
   console.log(arguments[2]) // "argument3"
 }
 myFunction("argument1"."argument2"."argument3")
Copy the code

We know what we know. We go back to problem 300. Siko siko


343. What is the purpose of the some method in arrays?

The some() method tests whether at least one element in the array passes the test implemented by the provided function. This method returns a Boolean value. Let’s take an example to test any odd number element,

 var array = [1.2.3.4.5.6 ,7.8.9.10];
 var odd = element ==> element % 2! = =0;
 console.log(array.some(odd)); // true (odd elements exist)
Copy the code

We know what we know. We go back to problem 300. Siko siko


344. How do you combine two or more arrays?

The concat() method is used to concatenate two or more arrays by returning a new array containing all the elements. The syntax is as follows,

array1.concat(array2, array3, ... , arrayX)Copy the code

Let’s take an array in series with an array of vegetables and fruits,

  var veggies = ["Tomato"."Carrot"."Cabbage"];
  var fruits = ["Apple"."Orange"."Pears"];
  var veggiesAndFruits = veggies.concat(fruits);
  console.log(veggiesAndFruits); // Tomato, Carrot, Cabbage, Apple, Orange, Pears
Copy the code

We know what we know. We go back to problem 300. Siko siko


345. What’s the difference between a shallow copy and a deep copy?

There are two ways to copy objects,

Shallow copy: A shallow copy is a bitwise copy of an object. Creates a new object that has an exact copy of the value in the original object. If any field of the object is a reference to another object, only the reference address is copied, that is, only the memory address is copied.

example

 var empDetails = {
   name: "John".age: 25.expertise: "Software Developer"
 }
Copy the code

Create a copy of the

 var empDetailsShallowCopy = empDetails    //Shallow copying!
Copy the code

If we change some property values in duplicates like this:

 empDetailsShallowCopy.name = "Johnson"
Copy the code

The above statement will also change the name empDetails because we have a shallow copy. That means we lose the original data, too.

Deep copy: A deep copy copies all fields and the dynamically allocated memory to which they point. Deep copying occurs when an object is copied along with the objects it references.

example

 var empDetails = {
   name: "John".age: 25.expertise: "Software Developer"
 }
Copy the code

Create a deep copy of the properties of the original object into the new variable

 var empDetailsDeepCopy = {
   name: empDetails.name,
   age: empDetails.age,
   expertise: empDetails.expertise
 }
Copy the code

Now, if you change empDetailsdeepCopy.name, it will only affect empDetailsDeepCopy and not empDetails

We know what we know. We go back to problem 300. Siko siko


346. How do you create a specific number of copies of a string?

The repeat() method is used to construct and return a new string that contains a specified number of copies of the string that called it, concatenated together. Remember that this method was added to the ECMAScript 2015 specification.

Let’s take the Hello string and repeat it four times,

'Hello'.repeat(4);  // 'HelloHelloHelloHello'
Copy the code

We know what we know. We go back to problem 300. Siko siko


347. How do you return all matched strings based on a regular expression?

The matchAll() method can be used as an iterator that returns all the results of a string that matches a regular expression. For example, the following example returns an array of matching string results based on a regular expression,

let regexp = /Hello(\d?) )/g;
let greeting = 'Hello1Hello2Hello3';

let greetingList = [...greeting.matchAll(regexp)];

console.log(greetingList[0]); //Hello1
console.log(greetingList[1]); //Hello2
console.log(greetingList[2]); //Hello3
Copy the code

We know what we know. We go back to problem 300. Siko siko


348. How do you trim a string at the beginning or end?

The trim string prototype method is used to trim the sides of a string. But if you want to trim, especially at the beginning or end of a string, then you can use the trimStart/trimLeft and trimEnd/trimRight methods. Let’s look at an example of these methods in a greeting message,

var greeting = ' Hello, Goodmorning! ';

console.log(greeting); // " Hello, Goodmorning! "
console.log(greeting.trimStart()); // "Hello, Goodmorning! "
console.log(greeting.trimLeft()); // "Hello, Goodmorning! "

console.log(greeting.trimEnd()); // " Hello, Goodmorning!"
console.log(greeting.trimRight()); // " Hello, Goodmorning!"
Copy the code

We know what we know. We go back to problem 300. Siko siko


349. What is the output of the following console statement with a unary operator?

Let’s execute the console statement using the unary operator, as shown below,

console.log(+ 'Hello');
Copy the code

The output from the above console log statement returns NaN. Because the element is prefixed with a unary operator, the JavaScript interpreter tries to convert the element to a numeric type. The value of the statement results in a NaN value because the conversion failed.

We know what we know. We go back to problem 300. Siko siko


350. Does javascript use mixins?

Yes, mixins can be seen in javascript as a way to “borrow” functionality from other objects. Each newly defined object has a Prototype property from which other objects can “borrow” functionality. The function here can be a property or a method.

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


351. What is the thunk function?

Thunk is simply a function of delaying the evaluation value. It does not take any arguments, but instead gives values when you call Thunk. That is, it is used for not executing now, but executing sometime in the future. Let’s take an example of synchronization,

const add = (x,y) = > x + y;
const thunk = () = > add(2.3);
thunk() / / 5
Copy the code

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


352. What is asynchronous Thunk?

Asynchronous Thunk can be used to make network requests. Let’s look at an example of a network request,

function fetchData(fn){
  fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response= > response.json())
  .then(json= > fn(json))
}

const asyncThunk = function (){
   return fetchData(function getData(data){
      console.log(data)
  })
}

asyncThunk()
Copy the code

The getData function is not called immediately, but only when data is available from the API endpoint. The setTimeout function is also used to make our code asynchronous. The best real-time example is the Redux state Management library, which uses asynchronous Thunk to delay operations to be scheduled.

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


353. What is the output of the following function call?

Code snippet:

const circle = {
  radius: 20.diameter() {
    return this.radius * 2;
  },
  perimeter: () = > 2 * Math.PI * this.radius
};


console.log(circle.diameter());
console.log(circle.perimeter());
Copy the code

Output:

The output is 40 and NaN. Remember that the diameter is a regular function, and the value of the perimeter is an arrow function. This regular function’s keyword (diameter) refers to the surrounding scope, which is a class (Shape object). Perimeter the keyword for perimeter functions is perimeter, which is a window object. Since the window object does not have a radius property, it returns an undefined value, and multiples of numeric values return NaN values.

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


354. How do I remove all newlines from a string?

The simplest approach is to use regular expressions to detect and replace newlines in a string. In this case, we use the replacement function and the string to be replaced, which in our case is an empty string.

function remove_linebreaks( var message ) {
    return message.replace( /[\r\n]+/gm."" );
}
Copy the code

In the above expression, g and m are used for global and multi-line flags.

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


355. What’s the difference between backflow and redraw?

A redraw changes occur when they affect the visibility of the component, not its layout. Examples of this include outline, visibility, or background color. A reflux involves a change in the layout that affects a portion of a page (or entire page). Resizing a browser window, changing fonts, changing content (such as user-typed text), using JavaScript methods that involve calculating styles, adding or removing elements from the DOM, and changing the classes of elements are some of the things that can trigger reflux. The backflow of an element results in subsequent backflow of all child and ancestor elements and any elements that follow it in the DOM.

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


356. What happens when you negate an array?

Use! Character negation of an array enforces the array to be a Boolean. Since the array is considered real, negating it will return false.

console.log(! []);// false
Copy the code

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


357. What happens if we add two arrays?

If you add two arrays, it converts them both to strings and concatenates them. For example, the result of adding an array is

console.log(['a'] + ['b']);  // "ab"
console.log([] + []); / / ""
console.log(! [] + []);// "false", because ! [] returns false.
Copy the code

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


358. What is the output of adding the addition operator to a false value?

If the addition (+) operator is added to a false value (NULL, undefined, NaN, false, “”), the false value is converted to the numeric value zero. Let’s display them on the browser console, as shown below,

console.log(+null); / / 0
console.log(+undefined);// NaN
console.log(+false); / / 0
console.log(+NaN); // NaN
console.log(+""); / / 0
Copy the code

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


359. How to use special characters to create from a string?

The self string can be created by! + Is a combination of characters. You need to remember the following conventions to implement this pattern.

Since the array is a true value, negating the array will produce an error:! [] === false Adding arrays together strings them up according to JavaScript enforcement rules: [] + [] === “” Prefixed with the + operator converts the array to false, negation makes it true, and the final conversion results in the value ‘1’ : +(! (+[])) === 1 By applying the above rule, we can get the following conditions

! [] + [] = = ="false"+! = = = + []1
Copy the code

Now the character pattern will be created as follows,

s e l f ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ (! [[] + [])3] + (! [[] + [])4] + (! [[] + [])2] + (! [[] + [])0] ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ (! []+ [])[+!+[]+!+[]+!+[] +! []+ [])[+!+[]+!+[]+!+[]+!+[] +! []+ [])[+!+[]+!+[]] + (! [] [])[+[]] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (! [] + []) [+ + [] +! + [] +! + []] + (! [] + []) [+ + [] +! + [] +! + [] +! + []] + (! [] + []) [+ + [] +! + []] + (! [] + + [] [] [])Copy the code

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


360. How to remove false values from an array?

You can apply a filter method to an array by passing a Boolean value as a parameter. In this way, it removes all false values (0, undefined, null, false, and “”) from the array.

const myArray = [false.null.1.5.undefined]
myArray.filter(Boolean); // [1, 5] myArray. Filter (x => x);
Copy the code

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


361. How do you get the unique value of an array?

You can use Set and rest expression/spread(…) To get the unique value of an array.

console.log([...new Set([1.2.4.4.3]]);// [1, 2, 4, 3]
Copy the code

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


362. What is a deconstructive alias?

Sometimes you want the name of the destruct variable to be different from the name of the property. In this case, you will use a: newName to specify the name of the variable. This process is called deconstructing aliases.

const obj = { x: 1 };
// Fetch obj. X as {otherName}
const { x: otherName } = obj;
Copy the code

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


363. How to map array values without using the map method?

Map maps array values without using methods using only fromArray’s methods. Let’s map the city names from the country array,

const countries = [
   { name: 'China'.capital: 'Beijing' },
   { name: 'India'.capital: 'Delhi' },
   { name: 'US'.capital: 'Washington' },
   { name: 'Russia'.capital: 'Moscow' },
   { name: 'Singapore'.capital: 'Singapore' },
   { name: 'France'.capital: 'Paris'},];const cityNames = Array.from(countries, ({ capital}) = > capital);
console.log(cityNames); // ['Beijing', 'Washington', 'Moscow', 'Singapore', 'Delhi', 'Paris']
Copy the code

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


364. How do you empty an array?

You can quickly empty an array by setting its length to zero.

let cities = ['Singapore'.'Delhi'.'London'];
cities.length = 0; // cities becomes []
Copy the code

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


365. How do you round a number to some decimal number?

You can use methods in toFixed native javascript to round numbers to a certain number.

let pie = 3.141592653;
pie = pie.toFixed(3); / / 3.142
Copy the code

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


366. What’s the easiest way to convert an array into an object?

You can use Spread (…) Operator converts an array to an object with the same data.

var fruits = ["banana"."apple"."orange"."watermelon"];
varfruitsObject = {... fruits};console.log(fruitsObject); // {0: "banana", 1: "apple", 2: "orange", 3: "wate
Copy the code

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


367. How do you create an array with some data?

You can use the fill method to create an array with some data or an array with the same value.

var newArray = new Array(5).fill("0");
console.log(newArray); // ["0", "0", "0", "0"]
Copy the code

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


368. What is the placeholder for the console object?

Here is a list of placeholders available for console objects,

%o – it needs an object, %s – it needs a string, %d – placeholders for decimal or integer can be represented in console.log as follows

const user = { "name":"Haiyong"."id": 1."city": "Beijing"};
console.log("Hello %s, your details %o are available in the object form"."John", user); // Hello Haiyong, your details {name: "Haiyong", id: 1, city: "Beijing"} are available in object
Copy the code

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


369. Is it possible to add CSS to console messages?

Yes, you can apply CSS styles to console messages that are similar to HTML text on a Web page.

console.log('%c text with blue, large font and red background '.'color: blue; font-size: x-large; background: red');
Copy the code

The text will display as follows,

Note: All CSS styles can be applied to console messages.

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


370. What is the purpose of the dir method on console objects?

Console.dir () is used to display an interactive list of the attributes of the specified JavaScript object as JSON.

const user = { "name":"Haiyong"."id": 1."city": "Beijing"};
console.dir(user);
Copy the code

A user object displayed as a JSON representation

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


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