This is the 27th 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)

To make it easier to read on my phone, I put links back to the top or back to the corresponding question wherever necessary

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?

1. What are some possible ways to create objects in JavaScript?

There are many ways to create objects in javascript, as shown below

1. Object constructor:

The easiest way to create an empty Object is to use the Object constructor. This approach is not currently recommended.

  var object = new Object(a);Copy the code

2. Object creation method:

The create method of Object creates a new Object by passing the prototype Object as a parameter

  var object = Object.create(null);
Copy the code

3. Object literal syntax:

The object literal syntax is equivalent to the create method when null is passed as an argument

  var object = {};
Copy the code

4. Function constructor:

Create any function and apply the new operator to create an object instance,

  function Person(name){
     var object = {};
     object.name=name;
     object.age=21;
     return object;
  }
  var object = new Person("Sudheer");
Copy the code

5. Function constructors with prototypes:

This is similar to a function constructor, but it uses stereotypes as its properties and methods,

  function Person(){}
  Person.prototype.name = "Sudheer";
  var object = new Person();
Copy the code

This is equivalent to creating an instance using an object creation method with a function prototype, and then calling the function with the instance and parameters as arguments.

  function func {};

  new func(x, y, z);
Copy the code

(or)

  // Create a new instance using the function prototype.
  var newInstance = Object.create(func.prototype)

  // Call the function
  var result = func.call(newInstance, x, y, z),

  // If the result is a non-empty object, it is used, otherwise only the new instance is used.
  console.log(result && typeof result === 'object' ? result : newInstance);
Copy the code

6. 6. How do you do?

ES6 introduces the class feature to create objects

  class Person {
     constructor(name) {
        this.name = name; }}var object = new Person("Sudheer");
Copy the code

7. Singletons:

A Singleton is an object that can only be instantiated once. Repeated calls to its constructor return the same instance, ensuring that they do not accidentally create multiple instances.

  var object = new function(){
     this.name = "Sudheer";
  }
Copy the code

Cross tracks


2. What is a prototype chain?

Prototype chains are used to build new types of objects based on existing objects. It is similar to inheritance in class-based languages.

The prototype on an instance of an Object can be obtained through the object.getPrototypeof (Object) or proto property, while the prototype on a constructor can be obtained through object.prototype.

Cross tracks


3. What’s the difference between call, apply and bind?

The difference between Call, Apply, and Bind can be explained by the following example,

Call: The call() method calls a function with the given value of this and the arguments

var employee1 = {firstName: 'Haiyong'.lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy'.lastName: 'Baily'};

function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}

invite.call(employee1, 'Hello'.'How are you? '); // Hello Haiyong Rodson, How are you?
invite.call(employee2, 'Hello'.'How are you? '); // Hello Jimmy Baily, How are you?
Copy the code

Apply: Calls a function with a given value of this and allows you to pass the arguments in as an array

var employee1 = {firstName: 'Haiyong'.lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy'.lastName: 'Baily'};

function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}

invite.apply(employee1, ['Hello'.'How are you? ']); // Hello Haiyong Rodson, How are you?
invite.apply(employee2, ['Hello'.'How are you? ']); // Hello Jimmy Baily, How are you?
Copy the code

Bind: returns a new function that allows you to pass any number of arguments

var employee1 = {firstName: 'Haiyong'.lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy'.lastName: 'Baily'};

function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}

var inviteEmployee1 = invite.bind(employee1);
var inviteEmployee2 = invite.bind(employee2);
inviteEmployee1('Hello'.'How are you? '); // Hello Haiyong Rodson, How are you?
inviteEmployee2('Hello'.'How are you? '); // Hello Jimmy Baily, How are you?
Copy the code

Call and apply are interchangeable. Both execute the current function immediately. You need to decide whether it’s easier to send an array or a comma-separated argument list. You can remember this by handling Call for commas (to separate lists) and Apply for arrays.

Bind creates a new function that sets this as the first argument passed to Bind ().

Cross tracks


4. What is JSON and its common operations?

JSON is a text-based data format that follows the JavaScript object syntax and was introduced by Douglas Crockford. Useful when you want to transfer data over the network, it’s basically just a text file with a.json extension and a MIME type called Application/JSON

Parse: converts a string to a native object

JSON.parse(text)
Copy the code

Stringization: Converts a native object to a string so that it can be transmitted over the network

JSON.stringify(object)
Copy the code

Cross tracks


5. What is the purpose of the array slice() method?

The slice() method returns the element selected in the array as a new array object. It selects the element that starts with the given start argument and ends at the given optional end argument, excluding the last element. If the second argument is omitted, it is selected until the end.

Some examples of this approach are,

let arrayIntegers = [1.2.3.4.5];
let arrayIntegers1 = arrayIntegers.slice(0.2); / / returns [1, 2]
let arrayIntegers2 = arrayIntegers.slice(2.3); // returns [3]
let arrayIntegers3 = arrayIntegers.slice(4); //returns [5]
Copy the code

== Note that the == : Slice method does not change the original array, but returns the subset as a new array.

Cross tracks


6. What is the purpose of the array splice() method?

The splice() method is used to add/remove items to/from the array and then return the deleted items. The first argument specifies the array location to insert or delete, and the second option argument indicates the number of elements to delete. Each additional parameter is added to the array.

Some examples of this approach are,

let arrayIntegersOriginal1 = [1.2.3.4.5];
let arrayIntegersOriginal2 = [1.2.3.4.5];
let arrayIntegersOriginal3 = [1.2.3.4.5];

let arrayIntegers1 = arrayIntegersOriginal1.splice(0.2); // returns [1, 2]; original array: [3, 4, 5]
let arrayIntegers2 = arrayIntegersOriginal2.splice(3); // returns [4, 5]; original array: [1, 2, 3]
let arrayIntegers3 = arrayIntegersOriginal3.splice(3.1."a"."b"."c"); //returns [4]; original array: [1, 2, 3, "a", "b", "c", 5]
Copy the code

== Note that the == : Splice method modifies the original array and returns the deleted array.

Cross tracks


7. What’s the difference between slice() and splice()?

Some major differences in tabular form

slice() splice()
Do not modify the original array (immutable) Modify the original array (mutable)
Returns a subset of the original array Returns the deleted elements as an array
Used to select elements from an array Used to insert or remove elements from an array

Cross tracks


8. How do you compare Object and Map

Objects are similar to Maps in that they both allow you to set keys to values, retrieve those values, delete keys, and detect whether a key stores something. For this reason, objects have historically been used as maps. But in some cases, there are some important differences in using Map.

  • The keys of Object are strings and symbols, and they can be any value of Map, including Functions, Object, and any primitive.
  • Keys in a Map are ordered, whereas keys added to an Object are not. Thus, when iterated over it, a Map object returns keys in the order in which they were inserted.
  • You can easily get the size of the Map using the size attribute, whereas the number of attributes in Object must be determined manually.
  • A Map is iterable, so you can iterate directly, whereas an iterated Object needs to somehow get its key and iterate over it.
  • An object has a prototype, so there are some default keys in the map that might conflict with your keys if you’re not careful. Starting with ES5, this can be done by usingmap =Object.create(null)Bypass, but rarely do so.
  • Maps may perform better in scenarios that involve frequent addition and removal of key pairs.

Cross tracks


9. What’s the difference between the == and === operators?

JavaScript provides strict (===,! ==) and type conversions (==,! =) equality comparison. Strict operators consider the type of a variable, whereas non-strict operators type correction/conversion based on the value of a variable. Strict operators follow different types of conditions,

  1. Two strings are strictly equal when they have the same sequence of characters, the same length, and the same characters in the corresponding position.
  2. When two numbers are numerically equal, they are strictly equal. That is, it has the same value. There are two special cases here,

NaN is not equal to anything, including NaN. Positive and negative zeros are equal to each other.

  1. If both Boolean operands are true or both are false, two Boolean operands are strictly equal.
  2. If two objects reference the same object, they are strictly equal.
  3. Null and Undefined types and= = =Not equal to, but equal to= =The same. That is,null===undefined --> falsenull==undefined --> true

Some examples that cover the above situations,

0= =false   // true
0= = =false  // false
1= ="1"     // true
1= = ="1"    // false
null= =undefined // true
null= = =undefined // false
'0'= =false // true
'0'= = =false // false
[]==[] or []===[] //false, refer different objects in memory
{}=={} or {}==={} //false, refer different objects in memory
Copy the code

Cross tracks


10. What is a lambda or arrow function?

Arrow functions are phrasal functions of function expressions and do not have their own this, arguments, super, or new.target. These functions are best suited for non-method functions and cannot be used as constructors.

Cross tracks


11. What is a first-class function?

In Javascript, functions are first class objects. A first-class function means that a function in the language is treated as any other variable.

For example, in this language, a function can be passed as an argument to another function, returned by another function, or assigned as a value to a variable. For example, in the following example, the handler assigned to the listener

const handler = () = > console.log ('This is a click handler function');
document.addEventListener ('click', handler);
Copy the code

Cross tracks


12. What is a first-order function?

A first-order function is a function that does not take another function as an argument and does not return a function as its return value.

const firstOrder = () = > console.log ('I am a first order function! ');
Copy the code

Cross tracks


13. What is a higher-order function?

A higher-order function is a function that takes another function as a parameter, returns a function as a return value, or both.

const firstOrderFunc = () = > console.log ('Hello, I am a First order function');
const higherOrder = ReturnFirstOrderFunc= > ReturnFirstOrderFunc();
higherOrder(firstOrderFunc);
Copy the code

Cross tracks


14. What is a function of one variable?

A monadic function is a function that takes only one argument. It represents a single parameter accepted by a function.

Let’s take a function of one variable,

const unaryFunction = a= > console.log (a + 10); // Add 10 to the given parameter
Copy the code

Cross tracks


15. What is a Curryization function?

Currying is the process of converting a function with multiple arguments into a sequence of functions with only one argument each. Currying is named after the mathematician Haskell Curry. And by applying currying, the n-element function becomes a function of one.

Let’s take an example of an n-ary function, and how it becomes a curryized function,

const multiArgFunction = (a, b, c) = > a + b + c;
console.log(multiArgFunction(1.2.3));/ / 6

const curryUnaryFunction = a= > b= > c= > a + b + c;
curryUnaryFunction (1); // return a function: b => c => 1 + b + c
curryUnaryFunction (1) (2); // return a function: c => 3 + c
curryUnaryFunction (1) (2) (3); // return the number 6
Copy the code

The Curried functions are useful for improving code reusability and function combinations.

Cross tracks


What is a pure function?

A pure function is a function whose return value is determined only by its arguments without any side effects. That is, if you call a function with the same argument ‘n’ times and ‘n’ positions in your application, it will always return the same value.

Let’s take an example of the difference between pure functions and impure functions,

/ / not pure
let numberArray = [];
const impureAddNumber = number= > numberArray.push(number);
/ / pure
const pureAddNumber = number= > argNumberArray= >
  argNumberArray.concat([number]);

// Display the result
console.log (impureAddNumber(6)); // returns 1
console.log (numberArray); // returns [6]
console.log (pureAddNumber(7) (numberArray)); // returns [6, 7]
console.log (numberArray); // returns [6]
Copy the code

According to the code snippet above, the push function itself is impure by changing the array and returning a push numeric index that is independent of the parameter value. Concat, on the other hand, takes an array and concatenates it with another array, producing a brand new array with no side effects. In addition, the return value is a concatenation of the previous array.

Remember, pure functions are important because they simplify unit testing, don’t have any side effects, and don’t require dependency injection. They also avoid tight coupling and make your application harder to break by not having any side effects. These principles are combined with the concept of constancy in ES6 by giving preference to const over let.

Cross tracks


17. What is the use of the let keyword?

The let statement declares a block-scoped local variable. Therefore, the scope of a variable defined with the let keyword is limited to the block, statement, or expression that uses it. Variables declared with the var keyword are used to define global or local variables, regardless of the block scope.

Here’s an example of how to use it,

let counter = 30;
if (counter === 30) {
  let counter = 31;
  console.log(counter); / / 31
}
console.log(counter); // 30 (because there is no variable in the if block)
Copy the code

Cross tracks


18. What’s the difference between let and var?

List the differences in a tabular format

var let
It is available from JavaScript onwards Introduced as part of ES6
It has function scope It has block scope
The variable will be promoted Promoted but not initialized
Let’s take an example of the difference,
function userDetails(username) {
   if(username) {
     console.log(salary); Undefined due to variable promotion
     console.log(age); // Error: "age" cannot be accessed before initialization
     let age = 30;
     var salary = 10000;
   }
   console.log(salary); //10000 (accessible to the appropriate function range)
   console.log(age); // Error: age not defined (due to block scope)
}
userDetails('Haiyong');
Copy the code

Cross tracks


19. Why do you choose the name “let” as the keyword?

A let is a mathematical statement adopted by early programming languages such as Scheme and Basic. It is borrowed from dozens of other languages where lets have used var as a traditional keyword as possible.

Cross tracks


20. How do you redeclare variables in a switch block without errors?

If you try to redeclare the variable in A, the switch block will result in an error because there is only one block. For example, the following code block throws the following syntax error,

let counter = 1;
switch(x) {
  case 0:
    let name;
    break;

  case 1:
    let name; // Redeclared syntax error.
    break;
}
Copy the code

To avoid this error, you can create a nested block in the case clause and create a new block-scope lexical environment.

let counter = 1;
    switch(x) {
      case 0: {
        let name;
        break;
      }
      case 1: {
        let name; // There is no SyntaxError for redeclaration.
        break; }}Copy the code

Cross tracks


21. What are temporary dead zones?

A temporary dead zone is a behavior in JavaScript that occurs when a variable is declared with the let and const keywords, but not with var. In ECMAScript 6, accessing a letorconst before its declaration (and within its scope) results in a ReferenceError. The time span during which this happens, between the creation and declaration of the variable binding, is called the time dead zone.

Let’s look at this behavior with an example,

function somemethod() {
  console.log(counter1); // undefined
  console.log(counter2); // ReferenceError
  var counter1 = 1;
  let counter2 = 2;
}
Copy the code

Cross tracks


22. What is IIFE (Perform function expressions immediately)?

IIFE (Call Function Expression Immediately) is a JavaScript function that runs immediately after it is defined. It was signed as follows,

(function ()
    {
      // Write logic here}) ();Copy the code

The main reason to use IIFE is for data privacy, since any variables declared in the IIFE cannot be accessed by the outside world. That is, if you try to access a variable using IIFE, the following error will be raised,

(function ()
        {
          var message = "IIFE";
          console.log(message); }) ();console.log(message); //Error: Message is not defined
Copy the code

Cross tracks


23. What are the benefits of using modules?

There are many benefits to using modules for extensions. Some of the benefits are,

  • maintainability
  • reusability
  • The namespace

Cross tracks


What is memoization?

Memoization is a programming technique that attempts to improve the performance of a function by caching the results of previous calculations. Each time the Memoized function is called, its parameters are used to index the cache. If the data exists, it can be returned without executing the entire function. Otherwise, execute the function and add the result to the cache.

Let’s take an example of adding memorization,

const memoizAddition = () = > {
  let cache = {};
 return (value) = > {
  if (value in cache) {
   console.log('Fetching from cache');
   return cache[value]; // In this case, cache.value cannot be used as a property name that begins with a number, which is not a valid JavaScript identifier. Therefore, it can only be accessed using square bracket notation.
  }
  else {
   console.log('Calculating result');
   let result = value + 20;
   cache[value] = result;
   returnresult; }}}// memoizAddition returns a function
const addition = memoizAddition();
console.log(addition(20)); // output: 40 calculated
console.log(addition(20)); // Output: 40 cached
Copy the code

Cross tracks


25. What is the use of reactive power?

In the case of reactive power, a JavaScript mechanism is used in which variable and function declarations are moved to the top of their scope before code is executed. Keep in mind that JavaScript only promotes declarations, not initialization. Let’s take a simple example of variable promotion,

console.log(message); // Output: undefined
var message = 'The variable Has been hoisted';
Copy the code

The above code looks like the interpreter below,

var message;
console.log(message);
message = 'The variable Has been hoisted';
Copy the code

Cross tracks


26. What are classes in ES6?

In ES6, Javascript classes are primarily syntactic sugar for Javascript’s existing prototype-based inheritance.

For example, a prototype-based inheritance written in a function expression looks like this,

function Bike(model,color) {
    this.model = model;
    this.color = color;
}

Bike.prototype.getDetails = function() {
    return this.model + ' bike has' + this.color + ' color';
};
Copy the code

The ES6 class can be defined as an alternative

class Bike{
  constructor(color, model) {
    this.color= color;
    this.model= model;
  }

  getDetails() {
    return this.model + ' bike has' + this.color + ' color'; }}Copy the code

Cross tracks


27. What are closures?

A closure is a combination of a function and the lexical context in which it is declared. That is, it is an internal function that can access variables of an external or enclosing function. Closures have three chains of scope

  • Its own scope, where variables are defined between its braces
  • A variable of an external function
  • The global variable

Let’s take an example of the concept of closures,

function Welcome(name){
  var greetingInfo = function(message){
   console.log(message+' '+name);
  }
return greetingInfo;
}
var myFunction = Welcome('Haiyong');
myFunction('Welcome '); // Output: Welcome Haiyong
myFunction('Hello Mr.'); // Output: Hello Mr.Haiyong
Copy the code

According to the above code, the inner function (that is, greetingInfo) can access variables in the outer function scope (that is, Welcome) even after the outer function returns.

Cross tracks


28. What is modules?

Modules are small units of independent, reusable code and are the basis for many JavaScript design patterns. Most JavaScript modules export object literals, functions, or constructors

Cross tracks


29. Why do you need modules?

Here are the benefits of using modules in the javascript ecosystem

  • maintainability
  • reusability
  • The namespace

Cross tracks


30. What is scope in javascript?

Scope is the accessibility of variables, functions, and objects in certain parts of the runtime code. In other words, scope determines the visibility of variables and other resources in a code area.

Cross tracks


What is a Service Worker?

A Service Worker is basically a script (JavaScript file) that runs in the background, detached from the web page and providing functionality that doesn’t require web pages or user interaction. Some of the main features of the Service Worker are a rich offline experience (offline development of the first Web application), regular background synchronization, push notifications, intercepting and processing network requests, and programmatic management of the response cache.

Cross tracks


32. How to manipulate the DOM using the Service Worker?

The Service Worker cannot directly access the DOM. But it can communicate with the pages it controls by responding to messages sent through the postMessage interface, and those pages can manipulate the DOM.

Cross tracks


33. How do you reuse information when a Service Worker restarts?

The problem with the Service Worker is that it terminates when not in use and is restarted the next time it is needed, so you cannot rely on global state in the Service Worker onfetch and onMessage handlers. In this case, the service worker will have access to the IndexedDB API for retention and reuse upon restart.

Cross tracks


34. What is IndexedDB?

IndexedDB is a low-level API for clients to store large amounts of structured data, including files/BLOBs. This API uses indexes to enable high-performance searching of this data.

Cross tracks


35. What is Web Storage?

Web storage is an API that provides a mechanism by which browsers can store key/value pairs locally in the user’s browser in a more intuitive way than using cookies. Web storage provides two mechanisms for storing data on the client.

  • Local storage: It stores data from the current source and has no expiration date.
  • Session storage: Stores data for a session, which is lost when the browser TAB is closed.

Cross tracks


36. What is a post message?

Post Message is a way to enable cross-source communication between Window objects. (that is, between the page and the pop-up it generates, or between the page and the embedded iframe). In general, scripts on different pages are allowed to access each other if and only if the pages follow the same origin policy (that is, the pages share the same protocol, port number, and host).

Cross tracks


37. What is a Cookie?

You can learn more about cookies in this article:

Haiyong.blog.csdn.net/article/det…

A cookie is a piece of data stored on your computer for your browser to access. Cookies are saved as key/value pairs.

For example, you could create a cookie named username, as shown below,

document.cookie = "username=Haiyong";
Copy the code

Cross tracks


38. Why do you need cookies?

Cookies are used to remember information about a user’s personal information (such as a user name). It basically consists of two steps,

  • When a user visits a web page, personal information can be stored in cookies.
  • The cookie remembers the user profile the next time the user visits the page.

Cross tracks


39. What are the options in cookies?

The following options are available for cookies,

By default, cookies are deleted when the browser is closed, but you can change this behavior by setting the expiration date (UTC time).

document.cookie = "username=Haiyong; expires=Sat, 8 Jun 2019 12:00:00 UTC";
Copy the code

By default, the cookie belongs to the current page. However, you can use the path parameter to tell the browser where the cookie belongs.

document.cookie = "username=Haiyong; path=/services";
Copy the code

Cross tracks


40. How do you delete cookies?

document.cookie = "username=; expires=Fri, 07 Jun 2019 00:00:00 UTC; path=/;";
Copy the code

Note: You should define the cookie path option to ensure that you delete the correct cookie. Some browsers do not allow cookies to be deleted unless you specify a path parameter.

Cross tracks


41. What are the differences between cookies, local storage, and session storage?

Here are some differences between cookies, local storage, and session storage

Characteristics of the cookie The local store The session storage
Access on the client or server Server and client The client only The client only
Lifetime Use the Expires option Until the delete Until the TAB closes
SSL support To support the Does not support
Maximum data size 4KB 5 MB 5MB
Cross tracks

What are the main differences between localStorage and sessionStorage?

LocalStorage is the same as SessionStorage, but it retains data even when the browser is closed and reopened (that is, it has no expiration time), whereas in SessionStorage, data is cleared when the page session ends.

Cross tracks


43. How do you access web storage?

The Window object implements the WindowLocalStorage and WindowSessionStorage objects, They have localStorage(window.localstorage) and sessionStorage(window.sessionStorage) properties, respectively. These properties create an instance of a Storage object through which data items can be set, retrieved, and deleted for a specific domain and Storage type (session or local). For example, you can read and write locally stored objects, as shown below

localStorage.setItem('logo'.document.getElementById('logo').value);
localStorage.getItem('logo');
Copy the code

Cross tracks


44. What are the available methods of session storage?

Session storage provides the means to read, write, and clear session data

// Save data to sessionStorage
sessionStorage.setItem('key'.'value');

// Obtain the data saved from sessionStorage
let data = sessionStorage.getItem('key');

// Delete the saved data from sessionStorage
sessionStorage.removeItem('key');

// Delete all saved data from sessionStorage
sessionStorage.clear();
Copy the code

Cross tracks


45. What are stored events and their event handlers?

A StorageEvent is an event that is fired when a storage area is changed in the context of another document. The onStorage property is an EventHandler used to handle storage events. Syntax is as follows

 window.onstorage = functionRef;
Copy the code

Let’s take an example of an onStorage event handler that records a storage key and its value

window.onstorage = function(e) {
  console.log('The ' + e.key +
    ' key has been changed from ' + e.oldValue +
    ' to ' + e.newValue + '. ');
};
Copy the code

Cross tracks


46. Why do you need Web storage?

Web storage is more secure. Large amounts of data can be stored locally without affecting website performance. In addition, the information is never transmitted to the server. Therefore, this is a more recommended approach than cookies.

Cross tracks


47. How do you check Web storage browser support?

Before using network storage, you need to check your browser’s support for localStorage and sessionStorage.

if (typeof(Storage) ! = ="undefined") {
  / / localStorage sessionStorage code.
} else {
  // Sorry! No network storage support..
}
Copy the code

Cross tracks


48. How do you check Web Workers browser support?

Before using it, you need to check your browser’s support for Web Workers

if (typeof(Worker) ! = ="undefined") {
  // Web worker supported code.
} else {
  // Sorry! No Web Worker support.
}
Copy the code

Cross tracks


49. Take the example of a Web worker

You need to follow these steps to get started with counting examples using network workers

Create the Web Worker file: You need to write a script to increment the count. We’ll call it counter.js

let i = 0;

function timedCount() {
  i = i + 1;
  postMessage(i);
  setTimeout("timedCount()".500);
}

timedCount();
Copy the code

The postMessage() method is used here to send the message back to the HTML page

Create a Web Worker object: You can create a Web Worker object by checking browser support. Let’s name this file web_worker_example.js

if (typeof(w) == "undefined") {
  w = new Worker("counter.js");
}
Copy the code

We can receive messages from network workers

w.onmessage = function(event){
  document.getElementById("message").innerHTML = event.data;
};
Copy the code

Terminate the Web Worker: The Web Worker will continue to listen for messages (even after the external script completes) until it is terminated. You can terminate listening for messages using the Terminate () method.

w.terminate();
Copy the code

Reuse Web Worker: If you set the Worker variable to undefined, you can reuse code

w = undefined;
Copy the code

Cross tracks


50. What are web worker limits to DOM?

WebWorker does not have access to the following javascript objects because they are defined in an external file

  • Window object
  • The document object
  • Parent object

We know what we know. We go back to number 50. Siko siko


What is a promise?

A PROMISE is an object that may produce a single value at some point in the future with a resolved value or an unresolved cause (for example, a network error). It will be in one of three possible states: completed, rejected, or pending.

The syntax for creating a Promise is shown below,

 const promise = new Promise(function(resolve, reject) {
      // promise description
    })
Copy the code

The use of a promise is as follows,

const promise = new Promise(resolve= > {
  setTimeout(() = > {
    resolve("I'm a Promise!");
  }, 5000);
}, reject= >{}); promise.then(value= > console.log(value));
Copy the code

We know what we know. We go back to number 50. Siko siko


52. Why do YOU need promises?

Promises are used to handle asynchronous operations. They provide an alternative to callbacks by reducing callback hell and writing cleaner code.

We know what we know. We go back to number 50. Siko siko


53. What are the three states of promise?

Promise has three states:

  • Pending: This is the initial state of the Promise before the operation begins
  • Completed: This state indicates that the specified operation has been completed.
  • Rejected: This state indicates that the operation is not completed. In this case, an error value is thrown.

We know what we know. We go back to number 50. Siko siko


54. What is a callback function?

A callback function is a function passed as an argument to another function. This function is called inside an external function to complete an action.

Let’s take a simple example of how to use a callback function

function callbackFunction(name) {
  console.log('Hello ' + name);
}

function outerFunction(callback) {
  let name = prompt('Please enter your name.');
  callback(name);
}

outerFunction(callbackFunction);
Copy the code

We know what we know. We go back to number 50. Siko siko


55. Why do we need a callback?

Callbacks are required because javascript is an event-driven language. This means that the javascript will continue to execute while listening for other events, rather than waiting for a response. Let’s take an example of the first function call API call (simulated by setTimeout) and the next function logging message.

function firstFunction(){
  // Simulate code delay
  setTimeout( function(){
    console.log('First function called');
  }, 1000 );
}
function secondFunction(){
  console.log('Second function called');
}
firstFunction();
secondFunction();

Output
// Second function called
// First function called
Copy the code

As you can see from the output, the javascript did not wait for the response from the first function and executed the rest of the code block. Therefore, callbacks are used to ensure that some code does not execute until other code has finished executing.

We know what we know. We go back to number 50. Siko siko


56. What is callback hell?

Callback hell is an anti-pattern with multiple nested callbacks, which makes code difficult to read and debug when working with asynchronous logic. Back to what hell looks like below,

async1(function(){
    async2(function(){
        async3(function(){
            async4(function(){... }); }); }); });Copy the code

We know what we know. We go back to number 50. Siko siko


57. What is a server send event?

Server Send Events (SSE) is a server push technology that enables the browser to receive automatic updates from the server over AN HTTP connection without resorting to polling. These are one-way communication channels – events flow only from the server to the client. This has been used for CSDN blog updates, stock price updates, news feeds, and so on.

We know what we know. We go back to number 50. Siko siko


58. How do you receive event notifications from the server?

The EventSource object is used to receive event notifications from the server. For example, you can receive messages from the server, as shown below,

if(typeof(EventSource) ! = ="undefined") {
  var source = new EventSource("sse_generator.js");
  source.onmessage = function(event) {
    document.getElementById("output").innerHTML += event.data + "<br>";
  };
}
Copy the code

We know what we know. We go back to number 50. Siko siko


59. How do you check browser support for server send events?

You can perform browser support for events sent by the server before using, as shown below,

if(typeof(EventSource) ! = ="undefined") {
  // Support events sent by the server. Let's have some code here!
} else {
  // Events sent by the server are not supported
}
Copy the code

We know what we know. We go back to number 50. Siko siko


60. What events are available for events sent by the server?

The following is a list of events available for the server to send events

activity instructions
Open the It is used when opening a connection to the server
Leave a message Use this event when a message is received
error Occurs when an error occurs

We know what we know. We go back to number 50. Siko siko


61. What are promise’s main rules?

Promises must follow a specific set of rules,

  • A PROMISE is an object that provides a standard.then() method
  • Pending promises can be converted to completed or rejected states
  • Completed or rejected Promises are resolved and may not be converted to any other state.
  • Once the promise is solved, the value cannot be changed.

We know what we know. We go back to number 50. Siko siko


62. What is a callback within a callback?

You can nest one callback within another to execute the actions in turn. This is called a callback within a callback.

loadScript('/script1.js'.function(script) {
   console.log('first script is loaded');
  loadScript('/script2.js'.function(script) {
    console.log('second script is loaded');
    loadScript('/script3.js'.function(script) {
        console.log('third script is loaded');
      // After loading all scripts}); })});Copy the code

We know what we know. We go back to number 50. Siko siko


63. What is promise chaining?

The process of using promises to perform a series of asynchronous tasks one after another is called Promise chaining. Let’s take an example of calculating the promise chaining of the final result,

new Promise(function(resolve, reject) {
  setTimeout(() = > resolve(1), 1000);
}).then(function(result) {
  console.log(result); / / 1
  return result * 2;
}).then(function(result) {
  console.log(result); / / 2
  return result * 3;
}).then(function(result) {
  console.log(result); / / 6
  return result * 4;
});
Copy the code

In the above handler, the result is passed to the.then() handler chain via the following workflow,

1. The initial promise resolves in 1 second, 2. After.then calls the handler by recording result(1), then returns a promise with the value result * 2. 3. After that,.then passes the value to the next handler by recording result(2) and returns a promise that the result is * 3. Then returns a promise that the result is * 4 by recording the value passed to the last handler by result(6).

We know what we know. We go back to number 50. Siko siko


64. What is promise.all?

Promise.all is a Promise that takes a series of promises as input (iterable) and is resolved when all of them are resolved or when any of them is rejected. For example, the syntax for the promise.all method looks like this,

Promise.all([Promise1, Promise2, Promise3]) .then(result) => {   console.log(result) }) .catch(error= > console.log(`Error in promises ${error}`))
Copy the code

== Note == : Remember that the promised order (output) is maintained in the input order.

We know what we know. We go back to number 50. Siko siko


65. What is the purpose of the RACE method in promise?

The promise.race () method returns the Promise instance that was first resolved or rejected. Let’s take an example of the race() method, where PromisE2 is first resolved

var promise1 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 500.'one');
});
var promise2 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 100.'two');
});

Promise.race([promise1, promise2]).then(function(value) {
  console.log(value); // "two" promises will be fixed, but promise2 is faster
});
Copy the code

We know what we know. We go back to number 50. Siko siko


66. What is strict mode in javascript?

Strict mode is a new feature in ECMAScript 5 that allows you to place programs or functions in the context of “strict” operations. In this way, it prevents certain actions from being performed and more exceptions from being thrown. The literal expression “use strict”; Instructs the browser to use javascript code in strict mode.

We know what we know. We go back to number 50. Siko siko


67. Why is strict mode needed?

Strict mode is useful for writing “safe” JavaScript by notifying “error syntax” as actual errors. For example, it eliminates the accidental creation of global variables by throwing errors, and also raises errors when assigning to unwritable attributes, getter-only attributes, nonexistent attributes, nonexistent variables, or nonexistent variables. Existing objects.

We know what we know. We go back to number 50. Siko siko


68. How do you declare strict mode?

Strict mode is declared by adding “use strict”; To the beginning of the script or function. If declared at the beginning of the script, it has global scope.

"use strict";
x = 3.14; // This will result in an error because x is not declared
Copy the code

If you declare it inside a function, it has local scope

x = 3.14;       // This will not cause an error.
myFunction();

function myFunction() {
  "use strict";
  y = 3.14;   // This will cause an error
}
Copy the code

We know what we know. We go back to number 50. Siko siko


69. What is the purpose of the double exclamation mark?

Double exclamation mark or negative (!!) Make sure the result type is a Boolean. If it is false (such as 0, empty, undefined, etc.), it will be false, otherwise true.

For example, you can test the IE version with the following expression,

let isIE8 = false;
isIE8 = !! navigator.userAgent.match(/ / MSIE 8.0);
console.log(isIE8); // returns true or false
Copy the code

If you do not use this expression, it returns the original value.

console.log(navigator.userAgent.match(/ / MSIE 8.0));  // Return an array or null
Copy the code

We know what we know. We go back to number 50. Siko siko


70. What is the purpose of the delete operator?

The delete keyword is used to delete an attribute and its value.

var user= {name: "Haiyong".age:20};
delete user.age;

console.log(user); // {name: "Haiyong"}
Copy the code

We know what we know. We go back to number 50. Siko siko


71. What is the Typeof operator?

You can use the JavaScript typeof operator to find the typeof a JavaScript variable. It returns the type of a variable or expression.

typeof "Haiyong Abraham"     // Returns "string"
typeof (1 + 2)        // Returns "number"
Copy the code

We know what we know. We go back to number 50. Siko siko


72. What is an undefined attribute?

The undefined attribute indicates that a variable is not assigned, or not declared at all. The type of an undefined value is also undefined.

var user;    // Value undefined, type undefined
console.log(typeof(user)) / / undefined
Copy the code

Any variable can be cleared by setting the value to undefined.

user = undefined
Copy the code

We know what we know. We go back to number 50. Siko siko


73. What is a null value?

The value NULL indicates that any object values are intentionally missing. It is one of the original values of JavaScript. Null values are of type object. You can clear a variable by setting the value to NULL.

var user = null;
console.log(typeof(user)) //object
Copy the code

We know what we know. We go back to number 50. Siko siko


74. What’s the difference between null and undefined?

Here are the main differences between null and undefined,

null undefined
It is an assignment value, indicating that the variable does not point to any object. It is not an assigned value of a declared variable that has not yet been assigned.
Null is of type object The type of undefined is undefined
A null value is a primitive value that represents an empty, empty, or nonexistent reference. Undefined values are the original values used when the variable has not yet been assigned.
Indicates that the variable has no value Means there is no variable itself
Converted to zero when performing the original operation (0) Convert to NaN when performing the original operation

We know what we know. We go back to number 50. Siko siko

75. What is eval?

The eval() function evaluates JavaScript code represented as a string. A string can be a JavaScript expression, variable, statement, or sequence of statements.

console.log(eval('1 + 2')); / / 3
Copy the code

We know what we know. We go back to number 50. Siko siko


76. What’s the difference between Window and Document?

Here are the main differences between Window and Document,

Window Document
It is the root element in any web page It is a direct child of the Window object. This is also known as the Document Object Model (DOM)
By default, window objects are available implicitly in the page You can access it through window.document or document.
It has methods like alert(), confirm(), and attributes like document, location, and so on It provides methods getElementById, getElementByTagName, createElement, and so on

We know what we know. We go back to number 50. Siko siko


77. How do you access history in javascript?

The window.history object contains the browser’s history. You can use the back() and next() methods to load the previous and next urls in the history.

function goBack() {
  window.history.back()
}
function goForward() {
  window.history.forward()
}
Copy the code

== Note == : You can also access the history without a window prefix.

We know what we know. We go back to number 50. Siko siko


78. How do you check if caps lock is on?

The mouseEvent getModifierState() is used to return a Boolean value indicating whether the specified modifier key is activated. Modifiers such as CapsLock, ScrollLock, and NumLock are activated when clicked and disabled when clicked again.

Let’s take an input element for example to detect CapsLock on/off behavior,

<input type="password" onmousedown="enterInput(event)">

<p id="feedback"></p>

<script>
function enterInput(e) {
  var flag = e.getModifierState("CapsLock");
  if(flag) {
      document.getElementById("feedback").innerHTML = "CapsLock activated";

  } else {
      document.getElementById("feedback").innerHTML = "CapsLock not activated"; }}</script>
Copy the code

We know what we know. We go back to number 50. Siko siko


79. What is isNaN?

The isNaN() function is used to determine whether a value is an illegal Number (not-a-number). That is, if the value is NaN, the function returns true. Otherwise return false.

isNaN('Hello') //true
isNaN('100') //false
Copy the code

We know what we know. We go back to number 50. Siko siko


80. What’s the difference between an undeclared variable and an undefined variable?

Here are the main differences between undeclared and undefined variables,

undeclared undefined
These variables do not exist in the program and are not declared These variables are declared in the program but not assigned
If you try to read the value of an undeclared variable, you will encounter a runtime error If you try to read the value of an undefined variable, an undefined value is returned.
Cross tracks
We’re back on problem 50

81. What are global variables?

Global variables are those that are available for the entire length of the code and do not have any scope. The var keyword is used to declare a local variable, but if omitted, it becomes a global variable

msg = "Hello" // var is missing; it becomes a global variable
Copy the code

We know what we know. We go back to number 50. Siko siko


82. What’s wrong with global variables?

The problem with global variables is that local and global scope variable names conflict. Debugging and testing code that relies on global variables is also difficult.

We know what we know. We go back to number 50. Siko siko


83. What is a NaN attribute?

The NaN attribute is a global attribute that represents a “non-numeric” value. That is, it indicates that a value is not a legal number. NaN is rarely used in programs, but in rare cases can be used as a return value

Math.sqrt(-1)
parseInt("Hello")
Copy the code

We know what we know. We go back to number 50. Siko siko


84. What is the purpose of isFinite?

The isFinite() function is used to determine whether a number is a finite legal number. Return false if the value is +infinity, -infinity, or NaN (not a number), true otherwise.

isFinite(Infinity);  // false
isFinite(NaN);       // false
isFinite(-Infinity); // false
isFinite(100);         // true
Copy the code

We know what we know. We go back to number 50. Siko siko


85. What is an Event flow?

An event stream is the order in which events are received on a web page. When you click on an element nested in various other elements, before your click actually reaches its destination or target element, it must first trigger a click event for each of its parent elements, starting at the top of the global window object.

Events flow in one of two ways

  • From top to bottom (event capture)
  • From bottom to top (events bubble)

We know what we know. We go back to number 50. Siko siko


86. What is event bubbling?

Event bubbling is an event propagation in which events are first fired on the innermost target element, and then sequentially on the ancestors (parents) of the target element in the same nested hierarchy until they reach the outermost DOM element.

We know what we know. We go back to number 50. Siko siko


87. What is event capturing?

Event capture is an event propagation in which the event is first captured by the outermost element and then fired continuously on the descendants (children) of the target element in the same nested hierarchy until it reaches the innermost DOM element.

We know what we know. We go back to number 50. Siko siko


88. How do you submit forms using JavaScript?

You can submit the form using JavaScript, using document.form[0].submit(). Use the onSubmit event handler to submit all form input information

function submit() {
    document.form[0].submit();
}
Copy the code

We know what we know. We go back to number 50. Siko siko


89. How do you find operating system details?

The window.Navigator object contains information about the operating system details of the visitor’s browser. Some operating system properties are available under platform properties,

console.log(navigator.platform);
Copy the code

We know what we know. We go back to number 50. Siko siko


What is the difference between document Load and DOMContentLoaded events?

DOMContentLoaded Fires this event when the initial HTML document is fully loaded and parsed without waiting for the assets (stylesheets, images, and subframes) to complete loading. The load event is triggered when the entire page loads, including all dependent resources (stylesheets, images).

We know what we know. We go back to number 50. Siko siko


What is the difference between Native, Host, and User Objects?

  • Native objectsAn object that is part of the JavaScript language defined by the ECMAScript specification. For example, the core objects defined in the ECMAScript specification are String, Math, RegExp, Object, Function, etc.
  • Host objectsIs an object provided by the browser or the runtime environment (node). For example, Windows, XmlHttpRequest, DOM nodes, and so on are considered host objects.
  • User objectsIs an object defined in javascript code. For example, a user object created for profile information.

We know what we know. We go back to number 50. Siko siko


92. What tools or techniques are available for debugging JavaScript code?

You can use the following tools or techniques to debug javascript

  • Chrome Developer Tools
  • debugger statement
  • The older console.log statement

We know what we know. We go back to number 50. Siko siko


93. What are the pros and cons of promises versus callbacks?

Advantages:

1. It avoids unreadable callback hell 2. Easy to write sequential asynchronous code with.then() 3. Use promise.all () to easily write parallel asynchronous code 4. Fix some common problems with callbacks (too late, too early, multiple callbacks, and swallowing errors/exceptions)

Disadvantages:

2. If ES6 is not supported, you need to load a Polyfill

We know what we know. We go back to number 50. Siko siko


What is the difference between attribute and property?

Attributes are defined on the HTML tag, while Properties are defined on the DOM. For example, the following HTML element has two attributes types and values,

<input type="text" value="Name:">
Copy the code

You can retrieve the attribute values as follows,

const input = document.querySelector('input');
console.log(input.getAttribute('value')); // Good morning
console.log(input.value); // Good morning
Copy the code

After changing the value of the text field to “Good evening”, it becomes like

console.log(input.getAttribute('value')); // Good morning
console.log(input.value); // Good evening
Copy the code

We know what we know. We go back to number 50. Siko siko


95. What is a same-origin policy?

The same origin policy is a policy that prevents JavaScript from making requests across domain boundaries. The source is defined as a combination of THE URI scheme, host name, and port number. If enabled, this policy prevents malicious scripts on one page from using the Document Object Model (DOM) to gain access to sensitive data on another web page.

We know what we know. We go back to number 50. Siko siko


What is the purpose of void 0?

Void (0) is used to prevent page refresh. This will help eliminate unwanted side effects because it will return an undefined raw value. It is commonly used with href=”JavaScript:Void(0);” HTML document. Inside an element. That is, when you click a link, the browser loads a new page or refreshes the same page. But using this expression will prevent this behavior.

For example, the following link notifies the message without reloading the page

<a href="JavaScript:void(0);" onclick="alert('Well done! ')">Click Me! </a>Copy the code

We know what we know. We go back to number 50. Siko siko


97. Is JavaScript a compiled or interpreted language?

JavaScript is an interpreted language, not a compiled language. The interpreter in the browser reads the JavaScript code, interprets each line, and then runs it. Today, modern browsers use a technique called just-in-time (JIT) compilation, which compiles JavaScript into executable bytecode as it is about to run.

We know what we know. We go back to number 50. Siko siko


98. Is JavaScript a case-sensitive language?

Yes, JavaScript is a case sensitive language. Language keywords, variable, function, and object names, and any other identifiers must always be entered in consistent uppercase letters.

We know what we know. We go back to number 50. Siko siko


99. What is the relationship between Java and JavaScript?

No, they are completely different programming languages that have nothing to do with each other. But they are all object-oriented programming languages, and like many other languages, their basic functions (if, else, for, switch, break, continue, and so on) follow a similar syntax.

You can see the differences in my post:

Haiyong.blog.csdn.net/article/det…

We know what we know. We go back to number 50. Siko siko


100. What is an event?

An event is a “thing” that occurs on an HTML element. When using JavaScript in an HTML page, JavaScript can react to these events. Some examples of HTML events are,

  • The page has been loaded
  • The input field has changed
  • Button is clicked

Let’s describe the behavior of the button element’s click event,

 <! doctypehtml>
 <html>
  <head>
    <script>
      function greeting() {
        alert('Hello! Good morning');
      }
    </script>
  </head>
  <body>
    <button type="button" onclick="greeting()">Click me</button>
  </body>
 </html>
Copy the code

As we cross tracks we go back to problem 100


I’ve been writing technology blogs for a long time, mostly through CSDN, and this is one of my interview questions. Hope you like it!

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