This is the 29th day of my participation in Gwen 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)

In order to make it easy to read, I have put links back to the top or to the corresponding questions where necessary

Serial number The problem
1 What are the possible ways to create objects in JavaScript?
2 What is a prototype chain?
3 What’s 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 an Object and a Map
9 What is the difference between the == and === operators?
10 What is a lambda or 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 Currie function?
16 What is a pure function?
17 What is the let keyword used for?
18 What is the difference between let and var?
19 Why choose the name let as the keyword?
20 How do you redeclare variables in switch blocks without errors?
21 What is a temporary dead zone?
22 What is IIFE (immediately executed function expression)?
23 What are the benefits of using modules?
24 What is memoization?
25 What is the power of variable promotion?
26 What are classes in ES6?
27 What is closures?
28 What is a module?
29 Why do you need modules?
30 What is the scope in javascript?
31 What is a Service Worker?
32 How do I manipulate the DOM using a Service Worker?
33 How do you reuse information when a 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 I need cookies?
39 What are the options in the cookie?
40 How do you delete cookies?
41 What is 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 are the methods 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 the limitations of Web workers on DOM?
51 What is promise?
52 Why do we need Promise?
53 What are the three states of promise?
54 What is a callback function?
55 Why do we need a correction?
56 What is callback hell?
57 What is a server sending event?
58 How do you receive event notifications from the server?
59 How do you check browser support for sending events to the server?
60 What are the available events for events sent by the server?
61 What are the main rules of promise?
62 What is the callback of a callback?
63 What is promise chaining?
64 What is promise.all?
65 What is the purpose of the race method in a promise?
66 What are strict patterns in javascript?
67 Why do you need strict patterns?
68 How do you declare strict patterns?
69 What is the purpose of the double exclamation mark?
70 What is the purpose of deleting an 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 detect if the caps lock key is on?
79 What is isNaN?
80 What is 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 attribute?
84 What is the purpose of isFinite?
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 a Document Load and a DOMContentLoaded event?
91 What is the difference between Native, Host and User objects?
92 What tools or techniques are available for debugging JavaScript code?
93 What are the advantages and disadvantages of Promises versus corrections?
94 What’s the difference between attribute and property?
95 What is the 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 B: What’s the preventDefault method for?
103 What is the use of the stopPropagation method?
104 What steps does return False involve?
105 What is BOM(Browser Object Model)?
106 What does setTimeout do?
107 What does setInterval do?
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 stringing?
114 How do you parse JSON strings?
115 Why do YOU need JSON?
116 What is 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 get the current URL using javascript?
123 What are the various URL properties of the Location object?
124 How do I get query string values in javascript?
125 How do I check if there are keys in an object?
126 How do you loop 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 the for loop?
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 trim strings in javascript?
135 How do you add a key-value pair to javascript?
136 ‘! Does the ‘symbol represent a special operator?
137 How do you assign default values to variables?
138 How do you define multi-line strings?
139 What is app Shell Model?
140 Can we define properties for functions?
141 What is the way to find the desired number of arguments for a function?
142 What is polyfill?
143 What are break and continue statements?
144 What are JS tags?
145 What are the benefits of putting statements 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 range?
151 What is tree shaking?
152 What does it take to 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 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 strings?
160 What is the purpose of the EXEC method?
161 How do I change the style of an HTML element?
162 What is the result of 1+2+’3′?
163 What are debugger statements?
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 do I detect mobile browsers without regular expressions?
168 How do you get the width and height of an image using JS?
169 How do I synchronize HTTP requests?
170 How do I make an asynchronous HTTP request?
171 How do you convert dates to another time zone in javascript?
172 What are the attributes used to get the window size?
173 What are conditional operators in javascript?
174 Can you apply chaining to conditional operators?
175 What are the ways to execute javascript after a 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 freeze?
181 How do you detect browser language preferences?
182 How do I use javascript to convert a string to title case?
183 How do you detect disabled javascript on 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 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 if two values are the same or do not use objects?
191 What is the purpose of the IS method using Object?
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 is the difference between the Freeze and SEAL methods?
198 How do I determine whether an object is SEAL?
199 How do I get enumerable key-value pairs?
200 What are the main differences between the object. values and object. entries methods?
201 How do I get the list of keys for any object?
202 How do you create an object with Prototype?
203 What is WeakSet?
204 What is the difference between WeakSet and Set?
205 List the set of methods available on WeakSet?
206 What is WeakMap?
207 What is the difference between a WeakMap and a Map?
208 List the set of methods available on WeakMap?
209 What is the purpose of Uneval?
210 How do you encode a URL?
211 How do you 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 an anonymous function?
215 What is the priority of 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 the defineProperty method?
221 What is the purpose of switch-case?
222 What conventions do YOU follow when using Swtich Case?
223 What is a primitive data type?
224 What are the different ways to access object properties?
225 What are function argument 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 the 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 of an array?
243 What is the purpose of compareFunction when sorting arrays?
244 How do you invert an array?
245 How do you find minimum and maximum values in an array?
246 How do I find min and Max values without math functions?
247 What is a null statement and its purpose?
248 How do I get metadata for a module?
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’s typescript’s advantage over javascript?
254 What is an object initializer?
255 What is a constructor?
256 What happens if you write a constructor more than once in a class?
257 How do I call the constructor of a parent class?
258 How do you get a prototype of an object?
259 What happens if I pass a string type for the getPrototype method?
260 How do I set the stereotype of one object to another?
261 How do you check if an object is extensible?
262 How do I prevent objects from expanding?
263 What are the different ways to make an object unextensible?
264 How can I define multiple attributes on an object?
265 What is MEAN in JavaScript?
266 What is obfuscation in javascript?
267 Why 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 constraints available to validate DOM attributes?
276 What is a validity attribute list?
277 For example using the rangeOverflow property?
278 Is enumeration provided in javascript?
279 What is enumeration?
280 How do you list all the attributes of an object?
281 How do I get the property descriptor of an object?
282 What properties do property descriptors provide?
283 How do you extend classes?
284 How can 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 using commas as thousands separators?
289 What’s the difference between Java and javascript?
290 Does javascript support namespaces?
291 How do you declare namespaces?
292 How do I call javascript code in iframe from the parent page?
293 How do I get a time zone offset from a date?
294 How to load CSS and JS files dynamically?
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 wait?
301 How do you create an infinite loop?
302 Why should we avoid the with statement?
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 a const variable make the value immutable?
308 What are the default parameters?
309 What are template literals?
310 How do I write multiline strings in template text?
311 What is a nested template?
312 What is a tag template?
313 What is a primitive string?
314 What is deconstruction assignment?
315 What is the default value in destructuring assignment?
316 How do you swap variables in a deconstruction assignment?
317 What are enhanced object literals?
318 What is dynamic import?
319 What are dynamically imported use cases?
320 What is typed arrays?
321 What are the advantages of a module loader?
322 What is collation?
323 What is a… Of the statement?
324 What is the output of the following expanded array of operators?
325 Is PostMessage secure?
326 What’s wrong with postMessage target sources being wildcards?
327 How do you avoid receiving postMessages from attackers?
328 Can I avoid Using postMessages entirely?
329 Is postMessages synchronized?
330 What is the paradigm of Javascript?
331 What is the difference between internal and external javascript?
332 Is JavaScript faster than server-side scripting?
333 How do you get the status of check boxes?
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 to strict modes?
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 is the difference between shallow copy and 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 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 reflow 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 strings?
360 How do I remove spurious values from an array?
361 How do you get the unique value of an array?
362 What is a deconstruction 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 numbers to certain decimals?
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 Can I add CSS to console messages?
370 What is the purpose of the dir method on a console object?
371 Can I debug HTML elements in the console?
372 How do I display data in tabular format using console objects?
373 How do you verify that the parameter is a number?
374 How do you create a copy to Clipboard button?
375 What is the shortcut to get the timestamp?
376 How do you flatten a multidimensional array?
377 What is the simplest multi-condition check?
378 How do you capture the browser back button?
379 How do I disable the right click in 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 extract request?
384 What is voip API?
385 What is the minimum timeout limit?
386 How do you achieve zero timeouts in modern browsers?
387 What are the tasks in the event loop?
388 What are microtasks?
389 What are the different event cycles?
390 What is the purpose of queueMicrotask?
391 How do you use javascript libraries in typescript files?
392 Promises and observables what is 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 is the difference between Shim and Polyfill?
397 How do you detect primitive or non-primitive 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 is the difference between a function constructor and a function declaration?
403 What is a short circuit?
404 What’s the easiest way to resize an array?
405 What is observable?
406 What is the difference between a function declaration and a class declaration?
407 What is an asynchronous function?
408 How would 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 detect if a function is called as a constructor?
414 What is the difference between arguments objects and REST parameters?
415 What is the difference between an extension operator and a REST parameter?
416 What are the different types of generators?
417 What is a built-in iterable?
418 for… Of and the for… What are the differences between in statements?
419 How do I define instance and non-instance attributes?
420 What is the difference between isNaN and number. isNaN?
421 How do I call IIFE without any extra parentheses?
422 Can expressions be used in switch cases?
423 What’s the easiest way to ignore a promise error?
424 How do I style console output using CSS?

201. How do I get the key list of any object?

You can use the methods object.keys () uses to return an array of the given Object’s own property names, in the same order as we would get with a normal loop. For example, you can get the key of a user object,

 const user = {
   name: 'Haiyong'.gender: 'male'.age: 40
 };

 console.log(Object.keys(user)); //['name', 'gender', 'age']
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


202. How do you create an object with Prototype?

The object.create () method is used to create a new Object with the specified prototype Object and properties. That is, it uses an existing object as a prototype for a newly created object. It returns a new object with the specified prototype object and properties.

  const user = {
    name: 'Haiyong'.printInfo: function () {
      console.log(`My name is The ${this.name}. `); }};const admin = Object.create(user);

  admin.name = "Nick"; // Remember that "name" is a property set on the "admin" object, not the "user" object

  admin.printInfo(); // My name is Nick
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


203. What is WeakSet?

WeakSet is used to store a collection of weakly (weak reference) held objects. Syntax is as follows,

 new WeakSet([iterable]);
Copy the code

Let’s look at the following example to explain its behavior,

 var ws = new WeakSet(a);var user = {};
 ws.add(user);
 ws.has(user);    // true
 ws.delete(user); // Delete the user from the collection
 ws.has(user);    // false, user has been deleted
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


204. What is the difference between a WeakSet and a Set?

The main difference lies in that the object reference in Set is a strong reference, while the object reference in WeakSet is a weak reference. That is, objects in WeakSet can be garbage collected if there are no other references.

The other difference is,

WeakSets can store any value, while WeakSets can only store the Set of objects. 2.WeakSet has no size property different from Set. 3.WeakSet does not have clear, keys, values, entries, forEach and other methods. 4.WeakSet is not iterative.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


205. List the set of methods available on WeakSet?

Below is a list of methods available on WeakSet,

1. Add (value) : append the given value to the new object of the WeakSet. 2. Delete (value) : delete the value from the WeakSet. 3. Has (value) : Return true if the value exists in the WeakSet, otherwise return false. 4. Length () : It returns the length of weakSetObject. Let’s see what all of the above methods do in an example,

 var weakSetObject = new WeakSet(a);var firstObject = {};
 var secondObject = {};
 // add(value)
 weakSetObject.add(firstObject);
 weakSetObject.add(secondObject);
 console.log(weakSetObject.has(firstObject)); //true
 console.log(weakSetObject.length()); / / 2
 weakSetObject.delete(secondObject);
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


206. What is WeakMap?

A WeakMap object is a collection of key/value pairs where the key is weakly referenced. In this case, the key must be an object and the value can be any value. The syntax is as follows,

 new WeakMap([iterable])
Copy the code

Let’s look at the following example to explain its behavior,

  var ws = new WeakMap(a);var user = {};
  ws.set(user);
  ws.has(user);    // true
  ws.delete(user); // Delete the user from the map
  ws.has(user);    // false, user has been deleted
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


207. What is the difference between a WeakMap and a Map?

The main difference is that the reference of key objects in Map is strong reference, while the reference of key objects in WeakMap is weak reference. That is, key objects in a WeakMap can be garbage collected if there are no other references.

The other difference is,

1.Maps can store any type of key, while WeakMaps can only store the set 2 of key objects. Different from Map, WeakMap does not have size property. 3.WeakMap does not have clear, keys, values, entries, forEach and other methods. 4.WeakMap cannot be iterated.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


208. List the set of methods available on WeakMap?

Below is a list of methods available on WeakMap,

1. Set (key, value) : Sets the key value in the WeakMap object. Return the WeakMap object. 2. Delete (key) : Deletes any value associated with the key. 3. Has (key) : Returns a Boolean value to assert whether a value is associated with a key in a WeakMap object. 4. Get (key) : Returns the value associated with the key. If not, undefined is returned. Let’s look at the capabilities of all of the above methods in one example,

 var weakMapObject = new WeakMap(a);var firstObject = {};
 var secondObject = {};
 // set(key, value)
 weakMapObject.set(firstObject, 'Haiyong');
 weakMapObject.set(secondObject, 100);
 console.log(weakMapObject.has(firstObject)); //true
 console.log(weakMapObject.get(firstObject)); // Haiyong
 weakMapObject.delete(secondObject);
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


209. What is the purpose of Uneval?

Uneval () is a built-in function that creates a string representation of an object’s source code. It is a top-level function and is not associated with any object. Let’s take a look at the following example to learn more about what it does,

 var a = 1;
 uneval(a); // Returns a string containing 1
 uneval(function user() {}); // returns "(function user(){})"
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


210. How do you encode a URL?

The encodeURI() function is used to divide (, /? The full URI with special characters is encoded outside the: @ & = + $#) character.

 var uri = 'https://mozilla.org/?x= ш е л л ы';
 var encoded = encodeURI(uri);
 console.log(encoded); // https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


211. How do you decode a URL?

The decodeURI() function is used to decode the uniform resource Identifier (URI) previously created by encodeURI().

  var uri = 'https://mozilla.org/?x= ш е л л ы';
  var encoded = encodeURI(uri);
  console.log(encoded); // https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B
 try {
   console.log(decodeURI(encoded)); / / https://mozilla.org/?x= "ш е л л ы"
 } catch(e) { // Catch ill-formed URIs
   console.error(e);
 }
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


212. How do you print the content of a web page?

The window object provides a print() method that prints the contents of the current window. It opens a print dialog box that lets you choose between various print options. Let’s look at the use of the print method in an example.

<input type="button" value="Print" onclick="window.print()" />
Copy the code

Note: In most browsers, it will be blocked when the print dialog opens.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


213. What is the difference between uneval and eval?

The uneval function returns the source of the given object; The eval function, on the other hand, evaluates source code in different areas of memory. Let’s look at an example to clarify the difference,

 var msg = uneval(function greeting() { return 'Hello, Good morning'; });
 var greeting = eval(msg);
 greeting(); // returns "Hello, Good morning"
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


214. What is an anonymous function?

An anonymous function is a function without a name! Anonymous functions are usually assigned to variable names or used as callback functions. Syntax is as follows,

 function (optionalParameters) {
   //do something
 }

 const myFunction = function(){ // An anonymous function assigned to a variable
   //do something
 };

 [1.2.3].map(function(element){ // The anonymous function is used as a callback function
   //do something
 });
Copy the code

Let’s look at the anonymous function above in an example,

 var x = function (a, b) {return a * b};
 var z = x(5.10);
 console.log(z); / / 50
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


215. What is the priority of local and global variables?

Local variables take precedence over global variables of the same name. Let’s look at this behavior in an example.

 var msg = "Good morning";
 function greeting() {
    msg = "Good Evening";
    console.log(msg);
 }
 greeting();
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


216. What are javascript accessors?

ECMAScript 5 introduces javascript object accessors, or computed properties, through getters and setters. Getters use the get keyword, and Setters use the set keyword.

 var user = {
   firstName: "Hai".lastName : "Yong".language : "cn".get lang() {
     return this.language;
   }
   set lang(lang) {
   this.language = lang; }};console.log(user.lang); // Getter access lang as cn
 user.lang = 'en';
 console.log(user.lang); // setter 用于将 lang 设置为 en
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


217. How do you define attributes on object constructors?

The object.defineProperty () static method is used to define new properties directly on an Object, or to modify existing properties on an Object, and return the Object. Let’s look at an example to see how attributes are defined,

 const newObject = {};

 Object.defineProperty(newObject, 'newProperty', {
   value: 100.writable: false
 });

 console.log(newObject.newProperty); / / 100

 newObject.newProperty = 200; // It throws an error in strict mode due to writable Settings
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


218. What’s the difference between Get and defineProperty?

Unless you use classes, both have similar results. If you use get this property will be defined on the prototype of the Object, and if you use Object.defineProperty() it will be defined on the instance to which it is applied.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


219. What are the advantages of getters and setters?

Here’s a list of benefits of getters and setters,

1. They provide simpler syntax 2. They are used to define accessors in computed properties or JS. 3. Used to provide equivalence between properties and methods 4. They can provide better data quality 5. Useful for working behind the scenes with encapsulated logic.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


220. Can I add getters and setters using the defineProperty method?

Yes, you can add getters and setters using the object.defineProperty () method. For example, the following counter object uses increment, decrement, plus or minus properties,

 var obj = {counter : 0};

 // Define getters
 Object.defineProperty(obj, "increment", {
   get : function () {this.counter++;}
 });
 Object.defineProperty(obj, "decrement", {
   get : function () {this.counter--;}
 });

 // Define setters
 Object.defineProperty(obj, "add", {
   set : function (value) {this.counter += value;}
 });
 Object.defineProperty(obj, "subtract", {
   set : function (value) {this.counter -= value;}
 });

 obj.add = 10;
 obj.subtract = 5;
 console.log(obj.increment); / / 6
 console.log(obj.decrement); / / 5
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


221. What is the purpose of switch-case?

The switch case statement in JavaScript is used for decision purposes. In some cases, it is more convenient to use a switch case statement than an if-else statement. Syntax is as follows,

 switch (expression)
 {
     case value1:
         statement1;
         break;
     case value2:
         statement2;
         break; .case valueN:
         statementN;
         break;
     default:
         statementDefault;
 }
Copy the code

The multi-way branching statement above provides a simple way to dispatch execution to different parts of the code based on the value of the expression.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


222. What are the rules for using swtich Case?

Here is a list of rules to be aware of,

1. Expressions can be numeric or string types. 2. Expressions do not allow duplicate values. 3. The default statement is optional. If the expression passed to the switch does not match any case value, the statement in the default case is executed. 4. The break statement is used in switch to terminate a sequence of statements. 5. The break statement is optional. But if omitted, execution continues to the next case.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


223. What is a primitive data type?

A primitive data type is data that has an original value (no attributes or methods). There are seven raw data types.

1.string 2.number 3.boolean 4.null 5.undefined 6.bigint 7.symbol

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


224. What are the different ways to access object properties?

There are three possible ways to access an object’s properties.

Dot notation: It uses dots to access properties

 objectName.property
Copy the code

Square bracket notation: It uses square brackets for property access

 objectName["property"]
Copy the code

Expression notation: It uses expressions in square brackets

 objectName[expression]
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


225. What are function argument rules?

JavaScript functions follow the following argument rules,

1. The function defines data types that do not specify parameters. 2. Do not perform type checking on passed parameters. 3. Do not check the number of parameters received. That is, the following functions follow the above rules,

 function functionName(parameter1, parameter2, parameter3) {
   console.log(parameter1); / / 1
 }
 functionName(1);
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


226. What is an error object?

An error object is a built-in error object that provides error information when an error occurs. It has two attributes: name and message. For example, the following function logs error details,

 try {
   greeting("Welcome");
 }
 catch(err) {
   console.log(err.name + "<br>" + err.message);
 }
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


227. When you receive a grammar error

If you try to evaluate code with syntax errors, a SyntaxError is raised. For example, the missing function parameter reference below raises a syntax error

 try {
   eval("greeting('welcome)");   // Missing ' will produce an error
 }
 catch(err) {
   console.log(err.name);
 }
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


228. What are the different error names for error objects?

The error object returns six different types of error names,

Wrong name instructions
EvalError The eval() function failed
RangeError Number out of range error
ReferenceError An error caused by an illegal reference
SyntaxError Errors caused by syntax errors
TypeError Error caused by type error
URIError Error due to encodeURI()

229. What are the various statements in error handling?

The following is a list of statements used in error handling,

1. Try: this statement is used to test if a code block has errors. 2. Catch: this statement is used to handle errors. 3. 4. Finally: This statement is used to execute code after a try and catch, regardless of the result.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


230. What are the two types of loops in javascript?

Controlled Loops: In this type of loop, test conditions before entering the loop body. For example, For loops and While loops fall into this category.

Exit Controlled Loops: In this type of loop, test conditions are tested or evaluated at the end of the loop. That is, the body of the loop will execute at least once regardless of whether the test condition is true or false. For example, a do-while loop falls into this category.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


231. What is NodeJS?

Node.js is a server-side platform built on Chrome’s JavaScript runtime for easily building fast and extensible web applications. It is an event-based, non-blocking, asynchronous I/O runtime that uses Google’s V8 JavaScript engine and libuv library.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


232. What is an Intl object?

Intl objects are namespaces of the ECMAScript internationalization API that provide language-sensitive string comparisons, number formats, and date and time formats. It provides access to several constructors and language-sensitive functions.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


233. How do you perform language-specific date and time formatting?

You can use the Intl.dateTimeFormat object, which is the constructor of an object that enables language-sensitive date and time formats. Let’s look at this behavior with an example,

 var date = new Date(Date.UTC(2019.07.07.3.0.0));
 console.log(new Intl.DateTimeFormat('en-GB').format(date)); / / 07/08/2019
 console.log(new Intl.DateTimeFormat('en-AU').format(date)); / / 07/08/2019
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


234. What is an iterator?

An iterator is an object that defines a sequence and a return value on termination. It implements the iterator protocol using a next() method that returns an object with two attributes :(the next value in the sequence of values) and done (true if the last value in the sequence has been consumed).

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


235. How does synchronous iteration work?

Synchronous iteration was introduced in ES6, which applies to the following set of components,

Iterable: It is an object that can be iterated through a method whose key is symbol. iterator. Iterator: This is an object returned by calling the [symbol.iterator]() iterable. This iterator object wraps the elements of each iteration in an object and returns them one by one through the next() method. IteratorResult: The object returned by the next() method. This object contains two properties; The value attribute contains an iteration element, and the done attribute determines whether the element is the last.

Let’s demonstrate synchronous iteration with the following array,

 const iterable = ['one'.'two'.'three'];
 const iterator = iterable[Symbol.iterator]();
 console.log(iterator.next());  // { value: 'one', done: false }
 console.log(iterator.next());  // { value: 'two', done: false }
 console.log(iterator.next());  // { value: 'three', done: false }
 console.log(iterator.next());  // { value: 'undefined, done: true }
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


236. What is an event loop?

An event loop is a queue of callback functions. When an asynchronous function executes, the callback function is pushed to the queue. The JavaScript engine does not start processing the event loop until the asynchronous function has finished executing the code.

== Note == : Even if JavaScript is single-threaded, it allows Node.js to perform non-blocking I/O operations.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


237. What is the call stack?

The call stack is a data structure in the javascript interpreter that keeps track of function calls in your program. It has two main actions,

1. Every time you call a function to execute it, you are pushing it onto the stack. 2. Every time execution is complete, the function pops off the stack.

Let’s take an example of a state representation in chart format

 function hungry() {
    eatFruits();
 }
 function eatFruits() {
    return "I'm eating fruits";
 }

 // Invoke the `hungry` function
 hungry();
Copy the code

The above code is handled in the call stack as follows,

1. Add the hungry() function to the call stack list and execute the code. 2. Add the eatFruits() function to the call stack list and execute the code. 3. EatFruits () Remove this function from our call stack list. 4. Hungry () removes this function from the call stack list because there are no more items.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


238. What is an event queue?

Temporal decoupling of the sending and processing of messages or events. In layman’s terms, a series of notifications or requests are stored in a queue in first-in, first-out order. When a notification is sent, the request is queued and returned. The system that processes the request later retrieves the request from the queue and processes it.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


239. What is a decorator?

A decorator is an expression that evaluates to a function and takes the target, name, and decorator descriptor as parameters. In addition, it can optionally return a decorator descriptor to install on the target object. Let’s define administrative decorators for user classes at design time,

 function admin(isAdmin) {
    return function(target) {
        target.isAdmin = isAdmin;
    }
 }

 @admin(true)
 class User(a){}console.log(User.isAdmin); //true

  @admin(false)
  class User(a){}console.log(User.isAdmin); //false
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


240. What are the properties of the Intl object?

The following is a list of properties available on Intl objects,

1.Collator: These are the objects that enable language-sensitive string comparisons. 2.DateTimeFormat: These are objects that enable language-sensitive date and time formats. ListFormat: these are language-sensitive ListFormat enabled objects. NumberFormat: Objects that enable language-sensitive number formats. 5.PluralRules: Objects that enable plural-sensitive formats and plural-language-specific rules. 6.RelativeTimeFormat: An object with language-sensitive relative time formats enabled.

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


241. What is a unary operator?

The unary (+) operator is used to convert a variable to a number. If the variable cannot be converted, it will still become a number, but with a NaN value. Let’s look at this behavior in an action.

 var x = "100";
 var y = + x;
 console.log(typeof x, typeof y); // string, number

 var a = "Hello";
 var b = + a;
 console.log(typeof a, typeof b, b); // string, number, NaN
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


242. How do I sort the elements in an array?

The sort() method is used to sort array elements in place and return the sorted array. Example usage is as follows,

 var months = ["Aug"."Sep"."Jan"."June"];
 months.sort();
 console.log(months); // ["Aug", "Jan", "June", "Sep"]
 
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


243. What is the purpose of compareFunction when sorting arrays?

CompareFunction is used to define the sort order. If omitted, the array elements are converted to strings, which are then sorted according to the Unicode code point value of each character. To take an example of the use of compareFunction,

 let numbers = [1.2.5.3.4];
 numbers.sort((a, b) = > b - a);
 console.log(numbers); // [5, 4, 3, 2, 1]
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


244. How do you reverse an array?

You can use the reverse() method to reverse elements in an array. This method is useful for sorting arrays in descending order. Let’s look at the use of the reverse() method in an example,

 let numbers = [1.2.5.3.4];
 numbers.sort((a, b) = > b - a);
 numbers.reverse();
 console.log(numbers); // [1, 2, 3, 4,5]
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


245. How do you find the minimum and maximum values in an array?

You can use the math.min and math.max methods on array variables to find the smallest and largest elements in an array. Let’s create two functions to find the minimum and maximum values in the array,

 var marks = [50.20.70.60.45.30];
 function findMin(arr) {
   return Math.min.apply(null, arr);
 }
 function findMax(arr) {
   return Math.max.apply(null, arr);
 }

 console.log(findMin(marks));
 console.log(findMax(marks));
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


246. How do I find min and Max values without math functions?

You can write functions that loop through groups of numbers, comparing each value to a minimum or maximum to find the minimum and maximum. Let’s create these functions to find minimums and maximums,

  var marks = [50.20.70.60.45.30];
  function findMin(arr) {
    var length = arr.length
    var min = Infinity;
    while (length--) {
      if(arr[length] < min) { min = arr[len]; }}return min;
  }

  function findMax(arr) {
    var length = arr.length
    var max = -Infinity;
    while (len--) {
      if(arr[length] > max) { max = arr[length]; }}return max;
  }

  console.log(findMin(marks));
  console.log(findMax(marks));
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


247. What is a null statement and its purpose?

The empty statement is a semicolon (;) , indicating that no statement will be executed, even if JavaScript syntax requires one. Since empty statements have no actions, you might think they are rarely used, but they can sometimes be useful when you want to create loops with empty bodies. For example, you can initialize an array with a zero value, as shown below,

 // Initialize an array a
 for(int i=0; i < a.length; a[i++] = 0);Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


248. How to obtain module metadata?

You can expose context-specific metadata to JavaScript modules using import.meta as an object with meta-attributes. It contains information about the current module, such as the URL of the module. In a browser, you might get metadata that is different from NodeJS.

 <script type="module" src="welcome-module.js"></script>
 console.log(import.meta); // { url: "file:///home/user/welcome-module.js"
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


249. What is a comma operator?

The comma operator evaluates each of its operands from left to right and returns the value of the last operand. This is completely different from the use of commas in array, object, and function arguments and arguments. For example, a numeric expression can be used as follows,

 var x = 1;
 x = (x++, x);

 console.log(x); / / 2
Copy the code

Let’s go back to the top and we’re on problem 100 and we’re on problem 200


250. What are the advantages of the comma operator?

It is typically used to include multiple expressions where a single expression is needed. One common use of this comma operator is to provide multiple arguments in a for loop. For example, the following for loop uses the comma operator to use multiple expressions in a single place,

 for (var a = 0, b =10; a <= 10; a++, b--)
Copy the code

You can also use the comma operator in a return statement, which is processed before the return.

 function myFunction() {
    var a = 1;
    return (a += 10, a); / / 11
 }
Copy the code

Go back to the top and we’re on problem 250


251. What is typescript?

TypeScript is a typed superset of JavaScript created by Microsoft that adds optional types, classes, async/await, and many other features and compiles to pure JavaScript. Angular is built entirely in TypeScript and is used as the primary language. You can install it globally as

  npm install -g typescript
Copy the code

Let’s look at a simple example of TypeScript usage.

  function greeting(name: string) :string {
     return "Hello, " + name;
  }

  let user = "Sudheer";

  console.log(greeting(user));
Copy the code

The greeting method only allows string types as arguments.

Go back to the top and we’re on problem 250


252. What’s the difference between javascript and typescript?

Here’s a list of the differences between javascript and typescript

function typescript javascript
Language paradigm Object-oriented programming language Scripting language
Typing support Static typing support It has dynamic typing
The module support Does not support
interface It has the concept of interfaces Interface not supported
Optional parameters The function supports optional arguments Optional arguments to functions are not supported

Go back to the top and we’re on problem 250


253. What are typescript’s advantages over javascript?

Here are some advantages of typescript over javascript,

1.TypeScript only finds compile-time errors at development time and ensures that runtime errors are minimized. Javascript is an interpreted language. 2.TypeScript is strongly typed or supports static typing, allowing type correctness to be checked at compile time. This is not available in javascript. 3. The TypeScript compiler compiles.ts files to ES3, ES4, and ES5, unlike the ES6 features of JavaScript that some browsers may not support.

Go back to the top and we’re on problem 250


254. What is an object initializer?

An object initializer is an expression describing the initialization of an object. The syntax for this expression is a comma-separated list of zero or more pairs of attribute names and object associated values, enclosed in curly braces ({}). This is also called literal notation. It’s one of the ways to create an object.

 var initObject = {a: 'Haiyong'.b: 50.c: {}};

 console.log(initObject.a); // Haiyong
Copy the code

Go back to the top and we’re on problem 250


255. What is a constructor?

Constructor methods are special methods used to create and initialize objects created in a class. If no constructor method is specified, the default constructor is used. An example use of the constructor is as follows,

 class Employee {
   constructor() {
     this.name = "Haiyong"; }}var employeeObject = new Employee();

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

Go back to the top and we’re on problem 250


256. What happens if a constructor is written more than once in a class?

A “constructor” in a class is a special method that can only be defined once in a class. That is, if you write a constructor method multiple times in a class, it will throw a SyntaxError.

  class Employee {
    constructor() {
      this.name = "Haiyong";
    }
    constructor() {   // Uncaught SyntaxError: A class may only have one constructor
      this.age = 30; }}var employeeObject = new Employee();

  console.log(employeeObject.name);
Copy the code

Go back to the top and we’re on problem 250


257. How do I call the constructor of a parent class?

You can use the super keyword to call the constructor of the parent class. Remember that super() must be called before using the “this” reference. Otherwise, reference errors will result. Let’s use it,

class Square extends Rectangle {
   constructor(length) {
     super(length, length);
     this.name = 'Square';
   }

   get area() {
     return this.width * this.height;
   }

   set area(value) {
     this.area = value; }}Copy the code

Go back to the top and we’re on problem 250


258. How do you get the prototype of an object?

You can use the object.getProtoTypeof (obj) method to return the prototype of a specified Object. The value of the internal Prototype property. If there is no inherited attribute, null returns the value.

 const newPrototype = {};
 const newObject = Object.create(newPrototype);

 console.log(Object.getPrototypeOf(newObject) === newPrototype); // true
Copy the code

Go back to the top and we’re on problem 250


259. What happens if I pass a string type to the getPrototype method?

In ES5, if the obj argument is not an object, it raises TypeError. In ES2015, this parameter is cast to Object.

 // ES5
 Object.getPrototypeOf('CSDN'); // TypeError: "CSDN" is not an object
 // ES2015
 Object.getPrototypeOf('CSDN'); // String.prototype
Copy the code

Go back to the top and we’re on problem 250


260. How do I set the prototype of one object to another?

You can use methods that set the Prototype (that is, the internal Prototype property) of the specified Object Object.setProtoTypeof () to another Object or null. For example, if you wanted to set the prototype of a square object to a rectangular object, you would look like this,

 Object.setPrototypeOf(Square.prototype, Rectangle.prototype);
 Object.setPrototypeOf({}, null);
Copy the code

Go back to the top and we’re on problem 250


261. How do you check if an object is extensible?

The object.isextensible () method is used to determine whether an Object isExtensible. That is, whether it can add new attributes.

 const newObject = {};
 console.log(Object.isExtensible(newObject)); //true
Copy the code

== Note == : By default, all objects are extensible. That is, new attributes can be added or modified.

Go back to the top and we’re on problem 250


262. How do I prevent object expansion?

The object.preventExtensions () method is used to prevent new properties from being added to the Object. In other words, it prevents future extensions to objects. Let’s look at how this property is used,

 const newObject = {};
 Object.preventExtensions(newObject); // Not extensible

 try {
   Object.defineProperty(newObject, 'newProperty', { // Add a new attribute
     value: 100
   });
 } catch (e) {
   console.log(e); // Type error: attribute newProperty cannot be defined, object is not extensible
 }
Copy the code

Go back to the top and we’re on problem 250


263. What are the different ways to make an object unextensible?

You can mark an object as unextensible in three ways,

1.Object.preventExtensions 2.Object.seal 3.Object.freeze

 var newObject = {};

 Object.preventExtensions(newObject); // Prevent objects from being unextensible
 Object.isExtensible(newObject); // false

 var sealedObject = Object.seal({}); // The sealed object cannot be extended
 Object.isExtensible(sealedObject); // false

 var frozenObject = Object.freeze({}); // Frozen objects are not extensible
 Object.isExtensible(frozenObject); // false
Copy the code

Go back to the top and we’re on problem 250


264. How can I define multiple attributes on an object?

The object.defineProperties () method is used to define new properties directly on an Object or modify existing properties and return the Object. Let’s define multiple properties on an empty object,

 const newObject = {};

 Object.defineProperties(newObject, {
   newProperty1: {
     value: 'Haiyong'.writable: true
   },
   newProperty2: {}});Copy the code

Go back to the top and we’re on problem 250


265. What is MEAN in JavaScript?

The MEAN (MongoDB, Express, AngularJS, and Node.js) stack is the most popular open source JavaScript software technology stack for building dynamic Web applications, You can write the server-side and client-side parts of your Web project entirely in JavaScript.

Go back to the top and we’re on problem 250


266. What is confusion in javascript?

Obfuscation is the deliberate act of creating obfuscated javascript code (that is, source code or machine code) that is difficult for humans to understand. It is similar to encryption, but the machine can understand the code and execute it. Let’s look at the following function before we get confused,

 function greeting() {
    console.log('Hello, welcome to JS world');
 }
Copy the code

After code obfuscation, it appears as follows,

 eval(function(p,a,c,k,e,d){e=function(c){return c};if(!' '.replace(/ ^ /.String)
Copy the code

Go back to the top and we’re on problem 250


267. Why confusion?

Here are a few reasons for confusion,

1. Code size will be reduced. So the data transfer between the server and the client is very fast. It hides business logic from the outside world and protects code from others. 3. Reverse engineering is difficult. Download times will be reduced

Go back to the top and we’re on problem 250


268. What is Minification?

Zoom is the process of removing all unnecessary characters (removing Spaces), and variables are renamed without changing their function. This is also a kind of confusion.

Go back to the top and we’re on problem 250


269. What are the benefits of shrinking?

In general, it is recommended to use minimization in cases of heavy traffic and resource-intensive requirements. It reduces file size with the following benefits,

1. Reduce web page loading time 2. Save bandwidth usage

Go back to the top and we’re on problem 250


270. What is the difference between obfuscation and encryption?

Here are the main differences between obfuscation and encryption,

features confusion encryption
define Change the form of any data in any other form Use a key to change the form of information to an unreadable format
The key to decoding Can be decoded without any key It is required
Target data format It will be converted into complex forms Convert to an unreadable format

Go back to the top and we’re on problem 250


271. What are the commonly used miniaturization tools?

There are many online/offline tools for miniaturizing javascript files,

  • Google’s Closure compiler
  • jsmin
  • javascript-minifier.com
  • Prettydiff.com

Go back to the top and we’re on problem 250


272. How do you perform form validation using javascript?

JavaScript can be used to perform HTML form validation. For example, if the form field is empty, the function needs to be notified and returns false to prevent the form from being submitted. Let’s perform the user login in HTML,

 <form name="myForm" onsubmit="return validateForm()" method="post">
 User name: <input type="text" name="uname">
 <input type="submit" value="Submit">
 </form>
Copy the code

User login verification is as follows,

 function validateForm() {
   var x = document.forms["myForm"] ["uname"].value;
   if (x == "") {
     alert("The username shouldn't be empty");
     return false; }}Copy the code

Go back to the top and we’re on problem 250


273. How do I perform form validation without javascript?

You can perform HTML form validation automatically without using javascript. Enable validation by applying the Required attribute to prevent submission of the form when the input is empty.

 <form method="post">
   <input type="text" name="uname" required>
   <input type="submit" value="Submit">
 </form>
Copy the code

== Note == : Automatic form validation does not work in Internet Explorer 9 or earlier.

Go back to the top and we’re on problem 250


274. What are the DOM methods available for constraint validation?

The following DOM methods can be used to constrain validation of invalid input,

CheckValidity () : Returns true if the input element contains valid data. 2. SetCustomValidity () : Used to set the validationMessage property of the input element. Let’s use a user login form with DOM authentication

 function myFunction() {
   var userName = document.getElementById("uname");
   if(! userName.checkValidity()) {document.getElementById("message").innerHTML = userName.validationMessage;
   } else {
     document.getElementById("message").innerHTML = "Entered a valid username"; }}Copy the code

Go back to the top and we’re on problem 250


275. What are the constraints available to validate DOM attributes?

Here is a list of the DOM attributes that are available for constraint validation,

1. Validity: It provides a list of Boolean attributes related to the validity of the input element. 2. ValidationMessage: Displays messages when validity is false. 3. WillValidate: Indicates whether the input element will be validated.

Go back to the top and we’re on problem 250


276. What is a validity attribute list?

The validity attributes of an input element provide a set of attributes related to data validity.

1. CustomError: Returns true if a custom validity message is set. 2. PatternMismatch: Return true if the value of the element does not match its schema attribute. 3. RangeOverflow: returns true if the value of an element is greater than its Max attribute. RangeUnderflow: Returns true if the value of an element is less than its min attribute. 5. StepMismatch: Return true if the element value is invalid based on the step attribute. TooLong: Returns true if the value of an element exceeds its maxLength attribute. TypeMismatch: Returns true if the value of the element is invalid based on the type attribute. ValueMissing: Returns true if the element with the required attribute has no value. 9. Valid: Returns true if the element value is valid.

Go back to the top and we’re on problem 250


277. Example of using the rangeOverflow property?

The rangeOverflow property returns true if the value of an element is greater than its Max property. For example, if the value is greater than 100, the following form reference raises an error,

 <input id="age" type="number" max="100">
 <button onclick="myOverflowFunction()">OK</button>
Copy the code
 function myOverflowFunction() {
   if (document.getElementById("age").validity.rangeOverflow) {
     alert("The mentioned age is not allowed"); }}Copy the code

Go back to the top and we’re on problem 250


278. Is enumeration provided in javascript?

No, javascript itself does not support enumerations. But there are different kinds of solutions that can simulate them, even though they may not provide exact equivalents. For example, you can use freezes or seals on objects,

 var DaysEnum = Object.freeze({"monday":1."tuesday":2."wednesday":3. })Copy the code

Go back to the top and we’re on problem 250


279. What is enumeration?

Enumeration is a type that restricts a variable to a single value from a predefined set of constants. JavaScript doesn’t have enumerations, but typescript does have built-in support for them.

 enum Color {
  RED, GREEN, BLUE
 }
Copy the code

Go back to the top and we’re on problem 250


280. How do you list all the attributes of an object?

You can use this Object. GetOwnPropertyNames () method returns directly find all of the attributes in the given Object array. Let’s use it in an example,

 const newObject = {
   a: 1.b: 2.c: 3
 };

 console.log(Object.getOwnPropertyNames(newObject));  ["a"."b"."c"]
Copy the code

Go back to the top and we’re on problem 250


281. How do I get the property descriptor of an object?

You can use Object. GetOwnPropertyDescriptors () returns a given Object method of all his property descriptors. An example use of this method is as follows,

  const newObject = {
    a: 1.b: 2.c: 3
  };
 const descriptorsObject = Object.getOwnPropertyDescriptors(newObject);
 console.log(descriptorsObject.a.writable); //true
 console.log(descriptorsObject.a.configurable); //true
 console.log(descriptorsObject.a.enumerable); //true
 console.log(descriptorsObject.a.value); / / 1
Copy the code

Go back to the top and we’re on problem 250


282. What properties do attribute descriptors provide?

Property descriptors are records that have the following properties

Writable: disables any additional information that can be changed without any additional control. If the type of the property descriptor can be changed and the property can be deleted from any additional object, the 64x works without any additional control. 4. Enumerable: Determine if the property appears when enumerating a property on the corresponding object. Set: a function that acts as a setter for properties. 6. Get: a function that acts as a getter for properties

Go back to the top and we’re on problem 250


283. How do you extend classes?

The extends keyword is used in a class declaration/expression to create a class that is a subclass of another class. It can be used to subclass custom classes as well as built-in objects. Syntax is as follows,

 class ChildClass extends ParentClass {... }Copy the code

Let’s take the Square subclass of Polygon’s parent class,

  class Square extends Rectangle {
    constructor(length) {
      super(length, length);
      this.name = 'Square';
    }

    get area() {
      return this.width * this.height;
    }

    set area(value) {
      this.area = value; }}Copy the code

Go back to the top and we’re on problem 250


284. How do I change the URL without reloading the page?

The window.location.url property will help modify the URL, but it will reload the page. HTML5 introduces history.pushstate () and history.replacestate () methods, which allow you to add and modify history entries, respectively. For example, you can use pushState as follows,

 window.history.pushState('page2'.'Title'.'/page2.html');
Copy the code

Go back to the top and we’re on problem 250


285. How do I check if an array contains a specific value?

The Array#includes() method is used to determine whether an array contains a particular value in its entries by returning true or false. Let’s look at an example of finding elements (numbers and strings) in an array.

 var numericArray = [1.2.3.4];
 console.log(numericArray.includes(3)); // true

 var stringArray = ['green'.'yellow'.'blue'];
 console.log(stringArray.includes('blue')); //true
Copy the code

Go back to the top and we’re on problem 250


286. How do you compare scalar arrays?

You can compare two scalar arrays (directly using === for comparison) using length and the array’s every method. The combination of these expressions gives the desired result,

 const arrayFirst = [1.2.3.4.5];
 const arraySecond = [1.2.3.4.5];
 console.log(arrayFirst.length === arraySecond.length && arrayFirst.every((value, index) = > value === arraySecond[index])); // true
Copy the code

If you want to compare arrays regardless of order, then you should sort them first,

const arrayFirst = [2.3.1.4.5];
const arraySecond = [1.2.3.4.5];
console.log(arrayFirst.length === arraySecond.length && arrayFirst.sort().every((value, index) = > value === arraySecond[index])); //true
Copy the code

Go back to the top and we’re on problem 250


287. How do I get values from get parameters?

The new URL() object accepts the URL string searchParams, whose properties can be used to access the fetch parameters. Keep in mind that you may need to use polyfill or window.location to access urls in older browsers, including Internet Explorer.

let urlString = "http://www.some-domain.com/about.html?x=1&y=2&z=3"; //window.location.href
let url = new URL(urlString);
let parameterZ = url.searchParams.get("z");
console.log(parameterZ); / / 3
Copy the code

Go back to the top and we’re on problem 250


288. How do you print numbers using commas as thousands separators?

You can use the Number. The prototype. ToLocaleString () method returns the string with language sensitive said, for example, a one thousand – bit separator, currency, etc.

function convertToThousandFormat(x){
return x.toLocaleString(); / / 12345679
}

console.log(convertToThousandFormat(12345.6789));
Copy the code

Go back to the top and we’re on problem 250


289. What is the difference between Java and javascript?

Both are completely unrelated programming languages, and there is no relationship between them. Java is statically typed, compiled, and runs on its own VM. Javascript, on the other hand, is dynamically typed, interpreted, and run in a browser and nodeJS environment. Let’s look at the main differences in table formats

features java JavaScript
type It is a strongly typed language It is a dynamically typed language
paradigm Object-oriented programming Prototype-based programming
The scope of Block scope Function scope
concurrent Based on the thread Based on the event
memory Use more memory Use less memory. So it will be used for web pages

Specific differences between reference: haiyong.blog.csdn.net/article/det…

Go back to the top and we’re on problem 250


290. Does javascript support namespaces?

JavaScript does not support namespaces by default. Therefore, if you create any element (function, method, object, variable), it becomes global and pollutes the global namespace. Let’s take an example of defining two functions that do not have any namespaces

function func1() {
console.log("That's the first definition.");

}
function func1() {
console.log("That's the second definition.");
}
func1(); // This is the second definition
Copy the code

It always calls the second function definition. In this case, namespace resolves name conflicts.

Go back to the top and we’re on problem 250


291. How do you declare namespaces?

Although JavaScript lacks namespaces, we can create namespaces using Objects, IIFE.

Use object literals: Let’s wrap variables and functions in object literals that act as namespaces. You can then access them using object notation

var namespaceOne = {
function func1() {
console.log("This is a first definition"); }}var namespaceTwo = {
function func1() {
console.log("This is a second definition");
}
}
namespaceOne.func1(); // This is a first definition
namespaceTwo.func1(); // This is a second definition
Copy the code

Using IIFE (Call function expressions now) : The outer pair of parentheses of IIFE creates a local scope for all code inside it and makes the anonymous function a function expression. Therefore, you can create the same function in two different function expressions to act as a namespace.

(function() {
function fun1(){
console.log("That's the first definition."); } fun1(); } ()); (function() {
function fun1(){
console.log("That's the second definition."); } fun1(); } ());Copy the code

Use block and LET /const declarations: In ECMAScript 6, you can simply use block and LET declarations to limit the scope of variables to blocks.

{
let myFunction= function fun1(){
console.log("That's the first definition.");
}
myFunction();
}
//myFunction(): ReferenceError: myFunction undefined.

{
let myFunction= function fun1(){
console.log("That's the second definition.");
}
myFunction();
}
//myFunction(): ReferenceError: myFunction undefined.
Copy the code

Go back to the top and we’re on problem 250


292. How do I call javascript code in iframe from the parent page?

You initially need to use document.getelementby or access iFrame window.frames. After the contentWindowiFrame property provides access to targetFunction

document.getElementById('targetFrame').contentWindow.targetFunction();
window.frames[0].frameElement.contentWindow.targetFunction(); // Accessing iframe in this way may not work with the latest versions of Chrome and Firefox
Copy the code

Go back to the top and we’re on problem 250


293. How do I get the time zone offset from the date?

You can use the getTimezoneOffset date object method. This method returns the time zone difference in minutes from the current locale (host system Settings) to UTC

var offset = new Date().getTimezoneOffset();
console.log(offset); / / - 480
Copy the code

Go back to the top and we’re on problem 250


294. How do I load CSS and JS files dynamically?

You can create link and script elements in the DOM and append them as children to the head tag. Let’s create a function to add script and style resources, as shown below,

function loadAssets(filename, filetype) {
if (filetype == "css") { // External CSS file
var fileReference = document.createElement("link")
fileReference.setAttribute("rel"."stylesheet");
fileReference.setAttribute("type"."text/css");
fileReference.setAttribute("href", filename);
} else if (filetype == "js") { // External JavaScript file
var fileReference = document.createElement('script');
fileReference.setAttribute("type"."text/javascript");
fileReference.setAttribute("src", filename);
}
if (typeoffileReference ! ="undefined")
document.getElementsByTagName("head") [0].appendChild(fileReference)
}
Copy the code

Go back to the top and we’re on problem 250


295. What are the different ways to find HTML elements in the DOM?

If you want to access any element in an HTML page, you need to start by accessing the document object. You can later find HTML elements using any of the following methods,

1. The document. The getElementById (id) : by id lookup element (2) the document. The getElementsByTagName (name) : Through the element tag name lookup 3. Document. GetElementsByClassName (name) : element via the name of the class

Go back to the top and we’re on problem 250


296. What is jQuery?

JQuery is a popular cross-browser JavaScript library that provides document Object Model (DOM) traversal, event handling, animation, and AJAX interaction by minimizing differences between browsers. It is known for its “write less, do more” philosophy. For example, you can use jQuery to display a welcome message when the page loads, as shown below,

$(document).ready(function(){ // It selects the document and applies it when the page loads
alert('Welcome to jQuery world');
});
Copy the code

== Note == : You can download it from the official jquery website or install it from a CDN (such as Google).

Siphiwe go back to the top on question 250


297. What is the V8 JavaScript engine?

V8 is an open source, high-performance JavaScript engine for Google Chrome, written in C++. It is also used in Node.js projects. It implements ECMAScript and WebAssembly and runs on Windows 7 or later, macOS 10.12+, and Linux systems using X64, IA-32, ARM, or MIPS processors.

== note == : this can be run independently or embedded in any C++ application.

Siphiwe go back to the top on question 250


298. Why do we call javascript a dynamic language?

JavaScript is a loosely typed or dynamic language because variables in JavaScript are not directly associated with any particular value type, and any variable can assign/reassign values of all types.

let age = 50; // age is a number now
age = 'old'; // age is a string now
age = true; // age is a boolean
Copy the code

Siphiwe go back to the top on question 250


299. What is the air freight operator?

The void operator evaluates the given expression and returns undefined (that is, no value). Syntax is as follows,

void (expression)
void expression
Copy the code

Let’s display a message without any redirection or reload

<a href="javascript:void(alert('Welcome to JS world'))">Click here to see a message</a>
Copy the code

== Note that == : This operator is usually used to get an undefined raw value, using “void(0)”.

Go back to the top and we’re on problem 250


300. How do I set cursor wait?

You can use the property “cursor” to set the cursor to wait in JavaScript. Let’s use the following function to perform this behavior when the page loads.

function myFunction() {
window.document.body.style.cursor = "wait";
}
Copy the code

This function is called when the page loads

<body onload="myFunction()">
Copy the code

Siphiwe go back to the top to question 300


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

More relevant articles and my contact information are listed here:

Github.com/wanghao221 gitee.com/haiyongcsdn…

If you really learn something new from this article, like it, bookmark it and share it with your friends. 🤗 and finally, don’t forget ❤ or 📑