This is the 28th 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?

101. Who created JavaScript?

JavaScript was created by Brendan Eich in 1995 during Netscape Communications. It was originally developed under the name Mocha, but the language was officially called LiveScript when it was first released in Netscape’s beta version. Sun and Netscape were working together at the time, and Sun trademarked “JavaScript,” and the two companies negotiated to change LiveScript to JavaScript as it is today.

Siphiwe go back to the top and we’re back on question 100


102. What is the preventDefault method for?

If the event is cancelable, the preventDefault() method cancels the event, which means the default action or behavior that belongs to the event will not happen. For example, blocking form submission when a submit button is clicked and opening a page URL when a hyperlink is clicked are common use cases.

 document.getElementById("link").addEventListener("click".function(event){
  event.preventDefault();
 });
Copy the code

== Note == : Remember that not all events can be cancelled.

Siphiwe go back to the top and we’re back on question 100


103. What is the use of the stopPropagation method?

The stopPropagation method is used to prevent events from bubbling up in the event chain. For example, the following nested div with stopPropagation method prevents default event propagation when a nested div(Div1) is clicked

 <p>Click DIV1 Element</p>
 <div onclick="secondFunc()">DIV 2
   <div onclick="firstFunc(event)">DIV 1</div>
 </div>

 <script>
 function firstFunc(event) {
   alert("DIV 1");
   event.stopPropagation();
 }

 function secondFunc() {
   alert("DIV 2");
 }
 </script>
Copy the code

Siphiwe go back to the top and we’re back on question 100


104. What steps does return false involve?

The return False statement in the event handler performs the following steps,

1. First it stops the default action or behavior of the browser. 2. It prevents events from propagating DOM 3. It stops the callback execution and returns immediately upon invocation.

Siphiwe go back to the top and we’re back on question 100


105. What is BOM(Browser Object Model)?

The Browser Object Model (BOM) allows JavaScript to “talk” to the browser. It consists of object navigators, history, screens, locations, and documents that are children of the window. The browser object model is not standardized and can vary from browser to browser.

Siphiwe go back to the top and we’re back on question 100


106. What is the use of setTimeout?

The setTimeout() method is used to call a function or evaluate an expression after a specified number of milliseconds. For example, let’s use the setTimeout method to record a message after 2 seconds,

 setTimeout(function(){ console.log("Good morning"); }, 2000);
Copy the code

Siphiwe go back to the top and we’re back on question 100


107. What does setInterval do?

The setInterval() method is used to call a function or evaluate an expression at a specified interval in milliseconds. For example, let’s use the setInterval method to record a message after 2 seconds,

 setInterval(function(){ console.log("Good morning"); }, 2000);
Copy the code

Siphiwe go back to the top and we’re back on question 100


108. Why is JavaScript considered single-threaded?

JavaScript is a single-threaded language. Because the language specification does not allow programmers to write code so that the interpreter can run parts of it in parallel across multiple threads or processes. Languages like Java, go, and C++ can make multithreaded and multiprocess programs.

Siphiwe go back to the top and we’re back on question 100


109. What is Event Delegation?

Event delegation is a technique for listening for events, where you can delegate a parent element as a listener for all events that occur within it.

For example, if you want to detect field changes within a particular form, you can use event delegation techniques,

 var form = document.querySelector('#registration-form');
 // Listen to the field changes in the form
 form.addEventListener('input'.function (event) {
 // Record the changed fields
 console.log(event.target);
 }, false);
Copy the code

Siphiwe go back to the top and we’re back on question 100


110. What is ECMAScript?

ECMAScript is the scripting language that forms the basis of JavaScript. ECMAScript is standardized by the ECMA International Standards Organization in the ECMA-262 and ECMA-402 specifications. The first version of ECMAScript was released in 1997.

Siphiwe go back to the top and we’re back on question 100


111. What is JSON?

JSON (JavaScript Object Notation) is a lightweight format for data interchange. It is based on a subset of the JavaScript language in which objects are built.

Siphiwe go back to the top and we’re back on question 100


112. What are the syntax rules for JSON?

Here is a list of JSON syntax rules

1. Data in name/value pairs 2. Data separated by commas 3. Square brackets hold arrays

Siphiwe go back to the top and we’re back on question 100


113. What is the purpose of JSON stringing?

When sending data to the Web server, the data must be in string format. You can do this by using the stringify() method to convert a JSON object into a string.

 var userJSON = {'name': 'Haiyong'.age: 31}
 var userString = JSON.stringify(user);
 console.log(userString); //"{"name":"Haiyong","age":31}"
Copy the code

Siphiwe go back to the top and we’re back on question 100


114. How do you parse JSON strings?

When you receive data from the Web server, it is always in string format. However, you can convert this string value into a javascript object using the parse() method.

 var userString = '{"name":"Haiyong","age":31}';
 var userJSON = JSON.parse(userString);
 console.log(userJSON);// {name: "Haiyong", age: 31}
Copy the code

Siphiwe go back to the top and we’re back on question 100


115. Why do I need JSON?

When data is exchanged between the browser and the server, it can only be text. Because JSON is only text, it can be sent and sent easily to and from the server, and can be used as a data format for any programming language.

Siphiwe go back to the top and we’re back on question 100


116. What is PWA?

Progressive Web Applications are mobile applications delivered over the Web and built using common Web technologies, including HTML, CSS, and JavaScript. These PWA are deployed to servers, accessed through urls, and indexed by search engines.

Siphiwe go back to the top and we’re back on question 100


117. What is the purpose of the clearTimeout method?

Javascript uses the clearTimeout() function to clear the timeout previously set by the setTimeout() function. That is, the return value of the setTimeout() function is stored in a variable and passed to the clearTimeout() function to clear the timer.

For example, the setTimeout method below is used to display the message after 3 seconds. This timeout can be cleared by using the clearTimeout() method.

 <script>
 var msg;
 function greeting() {
    alert('Good morning');
 }
 function start() {
   msg =setTimeout(greeting, 3000);

 }

 function stop() {
     clearTimeout(msg);
 }
 </script>
Copy the code

Siphiwe go back to the top and we’re back on question 100


118. What is the purpose of the clearInterval method?

Use the clearInterval() function in javascript to clear the interval set by the setInterval() function. That is, the return value returned by the setInterval() function is stored in a variable and passed to the clearInterval() function to clear the interval.

For example, the following setInterval method is used to display a message every 3 seconds. You can clear this interval with the clearInterval() method.

 <script>
 var msg;
 function greeting() {
    alert('Good morning');
 }
 function start() {
   msg = setInterval(greeting, 3000);

 }

 function stop() {
     clearInterval(msg);
 }
 </script>
Copy the code

Siphiwe go back to the top and we’re back on question 100


119. How do you redirect a new page in javascript?

In Vanilla javascript, you can use the properties of the LocationWindow object to redirect to a new page. Syntax is as follows,

 function redirect() {
    window.location.href = 'newPage.html';
 }
Copy the code

Siphiwe go back to the top and we’re back on question 100


120. How do you check if a string contains a substring?

There are three possible ways to check if a string contains a substring,

1. Use includes: String provided by the ES6. Prototype. Includes methods to test whether a String containing the substring

 var mainString = "hello", subString = "hell";
 mainString.includes(subString)
Copy the code

2. Use the indexOf: in ES5 or older environment, you can use the String. The prototype. IndexOfwhich returns the index of the substring. If the index value is not equal to -1, the substring exists in the main string.

 var mainString = "hello", subString = "hell"; mainString.indexOf(subString) ! = = -1
Copy the code

3. Use RegEx: The advanced solution is to use the regular expression test method (regexp.test), which allows testing against regular expressions

 var mainString = "hello", regex = /hell/;
 regex.test(mainString)
Copy the code

Siphiwe go back to the top and we’re back on question 100


121. How do you validate email in javascript?

You can use regular expressions to validate E-mail in javascript. It is recommended to authenticate on the server side rather than the client side. Because javascript can be disabled on the client side.

 function validateEmail(email) {
     var re = (([/ ^ ^ < > () \ [\] \ \,; : \ s + (\. @ "] [^ < > () \ [\] \ \,; : \ s @ "] +) *) | (" + ")) @ ((\ [[0-9] {1, 3} \. [0-9] {1, 3} \. [0-9] {1, 3} \. [0-9] {1, 3} \]) | ((( a-zA-Z\-0-9]+\.) +[a-zA-Z]{2,}))$/;
     return re.test(String(email).toLowerCase());
 }
Copy the code

The regular expression above accepts Unicode characters.

Siphiwe go back to the top and we’re back on question 100


122. How do you get the current URL using javascript?

You can use the window.location.href expression to get the current URL path, or you can use the same expression to update the URL. You can also use document.url for read-only purposes, but this solution is problematic in FF.

 console.log('location.href'.window.location.href); // Return the full URL
Copy the code

Siphiwe go back to the top and we’re back on question 100


123. What are the various URL properties of the location object?

The following Location object properties can be used to access the URL component of the page,

Protocol-url protocol 3. Host-url hostname and port 4. Hostname-url hostname 5 7. Search part of search-URL 8. Anchor part of hash-URL

Siphiwe go back to the top and we’re back on question 100


124. How do I get query string values in javascript?

You can use URLSearchParams to get query string values in javascript. Let’s look at an example of getting a client code value from a URL query string,

 const urlParams = new URLSearchParams(window.location.search);
 const clientCode = urlParams.get('clientCode');
Copy the code

Siphiwe go back to the top and we’re back on question 100


125. How do I check whether a key exists in an object?

You can check for the presence of a key in an object in three ways,

Use the IN operator: You can use the IN operator regardless of whether a key exists in the object

 "key" in obj
Copy the code

If you want to check if a key doesn’t exist, use parentheses,

! ("key" in obj)
Copy the code

Using the hasOwnProperty method: You can use hasOwnProperty to specifically test properties of an object instance (rather than inherited properties)

 obj.hasOwnProperty("key") // true
Copy the code

Use undefined comparisons: If a nonexistent property is accessed from an object, the result is undefined. Let’s compare the property to undefined to confirm the existence of the property.

 const user = {
   name: 'Haiyong'
 };

 console.log(user.name ! = =undefined);     // true
 console.log(user.nickName ! = =undefined); // false
Copy the code

Siphiwe go back to the top and we’re back on question 100


126. How do you loop or enumerate javascript objects?

You can use a for-in loop to loop through javascript objects. You can also ensure that the key you get is an actual property of the object, not from a prototype using the hasOwnProperty method.

 var object = {
     "k1": "value1"."k2": "value2"."k3": "value3"
 };

 for (var key in object) {
     if (object.hasOwnProperty(key)) {
         console.log(key + "- >" + object[key]); // k1 -> value1 ...}}Copy the code

Siphiwe go back to the top and we’re back on question 100


127. How do you test an empty object?

There are different solutions based on ECMAScript versions

Using object entries (ECMA 7+) : You can use object entry lengths and constructor types.

 Object.entries(obj).length === 0 && obj.constructor === Object // Since date object length is 0, you need to check constructor check as well
Copy the code

Using object Keys (ECMA 5+) : You can use object key lengths and constructor types.

 Object.keys(obj).length === 0 && obj.constructor === Object // Since date object length is 0, you need to check constructor check as well
Copy the code

Use for-In with hasOwnProperty (pre-ECMA 5) : You can use for-in loops with hasOwnProperty.

 function isEmpty(obj) {
   for(var prop in obj) {
     if(obj.hasOwnProperty(prop)) {
       return false; }}return JSON.stringify(obj) === JSON.stringify({});
 }
Copy the code

Siphiwe go back to the top and we’re back on question 100


128. What is a parameter object?

The Arguments object is an array-like object that can be accessed inside a function and contains the values of the arguments passed to the function. For example, let’s see how to use the Arguments object in the sum function,

 function sum() {
     var total = 0;
     for (var i = 0, len = arguments.length; i < len; ++i) {
         total += arguments[i];
     }
     return total;
 }

 sum(1.2.3) // returns 6
Copy the code

== Note that == : You cannot apply array methods on parameter objects. But you can convert to a regular array, as shown below.

 var argsArray = Array.prototype.slice.call(arguments);
Copy the code

Siphiwe go back to the top and we’re back on question 100


129. How do you capitalize the first letter of a string?

You can create a function that uses a series of string methods (such as charAt, toUpperCase, and Slice methods) to generate a string that starts with an uppercase letter.

 function capitalizeFirstLetter(string) {
     return string.charAt(0).toUpperCase() + string.slice(1);
 }
Copy the code

Siphiwe go back to the top and we’re back on question 100


130. What are the pros and cons of the for loop?

The for loop is a common iteration syntax in JavaScript. It cuts both ways

advantages

  • Suitable for all environments
  • You can use break and continue flow control statements

disadvantages

  • Too long
  • Imperative (Imperative programming)
  • You may face error after error

Siphiwe go back to the top and we’re back on question 100


131. How do you display the current date in javascript?

You can use new Date() to generate a new Date object that contains the current Date and time. For example, let’s display the current date as mm/ DD/YYYY

 var today = new Date(a);var dd = String(today.getDate()).padStart(2.'0');
 var mm = String(today.getMonth() + 1).padStart(2.'0'); //January is 0!
 var yyyy = today.getFullYear();

 today = mm + '/' + dd + '/' + yyyy;
 document.write(today);
Copy the code

Siphiwe go back to the top and we’re back on question 100


132. How do you compare two date objects?

You need to use the date.getTime() method to compare date values instead of comparing operators (==,! =, === and! == operator)

 var d1 = new Date(a);var d2 = new Date(d1);
 console.log(d1.getTime() === d2.getTime()); //True
 console.log(d1 === d2); // False
Copy the code

Siphiwe go back to the top and we’re back on question 100


133. How do you check if a string begins with another string?

You can use the ECMAScript 6 String. Prototype. StartsWith () method to check whether a String with another String. But not all browsers support it. Let’s look at an example to see how this is used,

 "Good morning".startsWith("Good"); // true
 "Good morning".startsWith("morning"); // false
Copy the code

Siphiwe go back to the top and we’re back on question 100


134. How do you trim strings in javascript?

JavaScript provides a trim method for string types to trim any whitespace that occurs at the beginning or end of the string.

 " Hello World ".trim(); //Hello World
Copy the code

If your browser (<IE9) does not support this method, you can use polyfill below.

 if (!String.prototype.trim) {
     (function() {
         Make sure we trim BOM and NBSP
         var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
         String.prototype.trim = function() {
             return this.replace(rtrim, ' '); }; }) (); }Copy the code

Siphiwe go back to the top and we’re back on question 100


135. How do you add a key-value pair to javascript?

There are two possible solutions for adding new properties to objects. Let’s explain these solutions with a simple object.

 var object = {
     key1: value1,
     key2: value2
 };
Copy the code

Use dot notation: This solution is useful when you know the name of the property

 object.key3 = "value3";
Copy the code

Use square bracket notation: This solution is useful when the name of the property is dynamically determined.

 obj["key3"] = "value3";
Copy the code

Siphiwe go back to the top and we’re back on question 100


136. ‘! Does the ‘symbol represent a special operator?

No, not special operators. But it’s a combination of two standard operators

Logical negation (!) Prefix decrement (–) First, the value is decrement by one, and then tests if it equals zero to determine true/false values.


137. How do you assign default values to variables?

You can use the logic or the operator | | in assignment expressions provide a default value. The syntax is as follows,

 var a = b || c;
Copy the code

According to the expression above, the variable ‘a’ will get the value of ‘c’ only if ‘b’ is false (if it is empty, false, undefined, 0, empty string, or NaN), otherwise ‘a’ will get the value of ‘b’.


138. How do you define a multi-line string?

You can use a “\” character followed by a line terminator to define a multi-line string literal.

 var str = "This is a \ very lengthy \ sentence!";
Copy the code

But if you have a space after the ” character, the code looks exactly the same, but it raises a SyntaxError.

Siphiwe go back to the top and we’re back on question 100


139. What is app Shell Model?

The Application Shell (or app Shell) architecture is a way to build progressive Web applications that can be reliably and instantaneously loaded onto a user’s screen, similar to what you see in native applications. This is useful for quickly bringing some initial HTML to the screen without a network.

Siphiwe go back to the top and we’re back on question 100


140. Can we define attributes for functions?

Yes, we can define properties for functions, because functions are also objects.

 fn = function(x) {
    // The function code is here
 }

 fn.name = "Haiyong";

 fn.profile = function(y) {
   // The config file code is here
 }
Copy the code

Siphiwe go back to the top and we’re back on question 100


141. What is the way to find the desired number of arguments for a function?

You can use the function.length syntax to find the number of parameters required by the function. Let’s take an example of a function of sum that computes the sum of numbers,

 function sum(num1, num2, num3, num4){
     return num1 + num2 + num3 + num4;
 }
 sum.length // 4 is the expected number of arguments.
Copy the code

Siphiwe go back to the top and we’re back on question 100


142. What is polyfill?

Polyfill is a piece of JS code that provides modern functionality on older browsers that don’t support it themselves. For example, the Silverlight plug-in Polyfill can be used to emulate the functionality of the HTML Canvas element on Microsoft Internet Explorer 7.

Siphiwe go back to the top and we’re back on question 100


143. What are break and continue statements?

The break statement is used to “break out” of the loop. That is, it breaks the loop and continues executing the code after the loop.

 for (i = 0; i < 10; i++) {
   if (i === 5) { break; }
   text += "Number: " + i + "<br>";
 }
Copy the code

The continue statement is used to “skip” an iteration of the loop. That is, if the specified condition occurs, it breaks one iteration (in the loop) and continues the next iteration in the loop.

 for (i = 0; i < 10; i++) {
     if (i === 5) { continue; }
     text += "Number: " + i + "<br>";
 }
Copy the code

Siphiwe go back to the top and we’re back on question 100


144. What is a JS tag?

The label statement allows us to name loops and blocks in JavaScript. We can then use these tags to reference the code later. For example, the labeled code below avoids printing numbers at the same time,

 var i, j;

 loop1:
 for (i = 0; i < 3; i++) {
    loop2:
    for (j = 0; j < 3; j++) {
       if (i === j) {
          continue loop1;
       }
       console.log('i = ' + i + ', j = '+ j); }}/ / output:
 // "i = 1, j = 0"
 // "i = 2, j = 0"
 // "i = 2, j = 1"
Copy the code

Siphiwe go back to the top and we’re back on question 100


145. What are the benefits of putting statements first?

It is recommended to keep all declarations at the top of each script or function. And the good thing about this is,

2. It provides a place to look up local variables 3. Easily avoid unwanted global variables. 4. It reduces the possibility of unwanted redeclarations

Siphiwe go back to the top and we’re back on question 100


146. What are the benefits of initializing variables?

It is recommended to initialize variables for the following benefits,

1. It provides cleaner code 2. It provides a place to initialize variables 3. Avoid undefined values in your code

Siphiwe go back to the top and we’re back on question 100


147. What are the recommendations for creating new objects?

It is recommended to avoid using new Object(). Instead, you can create an Object based on its type initialization value.

1. Assign {} instead of new Object() 2. Assign “” instead of new String() 3. Assign 0 instead of new Number() 4. Assign false instead of new Boolean() 5. Assign [] instead of new Array() 6. Assign /()/ instead of new RegExp() 7. Assign function (){} instead of new function ()

You can define them as examples,

 var v1 = {};
 var v2 = "";
 var v3 = 0;
 var v4 = false;
 var v5 = [];
 var v6 = / / ();
 var v7 = function(){};
Copy the code

Siphiwe go back to the top and we’re back on question 100


148. How do you define JSON arrays?

JSON arrays are written in square brackets and contain javascript objects. For example, the user’s JSON array looks like this,

 "users":[
   {"firstName":"Haiyong"."lastName":"Abrahm"},
   {"firstName":"Anna"."lastName":"Smith"},
   {"firstName":"Shane"."lastName":"Warn"}]Copy the code

Siphiwe go back to the top and we’re back on question 100


149. How do you generate random integers?

You can use math.random () and math.floor () to return random integers. For example, if you want to generate random integers between 1 and 10, the multiplication factor should be 10,

 Math.floor(Math.random() * 10) + 1;     // Return a random integer from 1 to 10
 Math.floor(Math.random() * 100) + 1;     // Return a random integer from 1 to 100
Copy the code

Note that == : math.random () returns a random number between 0 (inclusive) and 1 (inclusive)

Siphiwe go back to the top and we’re back on question 100


150. Can you write a random integer function to print integers in range?

Yes, you can create an appropriate random function to return a random number between min and Max (all inclusive)

 function randomInteger(min, max) {
   return Math.floor(Math.random() * (max - min + 1) ) + min;
 }
 randomInteger(1.100); // Return a random integer from 1 to 100
 randomInteger(1.1000); // Return a random integer from 1 to 1000
Copy the code

Siphiwe go back to the top to question 150


151. What is tree shaking?

Tree shaking is a form of eliminating dead code. This means that modules not used during the build process are not included in the package, so it relies on the static structure of ES2015 module syntax (i.e., imports and exports). Initially this has been promoted rollup by the ES2015 module bundler.

Siphiwe go back to the top to question 150


152. What is it that tree shaking takes?

Tree Shaking can significantly reduce the code size in any application. That is, the less code we send over the network, the better the performance of the application. For example, if we just wanted to create a “Hello World” application using the SPA framework, it would take about a few MEgabytes, but with treeShaking, it can be reduced to a few hundred KILobytes. Tree shaking is implemented in the Rollup and Webpack packers.

Siphiwe go back to the top to question 150


153. Is eval recommended?

Not recommended, it allows you to run arbitrary code that causes security problems. We know that the eval() function is used to run text as code. In most cases, it should not be necessary.

Siphiwe go back to the top to question 150


154. What is regular expression?

A regular expression is a sequence of characters that forms a search pattern. You can use this search mode to search for data in text. These can be used to perform all types of text search and text replacement operations. Now let’s look at the syntax,

 /pattern/modifiers;
Copy the code

For example, a case-insensitive regular expression or search pattern for a user name is,

 /Haiyong/i
Copy the code

Can’t see the conclusion: author of regular expression haiyong.blog.csdn.net/article/det…

Siphiwe go back to the top to question 150


155. What string methods are available in regular expressions?

Regular expressions have two string methods: search() and replace(). The search() method uses an expression to search for a match and returns the position of the match.

 var msg = "Hello Haiyong";
 var n = msg.search(/Haiyong/i); / / 6
Copy the code

The replace() method is used to return a modified string of replaced patterns.

 var msg = "Hello Haiyong";
 var n = msg.replace(/Haiyong/i."Buttler"); // Hello Buttler
Copy the code

Siphiwe go back to the top to question 150


156. What are modifiers in regular expressions?

Modifiers can be used to perform case-insensitive global searches. Let’s list some modifiers,

The modifier instructions
i (ignore) Performs case-insensitive matching
g (global) Perform a global match instead of stopping at the first match
m (more) Perform multi-line matching

Let’s take an example of a global modifier,

  var text = "Learn JS one by one";
  var pattern = /one/g;
  var result = text.match(pattern); // one,one
Copy the code

Siphiwe go back to the top to question 150


157. What is a regular expression pattern?

Regular expressions provide a set of patterns to match characters. Basically they fall into three types,

1. Parentheses: These are used to find a series of characters. For example, here are some use cases,

  • [ABC] : Used to find any character between parentheses (a,b,c)
  • [0-9] : Finds any number between parentheses
  • (a | b) : used to find to separate any options |

2. Metacharacters: These are characters with special meanings. For example, here are some use cases,

  • \ D: Used to find numbers
  • \ S: Used to find whitespace characters
  • \ B: Used to find matches at the beginning or end of words

Quantifiers: These are useful for defining quantities. For example, here are some use cases,

  • N + : Finds a match for any string containing at least one n
  • N * : A match for any string containing zero or more occurrences of n
  • n? : Used to find a match for any string containing zero or one n

Siphiwe go back to the top to question 150


158. What is a RegExp object?

The RegExp object is a regular expression object with predefined properties and methods. Let’s look at a simple use of the RegExp object,

 var regexp = new RegExp('\\w+');
 console.log(regexp);
 // Expected output: /\w+/
Copy the code

Siphiwe go back to the top to question 150


159. How do I search for patterns in strings?

You can use the test() method of a regular expression to search for patterns in a string and return true or false based on the result.

 var pattern = /you/;
 console.log(pattern.test("How are you?")); //true
Copy the code

Siphiwe go back to the top to question 150


160. What is the purpose of the EXEC method?

The purpose of the exec method is similar to that of the test method, but it performs a search for matches in the specified string and returns a result array, or null, instead of returning true/false.

 var pattern = /you/;
 console.log(pattern.exec("How are you?")); //["you", index: 8, output: "How are you?", groups: undefined]
Copy the code

Siphiwe go back to the top to question 150


161. How do I change the style of HTML elements?

You can use javascript to change the inline style or class name of an HTML element

Use style properties: You can modify inline styles using style properties

 document.getElementById("title").style.fontSize = "30px";
Copy the code

Use the ClassName attribute: It is easy to modify element classes using the ClassName attribute

  document.getElementById("title").className = "custom-title";
Copy the code

Siphiwe go back to the top to question 150


What is the result of 162.1+2+ 3?

The output will be 33. Since 1 and 2 are numerical values, the result for the first two digits will be the value 3. The next number is a string value, because the sum of the number 3 and the string value 3 is just a concatenation value 33.

Siphiwe go back to the top to question 150


163. What is a debugger statement?

Debugger statements invoke any available debugging functions, such as setting breakpoints. This statement is invalid if no debugging functionality is available.

For example, a debugger statement is inserted in the following function. Therefore, execution is paused at the debugger statement, just like a breakpoint in a script.

 function getProfile() {
 // The code is here
 debugger;
 // The code is here
 }
Copy the code

Siphiwe go back to the top to question 150


164. What is the purpose of debugging breakpoints?

Once the debugger statement is executed and the debugger window pops up, you can set breakpoints in your javascript code. At each breakpoint, the javascript stops execution and lets you check the javascript values. After checking the values, you can use the Play button to resume the execution of the code.

Siphiwe go back to the top to question 150


165. Can I use reserved words as identifiers?

No, you cannot use reserved words as variable, label, object, or function names. Let’s look at a simple example,

 var else = "hello"; // Uncaught SyntaxError: unexpected tag else
Copy the code

Siphiwe go back to the top to question 150


166. How do you detect mobile browsers?

You can use regular expressions that return true or false values depending on whether the user is using mobile browsing.

 window.mobilecheck = function() {
   var mobileCheck = false;
   (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|ki ndle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)? |phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|cra w|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc |fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01| 02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)| oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12| 21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1 )|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1 |si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0.4))) mobileCheck = true; })(navigator.userAgent||navigator.vendor||window.opera);
   return mobileCheck;
 };
Copy the code

Siphiwe go back to the top to question 150


167. How do I detect mobile browsers without regular expressions?

You can detect the mobile browser by simply running the device list and checking that the user agent matches anything. This is the alternative solution used by RegExp,

 function detectmob() {
  if( navigator.userAgent.match(/Android/i)
  || navigator.userAgent.match(/webOS/i)
  || navigator.userAgent.match(/iPhone/i)
  || navigator.userAgent.match(/iPad/i)
  || navigator.userAgent.match(/iPod/i)
  || navigator.userAgent.match(/BlackBerry/i)
  || navigator.userAgent.match(/Windows Phone/i)
  ){
     return true;
   }
  else {
     return false; }}Copy the code

Siphiwe go back to the top to question 150


168. How do you use JS to get the width and height of an image?

You can use Javascript to programmatically get the image and check the dimensions (width and height).

 var img = new Image();
 img.onload = function() {
   console.log(this.width + 'x' + this.height);
 }
 img.src = 'https://img-blog.csdnimg.cn/20210427214255127.png';
Copy the code

Siphiwe go back to the top to question 150


169. How do I synchronize HTTP requests?

The browser provides an XMLHttpRequest object that can be used to make synchronous HTTP requests from JavaScript

 function httpGet(theUrl)
 {
     var xmlHttpReq = new XMLHttpRequest();
     xmlHttpReq.open( "GET", theUrl, false ); // The synchronization request is false
     xmlHttpReq.send( null );
     return xmlHttpReq.responseText;
 }
Copy the code

Siphiwe go back to the top to question 150


170. How do I make an asynchronous HTTP request?

The browser provides an XMLHttpRequest object that can be used to make an asynchronous HTTP request from JavaScript by passing the third parameter to true.

 function httpGetAsync(theUrl, callback)
 {
     var xmlHttpReq = new XMLHttpRequest();
     xmlHttpReq.onreadystatechange = function() {
         if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
             callback(xmlHttpReq.responseText);
     }
     xmlHttp.open("GET", theUrl, true); // Asynchronous is true
     xmlHttp.send(null);
 }
Copy the code

Siphiwe go back to the top to question 150


171. How do you convert dates to another time zone in javascript?

You can convert dates in one time zone to another using the toLocaleString() method. For example, let’s convert the current date to the British English time zone, as shown below,

 console.log(event.toLocaleString('en-GB', { timeZone: 'UTC' })); / / 21/06/2021 08:00:00
Copy the code

Siphiwe go back to the top to question 150


172. What are the attributes used to get the window size?

You can find the size of a window using the innerWidth, innerHeight, clientWidth, and clientHeight properties of the window, document element, and document body object. Let’s use a combination of these properties to calculate the size of a window or document,

 var width = window.innerWidth
 || document.documentElement.clientWidth
 || document.body.clientWidth;

 var height = window.innerHeight
 || document.documentElement.clientHeight
 || document.body.clientHeight;
Copy the code

Siphiwe go back to the top to question 150


173. What are conditional operators in javascript?

The conditional (ternary) operator is the only JavaScript operator that takes three operands as a shortcut to an if statement.

 var isAuthenticated = false;
 console.log(isAuthenticated ? 'Hello, welcome' : 'Sorry, you are not authenticated');//Sorry, you are not authenticated
Copy the code

Siphiwe go back to the top to question 150


174. Can you apply chaining to conditional operators?

Yes, you can apply chaining to conditional operators, similar to if… else if … else if … The else chain. Syntax is as follows,

 function traceValue(someParam) {
     return condition1 ? value1
          : condition2 ? value2
          : condition3 ? value3
          : value4;
 }

 // The above conditional operators are equivalent to:

 function traceValue(someParam) {
     if (condition1) { return value1; }
     else if (condition2) { return value2; }
     else if (condition3) { return value3; }
     else { returnvalue4; }}Copy the code

Siphiwe go back to the top to question 150


175. What are the ways in which javascript is executed after a page is loaded?

You can execute javascript in many different ways after the page loads,

Window. Onload:

 window.onload = function.Copy the code

File loading:

 document.onload = function.Copy the code

Body loading:

 <body onload="script();">
Copy the code

Siphiwe go back to the top to question 150


176. What is the difference between Proto and Prototype?

The __proto__ object is the actual object used to parse methods and so on in the lookup chain. And when you create an object with new, prototype, the object used to build __proto__ is

 ( new Employee ).__proto__ === Employee.prototype;
 ( new Employee ).prototype === undefined;
Copy the code

Siphiwe go back to the top to question 150


177. For example, you’d better use a semicolon

It is recommended to use a semicolon after every statement in JavaScript. For example, in the following case, due to the absence of a semicolon, it will throw an error “.. Is not a function.

 // Define a function
 var fn = function () {
     / /...
 } // This line is missing a semicolon
 // Then execute some code in the closure
 (function () {
     / /...}) ();Copy the code

It will be interpreted as

 var fn = function () {
     / /...} (function () {
     / /...}) ();Copy the code

In this case, we pass the second function as an argument to the first function, and then try to call the result of the first function call as a function call. Therefore, the second function will be executed at run time due to “… Not function “error and fail.

Siphiwe go back to the top to question 150


178. What is the Freeze method?

The reeze() method is used to freeze objects. Frozen objects do not allow new attributes to be added to the object, prevent deletion, and prevent changes to the enumerability, configurability, or writability of existing attributes. That is, it returns the passed object and does not create a frozen copy.

const obj = {
   prop: 100
 };

 Object.freeze(obj);
 obj.prop = 200; Throw an error in strict mode

 console.log(obj.prop); / / 100
Copy the code

== Note that == : Raises TypeError if the argument passed is not an object.

Siphiwe go back to the top to question 150


179. What is the purpose of the Freeze method?

Here are the main benefits of using the freeze method,

1. It is used to freeze objects and arrays. 2. It is used to make objects immutable.

Siphiwe go back to the top to question 150


180. Why do I need to use freeze?

In the object-oriented paradigm, existing apis contain elements that are not intended to be extended, modified, or reused outside of the current context. Therefore, it is final as a key used in various languages.

Siphiwe go back to the top to question 150


181. How do you detect browser language preferences?

You can use the navigator object to detect browser language preferences, as shown below,

 var language = navigator.languages && navigator.languages[0] | |// Chrome / Firefox
                navigator.language ||   // All browsers
                navigator.userLanguage; // IE <= 10

 console.log(language);
Copy the code

Siphiwe go back to the top to question 150


182. How do I convert a string to title case using javascript?

Title case means that the first letter of each word is capitalized. You can use the following functions to convert strings to header case,

 function toTitleCase(str) {
     return str.replace(
         /\w\S*/g.function(txt) {
             return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } toTitleCase("good morning csdn"); // Good Morning Csdn
Copy the code

Siphiwe go back to the top to question 150


183. How do you detect disabled javascript on your page?

You can use this tag to detect whether javascript is disabled. Blocks of code inside are executed when JavaScript is disabled, and are often used to display alternate content when JavaScript generates the page.

 <script type="javascript">
     // Put the JS code here
 </script>
 <noscript>
     <a href="next_page.html? noJS=true">JavaScript is disabled in the page. Please click Next Page</a>
 </noscript>
Copy the code

Siphiwe go back to the top to question 150


184. What are the various operators supported by javascript?

Operators can manipulate (mathematically and logically) a value or operand. JavaScript supports the following operators:

  • Arithmetic operators: including + (addition), – (subtraction), * (multiplication), / (division), % (modulus), ++ (increment), and — (decrement)
  • Comparison operatorIncluding:= =(=),! =(not equal to),= = =(equal to type),>(greater than),> =(greater than or equal to),<(less than),< =(less than or equal to)
  • Logical operators: including && (logical and), | | (logical or),! (Logical non)
  • Assignment operators: including = (assignment operator), += (addition and assignment operator), — = (subtraction and assignment operator), *= (multiplication and assignment), /= (division and assignment), %= (module and assignment))
  • Ternary operator: It includes conditions (:?) operator
  • The typeof operator: Used to find the type of a variable. The syntax looks liketypeof variable

Siphiwe go back to the top to question 150


185. What are REST parameters?

The Rest argument is an improved way of handling function arguments that allows us to represent an unlimited number of arguments as arrays. Syntax is as follows,

 function f(a, b, ... theArgs) {
   // ...
 }
Copy the code

For example, let’s take a sum example to calculate the number of dynamic parameters,

 function total(... args){
 let sum = 0;
 for(let i of args){
 sum+=i;
 }
 return sum;
 }
 console.log(fun(1.2)); / / 3
 console.log(fun(1.2.3)); / / 6
 console.log(fun(1.2.3.4)); / / 13
 console.log(fun(1.2.3.4.5)); / / 15
Copy the code

== Note == : The Rest parameter is added in ES2015 or ES6

Siphiwe go back to the top to question 150


186. What happens if you don’t use the REST parameter as the last parameter?

The REST parameter should be the last parameter, because its job is to collect all the remaining parameters into an array. For example, if you define a function like the one below, it makes no sense and throws an error.

 function someFunc(A,... b,c){
 // Your code is here
 return;
 }
Copy the code

Siphiwe go back to the top to question 150


187. What are bitwise operators available in JavaScript?

Below is a list of bitwise logical operators used in JavaScript

1. Bitwise and (&) 2. Bitwise or (|) 3. The bitwise xor (^) 4. Bitwise non-(~) 5. left shift (<<) 6. symbol propagation right shift (>>) 7. Zero fill moved right (>>>)

Siphiwe go back to the top to question 150


188. What is a spread operator?

The expansion operator allows you to expand an iterable (array/object/string) into a single parameter/element. Let’s take an example of this behavior,

 function calculateSum(x, y, z) {
   return x + y + z;
 }

 const numbers = [1.2.3];

 console.log(calculateSum(... numbers));/ / 6
Copy the code

Siphiwe go back to the top to question 150


189. How do you determine if an object is frozen?

The object.isfrozen () method is used to determine whether an Object isFrozen. If all of the following conditions are true, the object is frozen,

1. If it cannot be extended. 2. If all of its properties are not configurable. 3. If all of its data attributes are unwritable. The usage is as follows,

 const object = {
    property: 'Welcome JS world'
 };
 Object.freeze(object);
 console.log(Object.isFrozen(object));
Copy the code

Siphiwe go back to the top to question 150


190. How do you determine if two values are the same or do not use objects?

The object.is () method determines whether two values are the same. For example, the use of different types of values is,

 Object.is('hello'.'hello');     // true
 Object.is(window.window);   // true
 Object.is([], []) // false
Copy the code

The two values are the same if one of the following conditions is true:

1. Both undefined 2. Both empty 3. Both true or false 4. Two strings of the same length have the same characters in the same order 5. Two identical objects (meaning two objects have the same reference) 6. Two numbers and two + zeros and two -zeros and both Nans are non-zero and neither is a NaN and both have the same value.

Siphiwe go back to the top to question 150


191. What is the purpose of the IS method using Object?

Some applications of Object’s IS method are as follows,

1. It is used to compare two strings. 2. It is used to compare two numbers. It is used to compare the polarity of two numbers. 4. It is used to compare two objects.

Siphiwe go back to the top to question 150


192. How do I copy properties from one object to another?

You can use the object.assign () method to copy values and attributes from one or more source objects to target objects. It returns the target object with properties and values copied from the target object. Syntax is as follows,

 Object.assign(target, ... sources)Copy the code

Let’s take a source and a target object,

 const target = { a: 1.b: 2 };
 const source = { b: 3.c: 4 };
 const returnedTarget = Object.assign(target, source);
 console.log(target); // { a: 1, b: 3, c: 4 }
 console.log(returnedTarget); // { a: 1, b: 3, c: 4 }
Copy the code

As observed in the code above, B has a common property() from source to target, so its value is overridden.

Siphiwe go back to the top to question 150


193. What are the applications of assignment methods?

Here are some of the main uses of the object.assign () method,

  • It is used to clone objects.
  • It is used to merge objects with the same properties.

Siphiwe go back to the top to question 150


194. What is a Proxy object?

Proxy objects are used to define custom behavior for basic operations, such as property lookups, assignments, enumerations, function calls, and so on. The syntax is as follows:

 var p = new Proxy(target, handler);
Copy the code

Let’s take a proxy object as an example,

 var handler = {
     get: function(obj, prop) {
         return prop in obj ?
             obj[prop] :
             100; }};var p = new Proxy({}, handler);
 p.a = 10;
 p.b = null;

 console.log(p.a, p.b); // 10, null
 console.log('c' in p, p.c); // false, 100
Copy the code

In the code above, it uses the GET handler to define the behavior of the agent when it performs operations on it

Siphiwe go back to the top to question 150


195. What is the purpose of the SEAL method?

The object.seal () method is used to seal an Object by preventing all existing properties from being unconfigurable from new properties being added to it and marking them. But the values of the current attributes can still be changed, as long as they are writable. Let’s look at the following example to learn more about the Seal() method

  const object = {
     property: 'Welcome JS world'
  };
  Object.seal(object);
  object.property = 'Welcome to object world';
  console.log(Object.isSealed(object)); // true
  delete object.property; // You cannot delete when sealed
  console.log(object.property); //Welcome to object world
Copy the code

Siphiwe go back to the top to question 150


196. What are the applications of the SEAL method?

Here are the main uses of the object.seal () method,

  • It is used to seal objects and arrays.
  • It is used to make objects immutable.

Siphiwe go back to the top to question 150


197. What is the difference between the Freeze and SEAL methods?

If the object.freeze () method is used to freeze an Object, its properties become immutable and cannot be changed, whereas if the object.seal () method is used to seal the Object, it is an Object that can be changed in its existing properties.

Siphiwe go back to the top to question 150


198. How do I determine whether an object is sealed?

The object.issealed () method is used to determine whether an Object isSealed. If all of the following conditions are true, the object is sealed

1. If it cannot be extended. 2. If all of its properties are not configurable. 3. If it is unmovable (but not necessarily unwritable). Let’s see it in action

 const object = {
 property: 'Hello, Good morning'
 };

 Object.seal(object); // Use the Seal() method to Seal the object

 console.log(Object.isSealed(object));      // Check whether the object is sealed
Copy the code

Siphiwe go back to the top to question 150


199. How do I get enumerable key-value pairs?

The object.entries () method returns an array of the given Object’s own enumerable string key-property pairs, in the same order as for… The in loop provides the same order. Let’s look at the functionality of the object.entries() method in an example,

 const object = {
   a: 'Good morning'.b: 100
 };

 for (let [key, value] of Object.entries(object)) {
   console.log(`${key}: ${value}`); // a: 'Good morning'
                                    // b: 100
 }
Copy the code

Note: Order is not guaranteed to be defined for objects.

Siphiwe go back to the top to question 150


What are the main differences between the object. values and object. entries methods?

The object.values () method behaves like the object.entries () method, but it returns an array of values instead of a [key,value] pair.

  const object = {
    a: 'Good morning'.b: 100
  };

  for (let value of Object.values(object)) {
    console.log(`${value}`); // 'Good morning'
                                 100
  }
Copy the code

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


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

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 πŸ“‘