JavaScript Interview Questions & Answers
JavaScript Interview Questions & Answers
No. Questions
1 What are the 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 is the difference between slice and splice
8 How do you compare Object and Map
9 What is the difference between == and === operators
10 What are lambda expressions or arrow functions
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 unary function
15 What is the currying function
16 What is a pure function
17 What is the purpose of the let keyword
18 What is the difference between let and var
19 What is the reason to choose the name let as a keyword
20 How do you redeclare variables in a switch block without an error
21 What is the Temporal Dead Zone
22 What is an IIFE (Immediately Invoked Function Expression)
23 How do you decode or encode a URL in JavaScript?
24 What is memoization
25 What is Hoisting
26 What are classes in ES6
27 What are closures
28 What are modules
29 Why do you need modules
30 What is scope in javascript
31 What is a service worker
32 How do you manipulate DOM using a service worker
33 How do you reuse information across service worker restarts
No. Questions
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 a Cookie
39 What are the options in a cookie
40 How do you delete a cookie
41 What are the differences between cookie, local storage and session storage
42 What is the main difference between localStorage and sessionStorage
43 How do you access web storage
44 What are the methods available on session storage
45 What is a storage event and its event handler
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 Give an example of a web worker
50 What are the restrictions of web workers on DOM
51 What is a promise
52 Why do you need a promise
53 What are the three states of promise
54 What is a callback function
55 Why do we need callbacks
56 What is a callback hell
57 What are server-sent events
58 How do you receive server-sent event notifications
59 How do you check browser support for server-sent events
60 What are the events available for server sent events
61 What are the main rules of promise
62 What is callback in 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 a strict mode in javascript
67 Why do you need strict mode
68 How do you declare strict mode
No. Questions
69 What is the purpose of double exclamation
70 What is the purpose of the delete operator
71 What is typeof operator
72 What is undefined property
73 What is null value
74 What is the difference between null and undefined
75 What is eval
76 What is the difference between window and document
77 How do you access history in javascript
78 How do you detect caps lock key turned on or not
79 What is isNaN
80 What are the differences between undeclared and undefined variables
81 What are global variables
82 What are the problems with global variables
83 What is NaN property
84 What is the purpose of isFinite function
85 What is an event flow
86 What is event bubbling
87 What is event capturing
88 How do you submit a form using JavaScript
89 How do you find operating system details
90 What is the difference between document load and DOMContentLoaded events
91 What is the difference between native, host and user objects
92 What are the tools or techniques used for debugging JavaScript code
93 What are the pros and cons of promises over callbacks
94 What is the difference between an attribute and a property
95 What is 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 any relation between Java and JavaScript
100 What are events
101 Who created javascript
102 What is the use of preventDefault method
103 What is the use of stopPropagation method
No. Questions
104 What are the steps involved in return false usage
105 What is BOM
106 What is the use of setTimeout
107 What is the use of setInterval
108 Why is JavaScript treated as Single threaded
109 What is an event delegation
110 What is ECMAScript
111 What is JSON
112 What are the syntax rules of JSON
113 What is the purpose JSON stringify
114 How do you parse JSON string
115 Why do you need JSON
116 What are PWAs
117 What is the purpose of clearTimeout method
118 What is the purpose of clearInterval method
119 How do you redirect new page in javascript
120 How do you check whether a string contains a substring
121 How do you validate an email in javascript
122 How do you get the current url with javascript
123 What are the various url properties of location object
124 How do get query string values in javascript
125 How do you check if a key exists in an object
126 How do you loop through or enumerate javascript object
127 How do you test for an empty object
128 What is an arguments object
129 How do you make first letter of the string in an uppercase
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 trim a string in javascript
135 How do you add a key value pair in javascript
136 Is the !– notation represents a special operator
137 How do you assign default values to variables
138 How do you define multiline strings
No. Questions
139 What is an app shell model
140 Can we define properties for functions
141 What is the way to find the number of parameters expected by a function
142 What is a polyfill
143 What are break and continue statements
144 What are js labels
145 What are the benefits of keeping declarations at the top
146 What are the benefits of initializing variables
147 What are the recommendations to create new object
148 How do you define JSON arrays
149 How do you generate random integers
150 Can you write a random integers function to print integers within a range
151 What is tree shaking
152 What is the need of tree shaking
153 Is it recommended to use eval
154 What is a Regular Expression
155 What are the string methods that accept Regular expression
156 What are modifiers in regular expression
157 What are regular expression patterns
158 What is a RegExp object
159 How do you search a string for a pattern
160 What is the purpose of exec method
161 How do you change the style of a HTML element
162 What would be the result of 1+2+‘3’
163 What is a debugger statement
164 What is the purpose of breakpoints in debugging
165 Can I use reserved words as identifiers
166 How do you detect a mobile browser
167 How do you detect a mobile browser without regexp
168 How do you get the image width and height using JS
169 How do you make synchronous HTTP request
170 How do you make asynchronous HTTP request
171 How do you convert date to another timezone in javascript
172 What are the properties used to get size of window
173 What is a conditional operator in javascript
No. Questions
174 Can you apply chaining on conditional operator
175 What are the ways to execute javascript after page load
176 What is the difference between proto and prototype
177 Can you give an example of when you really need a semicolon
178 What is a freeze method
179 What is the purpose of freeze method
180 Why do I need to use freeze method
181 How do you detect a browser language preference
182 How to convert string to title case with javascript
183 How do you detect javascript disabled in the page
184 What are various operators supported by javascript
185 What is a rest parameter
186 What happens if you do not use rest parameter as a last argument
187 What are the bitwise operators available in javascript
188 What is a spread operator
189 How do you determine whether object is frozen or not
190 How do you determine two values same or not using object
191 What is the purpose of using object is method
192 How do you copy properties from one object to other
193 What are the applications of assign method
194 What is a proxy object
195 What is the purpose of seal method
196 What are the applications of seal method
197 What are the differences between freeze and seal methods
198 How do you determine if an object is sealed or not
199 How do you get enumerable key and value pairs
200 What is the main difference between Object.values and Object.entries method
201 How can you get the list of keys of any object
202 How do you create an object with prototype
203 What is a WeakSet
204 What are the differences between WeakSet and Set
205 List down the collection of methods available on WeakSet
206 What is a WeakMap
207 What are the differences between WeakMap and Map
208 List down the collection of methods available on WeakMap
No. Questions
209 What is the purpose of uneval
210 How do you encode an URL
211 How do you decode an URL
212 How do you print the contents of web page
213 What is the difference between uneval and eval
214 What is an anonymous function
215 What is the precedence order between local and global variables
216 What are javascript accessors
217 How do you define property on Object constructor
218 What is the difference between get and defineProperty
219 What are the advantages of Getters and Setters
220 Can I add getters and setters using defineProperty method
221 What is the purpose of switch-case
222 What are the conventions to be followed for the usage of switch case
223 What are primitive data types
224 What are the different ways to access object properties
225 What are the function parameter rules
226 What is an error object
227 When you get a syntax error
228 What are the different error names from error object
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 works
236 What is an event loop
237 What is call stack
238 What is an event queue
239 What is a decorator
240 What are the properties of Intl object
241 What is an Unary operator
242 How do you sort elements in an array
243 What is the purpose of compareFunction while sorting arrays
No. Questions
244 How do you reversing an array
245 How do you find min and max value in an array
246 How do you find min and max values without Math functions
247 What is an empty statement and purpose of it
248 How do you get metadata of a module
249 What is a comma operator
250 What is the advantage of a comma operator
251 What is typescript
252 What are the differences between javascript and typescript
253 What are the advantages of typescript over javascript
254 What is an object initializer
255 What is a constructor method
256 What happens if you write constructor more than once in a class
257 How do you call the constructor of a parent class
258 How do you get the prototype of an object
259 What happens If I pass string type for getPrototype method
260 How do you set prototype of one object to another
261 How do you check whether an object can be extendable or not
262 How do you prevent an object to extend
263 What are the different ways to make an object non-extensible
264 How do you define multiple properties on an object
265 What is MEAN in javascript
266 What Is Obfuscation in javascript
267 Why do you need Obfuscation
268 What is Minification
269 What are the advantages of minification
270 What are the differences between Obfuscation and Encryption
271 What are the common tools used for minification
272 How do you perform form validation using javascript
273 How do you perform form validation without javascript
274 What are the DOM methods available for constraint validation
275 What are the available constraint validation DOM properties
276 What are the list of validity properties
277 Give an example usage of rangeOverflow property
278 Is enums feature available in javascript
No. Questions
279 What is an enum
280 How do you list all properties of an object
281 How do you get property descriptors of an object
282 What are the attributes provided by a property descriptor
283 How do you extend classes
284 How do I modify the url without reloading the page
285 How do you check whether an array includes a particular value or not
286 How do you compare scalar arrays
287 How to get the value from get parameters
288 How do you print numbers with commas as thousand separators
289 What is the difference between java and javascript
290 Does JavaScript supports namespace
291 How do you declare namespace
292 How do you invoke javascript code in an iframe from parent page
293 How do get the timezone offset from date
294 How do you load CSS and JS files dynamically
295 What are the different methods to find HTML elements in DOM
296 What is jQuery
297 What is V8 JavaScript engine
298 Why do we call javascript as dynamic language
299 What is a void operator
300 How to set the cursor to wait
301 How do you create an infinite loop
302 Why do you need to avoid with statement
303 What is the output of the following for loops
304 List down some of the features of ES6
305 What is ES6
306 Can I redeclare let and const variables
307 Does the const variable make the value immutable
308 What are default parameters
309 What are template literals
310 How do you write multi-line strings in template literals
311 What are nesting templates
312 What are tagged templates
313 What are raw strings
No. Questions
314 What is destructuring assignment
315 What are default values in destructuring assignment
316 How do you swap variables in destructuring assignment
317 What are enhanced object literals
318 What are dynamic imports
319 What are the use cases for dynamic imports
320 What are typed arrays
321 What are the advantages of module loaders
322 What is collation
323 What is for…of statement
324 What is the output of below spread operator array
325 Is PostMessage secure
326 What are the problems with postmessage target origin as wildcard
327 How do you avoid receiving postMessages from attackers
328 Can I avoid using postMessages completely
329 Is postMessages synchronous
330 What paradigm is Javascript
331 What is the difference between internal and external javascript
332 Is JavaScript faster than server side script
333 How do you get the status of a checkbox
334 What is the purpose of double tilde operator
335 How do you convert character to ASCII code
336 What is ArrayBuffer
337 What is the output of below string expression
338 What is the purpose of Error object
339 What is the purpose of EvalError object
340 What are the list of cases error thrown from non-strict mode to strict mode
341 Do all objects have prototypes
342 What is the difference between a parameter and an argument
343 What is the purpose of some method in arrays
344 How do you combine two or more arrays
345 What is the difference between Shallow and Deep copy
346 How do you create specific number of copies of a string
347 How do you return all matching strings against a regular expression
348 How do you trim a string at the beginning or ending
No. Questions
349 What is the output of below console statement with unary operator
350 Does javascript uses mixins
351 What is a thunk function
352 What are asynchronous thunks
353 What is the output of below function calls
354 How to remove all line breaks from a string
355 What is the difference between reflow and repaint
356 What happens with negating an array
357 What happens if we add two arrays
358 What is the output of prepend additive operator on falsy values
359 How do you create self string using special characters
360 How do you remove falsy values from an array
361 How do you get unique values of an array
362 What is destructuring aliases
363 How do you map the array values without using map method
364 How do you empty an array
365 How do you round numbers to certain decimals
366 What is the easiest way to convert an array to an object
367 How do you create an array with some data
368 What are the placeholders from console object
369 Is it possible to add CSS to console messages
370 What is the purpose of dir method of console object
371 Is it possible to debug HTML elements in console
372 How do you display data in a tabular format using console object
373 How do you verify that an argument is a Number or not
374 How do you create copy to clipboard button
375 What is the shortcut to get timestamp
376 How do you flattening multi dimensional arrays
377 What is the easiest multi condition checking
378 How do you capture browser back button
379 How do you disable right click in the web page
380 What are wrapper objects
381 What is AJAX
382 What are the different ways to deal with Asynchronous Code
383 How to cancel a fetch request
No. Questions
384 What is web speech API
385 What is minimum timeout throttling
386 How do you implement zero timeout in modern browsers
387 What are tasks in event loop
388 What is microtask
389 What are different event loops
390 What is the purpose of queueMicrotask
391 How do you use javascript libraries in typescript file
392 What are the differences between promises and observables
393 What is 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 type
398 What is babel
399 Is Node.js completely single threaded
400 What are the common use cases of observables
401 What is RxJS
402 What is the difference between Function constructor and function declaration
403 What is a Short circuit condition
404 What is the easiest way to resize an array
405 What is an observable
406 What is the difference between function and class declarations
407 What is an async function
408 How do you prevent promises swallowing errors
409 What is deno
410 How do you make an object iterable in javascript
411 What is a Proper Tail Call
412 How do you check an object is a promise or not
413 How to detect if a function is called as constructor
414 What are the differences between arguments object and rest parameter
415 What are the differences between spread operator and rest parameter
416 What are the different kinds of generators
417 What are the built-in iterables
418 What are the differences between for…of and for…in statements
No. Questions
419 How do you define instance and non-instance properties
420 What is the difference between isNaN and Number.isNaN?
421 How to invoke an IIFE without any extra brackets?
422 Is that possible to use expressions in switch cases?
423 What is the easiest way to ignore promise errors?
424 How do style the console output using CSS?
425 What is nullish coalescing operator (??)?
426 How do you group and nest console output?
427 What is the difference between dense and sparse arrays?
428 What are the different ways to create sparse arrays?
429 What is the difference between setTimeout, setImmediate and process.nextTick?
430 How do you reverse an array without modifying original array?
431 How do you create custom HTML element?
432 What is global execution context?
433 What is function execution context?
434 What is debouncing?
435 What is throttling?
436 What is optional chaining?
437 What is an environment record?
438 How to verify if a variable is an array?
439 What is pass by value and pass by reference?
440 What are the differences between primitives and non-primitives?
441 How do you create your own bind method using either call or apply method?
442 What are the differences between pure and impure functions?
443 What is referential transparency?
444 What are the possible side-effects in javascript?
445 What are compose and pipe functions?
446 What is module pattern?
447 What is Function Composition?
448 How to use await outside of async function prior to ES2022?
449 What is the purpose of the this keyword in JavaScript?
450 What are the uses of closures?
451 What are the phases of execution context?
452 What are the possible reasons for memory leaks?
453 What are the optimization techniques of V8 engine?
No. Questions
454 What are the examples of built-in higher order functions?
455 What are the benefits higher order functions?
456 How do you create polyfills for map, filter and reduce methods?
457 What is the difference between map and forEach functions?
458 Give an example of statements affected by automatic semicolon insertion?
459 What are the event phases of a browser?
460 What are the real world use cases of proxy?
461 What are hidden classes?
462 What is inline caching?
463 What are the different ways to execute external scripts?
464 What is Lexical Scope?
465 How to detect system dark mode in javascript?
466 What is the purpose of requestAnimationFrame method?
467 What is the difference between substring and substr methods?
468 How to find the number of parameters expected by a function?
469 What is globalThis, and what is the importance of it?
470 What are the array mutation methods?
471 What is module scope in JavaScript?
Object literal property values can be of any data type, including array,
function, and nested object.
Note: This is one of the easiest ways to create an object.
2. Object constructor:
The simplest way to create an empty object is using the Object constructor.
Currently this approach is not recommended.
var object = new Object();
The following code creates a new empty object whose prototype is null.
var object = Object.create(null);
4. Function constructor:
In this approach, create any function and apply the new operator to create
object instances.
function Person(name) {
this.name = name;
this.age = 21;
}
var object = new Person("Sudheer");
function func() {}
(OR)
// Create a new instance using function prototype.
var newInstance = Object.create(func.prototype)
The following code creates a new staff object by copying properties of his
working company and the car he owns.
const orgObject = { company: 'XYZ Corp'};
const carObject = { name: 'Toyota'};
const staff = Object.assign({}, orgObject, carObject);
8. Singleton pattern:
Bind: returns a new function, allowing you to pass any number of arguments
var employee1 = { firstName: "John", lastName: "Rodson" };
var employee2 = { firstName: "Jimmy", lastName: "Baily" };
Call and Apply are pretty much interchangeable. Both execute the current function
immediately. You need to decide whether it’s easier to send in an array or a comma
separated list of arguments. You can remember by treating Call is for comma
(separated list) and Apply is for Array.
Bind creates a new function that will have this set to the first parameter passed to
bind().
JSON.parse(text);
JSON.stringify(object);
Note: Slice method doesn’t mutate the original array but it returns the subset as a
new array.
Note: Splice method modifies the original array and returns the deleted array.
Slice Splice
Doesn’t modify the original Modifies the original array(mutable)
array(immutable)
Returns the subset of original array Returns the deleted elements as
array
Used to pick the elements from array Used to insert/delete elements
to/from array
0 == false // true
0 === false // false
1 == "1" // true
1 === "1" // false
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
NaN == NaN or NaN === NaN // false
[]==[] or []===[] //false, refer different objects in memory
{}=={} or {}==={} //false, refer different objects in memory
You can also call the function which you are passing to higher order function as
callback function.
The higher order function is helpful to write the modular and reusable code.
Let’s take an example to see the difference between pure and impure functions,
//Impure
let numberArray = [];
const impureAddNumber = (number) => numberArray.push(number);
//Pure
const pureAddNumber = (number) => (argNumberArray) =>
argNumberArray.concat([number]);
As per the above code snippets, the Push function is impure itself by altering the
array and returning a push number index independent of the parameter value,
whereas Concat on the other hand takes the array and concatenates it with the
other array producing a whole new array without side effects. Also, the return value
is a concatenation of the previous array.
Remember that Pure functions are important as they simplify unit testing without
any side effects and no need for dependency injection. They also avoid tight
coupling and make it harder to break your application by not having any side effects.
These principles are coming together with the Immutability concept of ES6: giving
preference to const over let usage.
17. What is the purpose of the let keyword
The let statement declares a block scope local variable. Hence the variables
defined with let keyword are limited in scope to the block, statement, or expression
on which it is used. Whereas variables declared with the var keyword used to define
a variable globally, or locally to an entire function regardless of block scope.
var let
It has been available from the beginning of Introduced as part of ES6
JavaScript
It has function scope It has block scope
Variable declaration will be hoisted, Hoisted but not initialized
initialized as undefined
It is possible to re-declare the variable in It is not possible to re-declare
the same scope the variable
Let’s take an example to see the difference,
function userDetails(username) {
if (username) {
console.log(salary); // undefined due to hoisting
console.log(age); // ReferenceError: Cannot access 'age' before
initialization
let age = 30;
var salary = 10000;
}
console.log(salary); //10000 (accessible due to function scope)
console.log(age); //error: age is not defined(due to block scope)
}
userDetails("John");
19. What is the reason to choose the name let as a keyword
let is a mathematical statement that was adopted by early programming languages
like Scheme and Basic. It has been borrowed from dozens of other languages that
use let already as a traditional keyword as close to var as possible.
case 1:
let name; // SyntaxError for redeclaration.
break;
}
To avoid this error, you can create a nested block inside a case clause and create a
new block scoped lexical environment.
let counter = 1;
switch (x) {
case 0: {
let name;
break;
}
case 1: {
let name; // No SyntaxError for redeclaration.
break;
}
}
The primary reason to use an IIFE is to obtain data privacy because any variables
declared within the IIFE cannot be accessed by the outside world. i.e, If you try to
access variables from the IIFE then it throws an error as below,
(function () {
var message = "IIFE";
console.log(message);
})();
console.log(message); //Error: message is not defined
function message(name) {
console.log(name);
}
This hoisting makes functions to be safely used in code before they are declared.
Bike.prototype.getDetails = function () {
return this.model + " bike has" + this.color + " color";
};
getDetails() {
return this.model + " bike has" + this.color + " color";
}
}
As per the above code, the inner function(i.e, greetingInfo) has access to the
variables in the outer function scope(i.e, Welcome) even after the outer function has
returned.
Screenshot
38. Why do you need a Cookie
Cookies are used to remember information about the user profile(such as
username). It basically involves two steps,
1. When a user visits a web page, the user profile can be stored in a cookie.
2. Next time the user visits the page, the cookie remembers the user profile.
1. By default, the cookie is deleted when the browser is closed but you can
change this behavior by setting expiry date (in UTC time).
document.cookie = "username=John; expires=Sat, 8 Jun 2019 12:00:00
UTC";
1. By default, the cookie belongs to a current page. But you can tell the browser
what path the cookie belongs to using a path parameter.
document.cookie = "username=John; path=/services";
Note: You should define the cookie path option to ensure that you delete the right
cookie. Some browsers doesn’t allow to delete a cookie unless you specify a path
parameter.
41. What are the differences between cookie, local storage and session storage
Below are some of the differences between cookie, local storage and session storage,
Local Session
Feature Cookie storage storage
Accessed on Both server-side & client-side client-side
client or client-side. The set- only only
server side cookie HTTP
response header is
used by server
inorder to send it to
user.
Local Session
Feature Cookie storage storage
Expiry Manually configured Forever until tab is
using Expires option until closed
deleted
SSL support Supported Not Not
supported supported
Maximum 4KB 5 MB 5MB
data size
Accessible Any window Any Same tab
from window
Sent with Yes No No
requests
localStorage.setItem("logo", document.getElementById("logo").value);
localStorage.getItem("logo");
window.onstorage = functionRef;
Let’s take the example usage of onstorage event handler which logs the storage key
and it’s values
window.onstorage = function (e) {
console.log(
"The " +
e.key +
" key has been changed from " +
e.oldValue +
" to " +
e.newValue +
"."
);
};
1. Create a Web Worker File: You need to write a script to increment the count
value. Let’s name it as counter.js
let i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()", 500);
}
timedCount();
Here postMessage() method is used to post a message back to the HTML page
1. Create a Web Worker Object: You can create a web worker object by
checking for browser support. Let’s name this file as web_worker_example.js
if (typeof w == "undefined") {
w = new Worker("counter.js");
}
1. Terminate a Web Worker: Web workers will continue to listen for messages
(even after the external script is finished) until it is terminated. You can use
the terminate() method to terminate listening to the messages.
w.terminate();
1. Reuse the Web Worker: If you set the worker variable to undefined you can
reuse the code
w = undefined;
50. What are the restrictions of web workers on DOM
WebWorkers don’t have access to below javascript objects since they are defined in
an external files
1. Window object
2. Document object
3. Parent object
Screenshot
function outerFunction(callback) {
let name = prompt("Please enter your name.");
callback(name);
}
outerFunction(callbackFunction);
// Output:
// Second function called
// First function called
As observed from the output, javascript didn’t wait for the response of the first
function and the remaining code block got executed. So callbacks are used in a way
to make sure that certain code doesn’t execute until the other code finishes
execution.
async1(function(){
async2(function(){
async3(function(){
async4(function(){
....
});
});
});
});
60. What are the events available for server sent events
Below are the list of events available for server sent events | Event | Description |
|—- | ——— | onopen | It is used when a connection to the server is opened | |
onmessage | This event is used when a message is received | | onerror | It happens
when an error occurs|
In the above handlers, the result is passed to the chain of .then() handlers with the
below work flow,
Note: Remember that the order of the promises(output the result) is maintained as
per input order.
function myFunction() {
"use strict";
y = 3.14; // This will cause an error
}
69. What is the purpose of double exclamation
The double exclamation or negation(!!) ensures the resulting type is a boolean. If it
was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, it will be true. For
example, you can test IE version using this expression as below,
If you don’t use this expression then it returns the original value.
console.log(navigator.userAgent.match(/MSIE 8.0/)); // returns either
an Array or null
Null Undefined
It is an assignment value which It is not an assignment value where a
indicates that variable points to no variable has been declared but has not
object. yet been assigned a value.
Type of null is object Type of undefined is undefined
The null value is a primitive value The undefined value is a primitive
that represents the null, empty, or value used when a variable has not
non-existent reference. been assigned a value.
Indicates the absence of a value for Indicates absence of variable itself
a variable
Converted to zero (0) while Converted to NaN while performing
performing primitive operations primitive operations
Window Document
It is the root level element in It is the direct child of the window object.
any web page This is also known as Document Object
Model (DOM)
By default window object is You can access it via window.document or
available implicitly in the page document.
It has methods like alert(), It provides methods like getElementById,
confirm() and properties like getElementsByTagName, createElement etc
Window Document
document, location
Let’s take an input element to detect the CapsLock on/off behavior with an example:
<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>
79. What is isNaN
The isNaN() function is used to determine whether a value is an illegal number
(Not-a-Number) or not. i.e, This function returns true if the value equates to NaN.
Otherwise it returns false.
isNaN("Hello"); //true
isNaN("100"); //false
80. What are the differences between undeclared and undefined variables
Below are the major differences between undeclared(not defined) and undefined
variables,
undeclared undefined
These variables do not exist in a These variables declared in the
program and are not declared program but have not assigned any
value
If you try to read the value of an If you try to read the value of an
undeclared variable, then a runtime undefined variable, an undefined
error is encountered value is returned.
```javascript
b; // Throws runtime error like „Uncaught ReferenceError: b is not defined“ ``` This
can be confusing, because it says „not defined“ instead of „not declared“ (Chrome)
Math.sqrt(-1);
parseInt("Hello");
isFinite(100); // true
<script>
const parent = document.querySelector("div");
const child = document.querySelector(".child");
parent.addEventListener("click",
function () {
console.log("Parent");
}
);
child.addEventListener("click", function () {
console.log("Child");
});
</script>
// Child
// Parent
<script>
const parent = document.querySelector("div");
const child = document.querySelector(".child");
parent.addEventListener("click",
function () {
console.log("Parent");
},
true
);
child.addEventListener("click", function () {
console.log("Child");
});
</script>
// Parent
// Child
88. How do you submit a form using JavaScript
You can submit a form using document.forms[0].submit(). All the form input’s
information is submitted using onsubmit event handler
function submit() {
document.forms[0].submit();
}
console.log(navigator.platform);
90. What is the difference between document load and DOMContentLoaded events
The DOMContentLoaded event is fired when the initial HTML document has been
completely loaded and parsed, without waiting for assets(stylesheets, images, and
subframes) to finish loading. Whereas The load event is fired when the whole page
has loaded, including all dependent resources(stylesheets, images).
91. What is the difference between native, host and user objects
Native objects are objects that are part of the JavaScript language defined by the
ECMAScript specification. For example, String, Math, RegExp, Object, Function etc
core objects defined in the ECMAScript spec. Host objects are objects provided by
the browser or runtime environment (Node).
For example, window, XmlHttpRequest, DOM nodes etc are considered as host
objects. User objects are objects defined in the javascript code. For example, User
objects created for profile information.
92. What are the tools or techniques used for debugging JavaScript code
You can use below tools or techniques for debugging javascript
1. Chrome Devtools
2. debugger statement
3. Good old console.log statement
93. What are the pros and cons of promises over callbacks
Below are the list of pros and cons of promises over callbacks,
Pros:
You can retrieve the attribute value as below, for example after typing “Good
morning” into the input field:
const input = document.querySelector("input");
console.log(input.getAttribute("value")); // Good morning
console.log(input.value); // Good morning
And after you change the value of the text field to “Good evening”, it becomes like
console.log(input.getAttribute("value")); // Good evening
console.log(input.value); // Good evening
<script>
function firstFunc(event) {
alert("DIV 1");
event.stopPropagation();
}
function secondFunc() {
alert("DIV 2");
}
</script>
For example, if you wanted to detect field changes inside a specific form, you can use
event delegation technique,
var form = document.querySelector("#registration-form");
function stop() {
clearTimeout(msg);
}
</script>
function stop() {
clearInterval(msg);
}
</script>
/^(([^<>()\[\]\\.,;:\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());
}
"key" in obj;
and If you want to check if a key doesn’t exist, remember to use parenthesis,
!("key" in obj);
var object = {
k1: "value1",
k2: "value2",
k3: "value3",
};
1. Using Object entries(ECMA 7+): You can use object entries length along
with constructor type.
Object.entries(obj).length === 0 && obj.constructor === Object; //
Since date object length is 0, you need to check constructor check as
well
2. Using Object keys(ECMA 5+): You can use object keys length along with
constructor type.
Object.keys(obj).length === 0 && obj.constructor === Object; // Since
date object length is 0, you need to check constructor check as well
3. Using for-in with hasOwnProperty(Pre-ECMA 5): You can use a for-in loop
along with hasOwnProperty.
function isEmpty(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return JSON.stringify(obj) === JSON.stringify({});
}
Note: You can’t apply array methods on arguments object. But you can convert into
a regular array as below.
var argsArray = Array.prototype.slice.call(arguments);
Pros
1. Works on every environment
2. You can use break and continue flow control statements
Cons
3. Too verbose
4. Imperative
5. You might face off-by-one errors.
If your browser(<IE9) doesn’t support this method then you can use below polyfill.
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, "");
};
})();
}
1. Using dot notation: This solution is useful when you know the name of the
property
object.key3 = "value3";
2. Using square bracket notation: This solution is useful when the name of
the property is dynamically determined or the key’s name is non-JS like
“user-name”
obj["key3"] = "value3";
As per the above expression, variable ‘a ’will get the value of ’c’ only if ‘b’ is falsy (if
is null, false, undefined, 0, empty string, or NaN), otherwise ‘a’ will get the value of
‘b’.
138. How do you define multiline strings
You can define multiline string literals using the ‘’ character followed by line
terminator(’').
var str =
"This is a \n\ very lengthy \n\ sentence!";
console.log(str);
But if you have a space after the ‘’ character, there will be indentation
inconsistencies.
fn.name = "John";
141. What is the way to find the number of parameters expected by a function
You can use function.length syntax to find the number of parameters expected by
a function. Let’s take an example of sum function to calculate the sum of numbers,
function sum(num1, num2, num3, num4) {
return num1 + num2 + num3 + num4;
}
sum.length; // 4 is the number of parameters expected.
The continue statement is used to “jump over” one iteration in the loop. i.e, It breaks
one iteration (in the loop), if a specified condition occurs, and continues with the
next iteration in the loop.
for (i = 0; i < 10; i++) {
if (i === 5) {
continue;
}
text += "Number: " + i + "<br>";
}
150. Can you write a random integers function to print integers within a range
Yes, you can create a proper random function to return a random number between
min and max (both included)
function randomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomInteger(1, 100); // returns a random integer from 1 to 100
randomInteger(1, 1000); // returns a random integer from 1 to 1000
/pattern/modifiers;
/John/i;
155. What are the string methods that accept Regular expression
There are six string methods: search(), replace(), replaceAll(), match(), matchAll(),
and split().
The search() method uses an expression to search for a match, and returns the
position of the match.
var msg = "Hello John";
var n = msg.search(/John/i); // 6
The replace() and replaceAll() methods are used to return a modified string where
the pattern is replaced.
var msg = "ball bat";
var n1 = msg.replace(/b/i, "c"); // call bat
var n2 = msg.replaceAll(/b/i, "c"); // call cat
The match() and matchAll() methods are used to return the matches when matching
a string against a regular expression.
var msg = "Hello John";
var n1 = msg.match(/[A-Z]/g); // ["H", "J"]
var n2 = msg.matchAll(/[A-Z]/g); // this returns an iterator
The split() method is used to split a string into an array of substrings, and returns
the new array.
var msg = "Hello John";
var n = msg.split(/\s/); // ["Hello", "John"]
Modifier Description
i Perform case-insensitive matching
g Perform a global match rather than stops at first match
m Perform multiline matching
Let’s take an example of global modifier,
1. Using style property: You can modify inline style using style property
document.getElementById("title").style.fontSize = "30px";
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;
}
}
168. How do you get the image width and height using JS
You can programmatically get the image and check the dimensions(width and
height) using Javascript.
var img = new Image();
img.onload = function () {
console.log(this.width + "x" + this.height);
};
img.src = "http://www.google.com/intl/en_ALL/images/logo.gif";
var height =
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
function traceValue(someParam) {
if (condition1) {
return value1;
} else if (condition2) {
return value2;
} else if (condition3) {
return value3;
} else {
return value4;
}
}
175. What are the ways to execute javascript after page load
You can execute javascript after page load in many different ways,
1. window.onload:
window.onload = function ...
2. document.onload:
document.onload = function ...
3. body onload:
<body onload="script();">
176. What is the difference between proto and prototype
The __proto__ object is the actual object that is used in the lookup chain to resolve
methods, etc. Whereas prototype is the object that is used to build __proto__ when
you create an object with new.
new Employee().__proto__ === Employee.prototype;
new Employee().prototype === undefined;
177. Can you give an example of when you really need a semicolon
It is recommended to use semicolons after every statement in JavaScript. For
example, in the below case it throws an error “.. is not a function” at runtime due to
missing semicolon.
// define a function
var fn = (function () {
//...
})(
// semicolon missing at this line
Object.freeze(obj);
obj.prop = 200; // Throws an error in strict mode
console.log(obj.prop); //100
Remember freezing is only applied to the top-level properties in objects but not for
nested objects. For example, let’s try to freeze user object which has employment
details as nested object and observe that details have been changed.
const user = {
name: "John",
employment: {
department: "IT",
},
};
Object.freeze(user);
user.employment.department = "HR";
console.log(language);
console.log(calculateSum(...numbers)); // 6
1. If it is not extensible.
2. If all of its properties are non-configurable.
3. If all its data properties are non-writable. The usage is going to be as follows,
const object = {
property: "Welcome JS world",
};
Object.freeze(object);
console.log(Object.isFrozen(object));
190. How do you determine two values same or not using object
The Object.is() method determines whether two values are the same value. For
example, the usage with different types of values would be,
Object.is("hello", "hello"); // true
Object.is(window, window); // true
Object.is([], []); // false
Let’s take example with one source and one 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 }
As observed in the above code, there is a common property(b) from source to target
so it’s value has been overwritten.
A proxy is created with two parameters: a target object which you want to proxy
and a handler object which contains methods to intercept fundamental operations.
The syntax would be as follows,
Let’s take a look at below examples of proxy object and how the get method which
customize the lookup behavior,
//Example1:
const person = {
name: 'Sudheer Jonna',
age: 35
};
const handler = {
get(target, prop) {
if (prop === 'name') {
return 'Mr. ' + target[prop];
}
return target[prop];
}
};
var handler1 = {
get: function (obj, prop) {
return prop in obj ? obj[prop] : 100;
},
};
In the above code, it uses get handler which define the behavior of the proxy when
an operation is performed on it. These proxies are mainly used for some of the
below cross-cutting concerns.
1. Logging
2. Authentication or Authorization
3. Data binding and observables
4. Function parameter validation
Note: This is a new feature in ES6.
197. What are the differences between freeze and seal methods
If an object is frozen using the Object.freeze() method then its properties become
immutable and no changes can be made in them whereas if an object is sealed using
the Object.seal() method then the changes can be made in the existing properties of
the object.
201. How can you get the list of keys of any object
You can use the Object.keys() method which is used to return an array of a given
object’s own property names, in the same order as we get with a normal loop. For
example, you can get the keys of a user object,
const user = {
name: "John",
gender: "male",
age: 40,
};
new WeakSet([iterable]);
new WeakMap([iterable]);
1. set(key, value): Sets the value for the key in the WeakMap object. Returns the
WeakMap object.
2. delete(key): Removes any value associated to the key.
3. has(key): Returns a Boolean asserting whether a value has been associated
to the key in the WeakMap object or not.
4. get(key): Returns the value associated to the key, or undefined if there is
none. Let’s see the functionality of all the above methods in an example,
var weakMapObject = new WeakMap();
var firstObject = {};
var secondObject = {};
// set(key, value)
weakMapObject.set(firstObject, "John");
weakMapObject.set(secondObject, 100);
console.log(weakMapObject.has(firstObject)); //true
console.log(weakMapObject.get(firstObject)); // John
weakMapObject.delete(secondObject);
Note: In most browsers, it will block while the print dialog is open.
215. What is the precedence order between local and global variables
A local variable takes precedence over a global variable with the same name. Let’s
see this behavior in an example.
var msg = "Good morning";
function greeting() {
msg = "Good Evening";
console.log(msg); // Good Evening
}
greeting();
var user = {
firstName: "John",
lastName: "Abraham",
language: "en",
get lang() {
return this.language;
},
set lang(lang) {
this.language = lang;
},
};
console.log(user.lang); // getter access lang as en
user.lang = "fr";
console.log(user.lang); // setter used to set lang as fr
console.log(newObject.newProperty); // 100
// Define getters
Object.defineProperty(obj, "increment", {
get: function () {
this.counter++;
return this.counter;
},
});
Object.defineProperty(obj, "decrement", {
get: function () {
this.counter--;
return this.counter;
},
});
// Define setters
Object.defineProperty(obj, "add", {
set: function (value) {
this.counter += value;
},
});
Object.defineProperty(obj, "subtract", {
set: function (value) {
this.counter -= value;
},
});
obj.add = 10;
obj.subtract = 5;
console.log(obj.increment); //6
console.log(obj.decrement); //5
The above multi-way branch statement provides an easy way to dispatch execution
to different parts of code based on the value of the expression.
222. What are the conventions to be followed for the usage of switch case
Below are the list of conventions should be taken care,
1. The expression can be of type either number or string.
2. Duplicate values are not allowed for the expression.
3. The default statement is optional. If the expression passed to switch does not
match with any case value then the statement within default case will be
executed.
4. The break statement is used inside the switch to terminate a statement
sequence.
5. The break statement is optional. But if it is omitted, the execution will
continue on into the next case.
228. What are the different error names from error object
There are 7 different types of error names returned from error object, | Error Name
| Description | |—- | ——— | AggregateError | An error indicating that multiple
errors occurred | | EvalError | An error has occurred in the eval() function | |
RangeError | An error has occurred with a number “out of range” | | ReferenceError
| An error due to an illegal reference| | SyntaxError | An error due to a syntax error|
| TypeError | An error due to a type error | | URIError | An error due to encodeURI()
|
233. How do you perform language specific date and time formatting
You can use the Intl.DateTimeFormat object which is a constructor for objects that
enable language-sensitive date and time formatting. Let’s see this behavior with an
example,
Iterable: It is an object which can be iterated over via a method whose key is
Symbol.iterator.
Iterator: It is an object returned by invoking [Symbol.iterator]() on an iterable.
This iterator object wraps each iterated element in an object and returns it via
next() method one by one.
Note: The event loop allows Node.js to perform non-blocking I/O operations, even
though JavaScript is single-threaded, by offloading operations to the system kernel
whenever possible. Since most modern kernels are multi-threaded, they can handle
multiple operations executing in the background.
1. Whenever you call a function for its execution, you are pushing it to the stack.
2. Whenever the execution is completed, the function is popped out of the stack.
Let’s take an example and it’s state representation in a diagram format
function hungry() {
eatFruits();
}
function eatFruits() {
return "I'm eating fruits";
}
@admin(true)
class User() {
}
console.log(User.isAdmin); //true
@admin(false)
class User() {
}
console.log(User.isAdmin); //false
var a = "Hello";
var b = +a;
console.log(typeof a, typeof b, b); // string, number, NaN
242. How do you sort elements in an array
The sort() method is used to sort the elements of an array in place and returns the
sorted array. The default sort order is ascending, based on the string Unicode order.
The example usage would be as below,
246. How do you find min and max values without Math functions
You can write functions which loop through an array comparing each value with the
lowest value or highest value to find the min and max values. Let’s create those
functions to find min and max values,
var marks = [50, 20, 70, 60, 45, 30];
function findMin(arr) {
var length = arr.length;
var min = Infinity;
while (length--) {
if (arr[length] < min) {
min = arr[length];
}
}
return min;
}
function findMax(arr) {
var length = arr.length;
var max = -Infinity;
while (length--) {
if (arr[length] > max) {
max = arr[length];
}
}
return max;
}
console.log(findMin(marks));
console.log(findMax(marks));
var x = 1;
x = (x++, x);
console.log(x); // 2
You can also use the comma operator in a return statement where it processes
before returning.
function myFunction() {
var a = 1;
return (a += 10), a; // 11
}
console.log(greeting(user));
console.log(initObject.a); // John
console.log(employeeObject.name); // John
256. What happens if you write constructor more than once in a class
The “constructor” in a class is a special method and it should be defined only once in
a class. i.e, If you write a constructor method more than once in a class it will throw
a SyntaxError error.
class Employee {
constructor() {
this.name = "John";
}
constructor() { // Uncaught SyntaxError: A class may only have
one constructor
this.age = 30;
}
}
console.log(employeeObject.name);
257. How do you call the constructor of a parent class
You can use the super keyword to call the constructor of a parent class. Remember
that super() must be called before using ‘this’ reference. Otherwise it will cause a
reference error. Let’s the usage of it,
class Square extends Rectangle {
constructor(length) {
super(length, length);
this.name = "Square";
}
get area() {
return this.width * this.height;
}
set area(value) {
this.area = value;
}
}
Note: By default, all the objects are extendable. i.e, The new properties can be added
or modified.
try {
Object.defineProperty(newObject, "newProperty", {
// Adding new property
value: 100,
});
} catch (e) {
console.log(e); // TypeError: Cannot define property newProperty,
object is not extensible
}
Object.defineProperties(newObject, {
newProperty1: {
value: "John",
writable: true,
},
newProperty2: {},
});
"console|greeting|function|log|Hello|JS|to|welcome|world".split("|"),
0,
{}
)
);
<form method="post">
<input type="text" name="uname" required />
<input type="submit" value="Submit" />
</form>
Note: Automatic form validation does not work in Internet Explorer 9 or earlier.
274. What are the DOM methods available for constraint validation
The below DOM methods are available for constraint validation on an invalid input,
function myOverflowFunction() {
if (document.getElementById("age").validity.rangeOverflow) {
alert("The mentioned age is not allowed");
}
}
278. Is enums feature available in javascript
No, javascript does not natively support enums. But there are different kinds of
solutions to simulate them even though they may not provide exact equivalents. For
example, you can use freeze or seal on object,
console.log(Object.getOwnPropertyNames(newObject));
["a", "b", "c"];
get area() {
return this.width * this.height;
}
set area(value) {
this.area = value;
}
}
285. How do you check whether an array includes a particular value or not
The Array#includes() method is used to determine whether an array includes a
particular value among its entries by returning either true or false. Let’s see an
example to find an element(numeric and string) within an array.
var numericArray = [1, 2, 3, 4];
console.log(numericArray.includes(3)); // true
If you would like to compare arrays irrespective of order then you should sort them
before,
const arrayFirst = [2, 3, 1, 4, 5];
const arraySecond = [1, 2, 3, 4, 5];
console.log(
arrayFirst.length === arraySecond.length &&
arrayFirst.sort().every((value, index) => value ===
arraySecond[index])
); //true
console.log(convertToThousandFormat(12345.6789));
1. Using Object Literal Notation: Let’s wrap variables and functions inside an
Object literal which acts as a namespace. After that you can access them
using object notation
var namespaceOne = {
function func1() {
console.log("This is a first definition");
}
}
var namespaceTwo = {
function func1() {
console.log("This is a second definition");
}
}
namespaceOne.func1(); // This is a first definition
namespaceTwo.func1(); // This is a second definition
(function () {
function fun1() {
console.log("This is a second definition");
}
fun1();
})();
{
let myFunction = function fun1() {
console.log("This is a second definition");
};
myFunction();
}
//myFunction(): ReferenceError: myFunction is not defined.
292. How do you invoke javascript code in an iframe from parent page
Initially iFrame needs to be accessed using either document.getElementBy or
window.frames. After that contentWindow property of iFrame gives the access for
targetFunction
document.getElementById("targetFrame").contentWindow.targetFunction();
window.frames[0].frameElement.contentWindow.targetFunction(); //
Accessing iframe this way may not work in latest versions chrome and
firefox
document.getElementsByTagName("head")[0].appendChild(fileReference);
}
295. What are the different methods to find HTML elements in DOM
If you want to access any element in an HTML page, you need to start with accessing
the document object. Later you can use any of the below methods to find the HTML
element,
Note: You can download it from jquery’s official site or install it from CDNs, like
google.
Note: This operator is often used to obtain the undefined primitive value, using
“void(0)”.
a.b.c.greeting = "welcome";
a.b.c.age = 32;
with (a.b.c) {
greeting = "welcome";
age = 32;
}
But this with statement creates performance problems since one cannot predict
whether an argument will refer to a real variable or to a property inside the with
argument.
Explanation: The variable declaration with var keyword refers to a function scope
and the variable is treated as if it were declared at the top of the enclosing scope due
to hoisting feature. So all the multiple declarations contributing to the same hoisted
variable without any error. Let’s take an example of re-declaring variables in the
same scope for both var and let/const variables.
var name = "John";
function myFunc() {
var name = "Nick";
var name = "Abraham"; // Re-assigned in the same function block
alert(name); // Abraham
}
myFunc();
alert(name); // John
The block-scoped multi-declaration throws syntax error,
let name = "John";
function myFunc() {
let name = "Nick";
let name = "Abraham"; // Uncaught SyntaxError: Identifier 'name' has
already been declared
alert(name);
}
myFunc();
alert(name);
console.log(calculateArea()); //300
309. What are template literals
Template literals or template strings are string literals allowing embedded
expressions. These are enclosed by the back-tick (`) character instead of double or
single quotes. In ES6, this feature enables using dynamic expressions as below,
Note: You can use multi-line strings and string interpolation features with template
literals.
Whereas in ES6, You don’t need to mention any newline sequence character,
console.log(`This is string sentence
'This is string sentence 2`);
You can write the above use case without nesting template features as well.
However, the nesting template feature is more compact and readable.
//Without nesting templates
const iconStyles = `icon ${
isMobilePlatform()
? ""
: user.isAuthorized
? "icon-submit"
: "icon-disabled"
}`;
var expertiseStr;
if (experienceExp > 10) {
expertiseStr = "expert developer";
} else if (skillExp > 5 && skillExp <= 10) {
expertiseStr = "senior developer";
} else {
expertiseStr = "junior developer";
}
return `${str0}${userExp}${str1}${expertiseStr}${str2}${skillExp}`;
}
If you don’t use raw strings, the newline character sequence will be processed by
displaying the output in multiple lines
var calculationString = `The sum of numbers is \n${1 + 2 + 3 + 4}!`;
console.log(calculationString);
// The sum of numbers is
// 10!
Also, the raw property is available on the first argument to the tag function
function tag(strings) {
console.log(strings.raw[0]);
}
console.log(one); // "JAN"
console.log(two); // "FEB"
console.log(three); // "MARCH"
and you can get user properties of an object using destructuring assignment,
var { name, age } = { name: "John", age: 32 };
console.log(name); // John
console.log(age); // 32
315. What are default values in destructuring assignment
A variable can be assigned a default value when the value unpacked from the array
or object is undefined during destructuring assignment. It helps to avoid setting
default values separately for each assignment. Let’s take an example for both arrays
and object use cases,
Arrays destructuring:
var x, y, z;
[x = 2, y = 4, z = 6] = [10];
console.log(x); // 10
console.log(y); // 4
console.log(z); // 6
Objects destructuring:
var { x = 2, y = 4, z = 6 } = { x: 10 };
console.log(x); // 10
console.log(y); // 4
console.log(z); // 6
if (isLegacyBrowser()) {
import(···)
.then(···);
}
2. Compute the module specifier at runtime. For example, you can use it for
internationalization.
import(`messages_${getLocale()}.js`).then(···);
1. Dynamic loading
2. State isolation
3. Global namespace isolation
4. Compilation hooks
5. Nested virtualization
2. Sorting:
var list = ["ä", "a", "z"]; // In German, "ä" sorts with "a" Whereas
in Swedish, "ä" sorts after "z"
var l10nDE = new Intl.Collator("de");
var l10nSV = new Intl.Collator("sv");
console.log(list.sort(l10nDE.compare)); // [ "a", "ä", "z" ]
console.log(list.sort(l10nSV.compare)); // [ "a", "z", "ä" ]
323. What is for…of statement
The for…of statement creates a loop iterating over iterable objects or elements such
as built-in String, Array, Array-like objects (like arguments or NodeList),
TypedArray, Map, Set, and user-defined iterables. The basic usage of for…of
statement on arrays would be as below,
let arrayIterable = [10, 20, 30, 40, 50];
The output of the array is [‘J’, ‘o’, ‘h’, ‘n’, ’ ‘, ’R’, ‘e’, ‘s’, ‘i’, ‘g’]
Explanation: The string is an iterable type and the spread operator within an array
maps every character of an iterable to one element. Hence, each character of a string
becomes an element within an Array.
326. What are the problems with postmessage target origin as wildcard
The second argument of postMessage method specifies which origin is allowed to
receive the message. If you use the wildcard “*” as an argument then any origin is
allowed to receive the message. In this case, there is no way for the sender window
to know if the target window is at the target origin when sending the message. If the
target window has been navigated to another origin, the other origin would receive
the data. Hence, this may lead to XSS vulnerabilities.
targetWindow.postMessage(message, "*");
327. How do you avoid receiving postMessages from attackers
Since the listener listens for any message, an attacker can trick the application by
sending a message from the attacker’s origin, which gives an impression that the
receiver received the message from the actual sender’s window. You can avoid this
issue by validating the origin of the message on the receiver’s end using the
“message.origin” attribute.
For example, let’s check the sender’s origin http://www.some-sender.com on
receiver side www.some-receiver.com,
//Listener on http://www.some-receiver.com/
window.addEventListener("message", function(message){
if(/^http://www\.some-sender\.com$/.test(message.origin)){
console.log('You received the data from valid sender',
message.data);
}
});
console.log(document.getElementById(‘checkboxname’).checked); // true
or false
The output of the above expression is “W”. Explanation: The bracket notation with
specific index on a string returns the character at a specific location. Hence, it
returns the character “W” of the string. Since this is not supported in IE7 and below
versions, you may need to use the .charAt() method to get the desired result.
You can throw user defined exceptions or errors using Error object in try…catch
block as below,
try {
if (withdraw > balance)
throw new Error("Oops! You don't have enough balance");
} catch (e) {
console.log(e.name + ": " + e.message);
}
Hence, the errors from above cases are helpful to avoid errors in
development/production environments.
Let’s take an example of array’s concatenation with veggies and fruits arrays,
var veggies = ["Tomato", "Carrot", "Cabbage"];
var fruits = ["Apple", "Orange", "Pears"];
var veggiesAndFruits = veggies.concat(fruits);
console.log(veggiesAndFruits); // Tomato, Carrot, Cabbage, Apple,
Orange, Pears
Shallow Copy: Shallow copy is a bitwise copy of an object. A new object is created
that has an exact copy of the values in the original object. If any of the fields of the
object are references to other objects, just the reference addresses are copied i.e.,
only the memory address is copied.
Example
var empDetails = {
name: "John",
age: 25,
expertise: "Software Developer",
};
to create a duplicate
The above statement will also change the name of empDetails, since we have a
shallow copy. That means we’re losing the original data as well.
Deep copy: A deep copy copies all fields, and makes copies of dynamically allocated
memory pointed to by the fields. A deep copy occurs when an object is copied along
with the objects to which it refers.
Example
var empDetails = {
name: "John",
age: 25,
expertise: "Software Developer",
};
Create a deep copy by using the properties from the original object into new
variable
var empDetailsDeepCopy = {
name: empDetails.name,
age: empDetails.age,
expertise: empDetails.expertise,
};
"Hello".repeat(4); // 'HelloHelloHelloHello'
347. How do you return all matching strings against a regular expression
The matchAll() method can be used to return an iterator of all results matching a
string against a regular expression. For example, the below example returns an
array of matching string results against a regular expression,
let regexp = /Hello(\d?)/g;
let greeting = "Hello1Hello2Hello3";
console.log(greetingList[0][0]); //Hello1
console.log(greetingList[1][0]); //Hello2
console.log(greetingList[2][0]); //Hello3
348. How do you trim a string at the beginning or ending
The trim method of string prototype is used to trim on both sides of a string. But if
you want to trim especially at the beginning or ending of the string then you can use
trimStart/trimLeft and trimEnd/trimRight methods. Let’s see an example of
these methods on a greeting message,
349. What is the output of below console statement with unary operator
Let’s take console statement with unary operator as given below,
console.log(+"Hello"); // NaN
The output of the above console log statement returns NaN. Because the element is
prefixed by the unary operator and the JavaScript interpreter will try to convert that
element into a number type. Since the conversion fails, the value of the statement
results in NaN value.
// usage:
class User {
constructor(name) {
this.name = name;
}
}
thunk(); // 5
asyncThunk();
The getData function won’t be called immediately but it will be invoked only when
the data is available from API endpoint. The setTimeout function is also used to
make our code asynchronous. The best real time example is redux state
management library which uses the asynchronous thunks to delay the actions to
dispatch.
console.log(circle.diameter());
console.log(circle.perimeter());
Output:
The output is 40 and NaN. Remember that diameter is a regular function, whereas
the value of perimeter is an arrow function. The this keyword of a regular
function(i.e, diameter) refers to the surrounding scope which is a class(i.e, Shape
object). Whereas this keyword of perimeter function refers to the surrounding
scope which is a window object. Since there is no radius property on window
objects it returns an undefined value and the multiple of number value returns NaN
value.
In the above expression, g and m are for global and multiline flags.
console.log(![]); // false
Screenshot
372. How do you display data in a tabular format using console object
The console.table() is used to display data in the console in a tabular format to
visualize complex arrays or objects.
const users = [
{ name: "John", id: 1, city: "Delhi" },
{ name: "Max", id: 2, city: "London" },
{ name: "Rod", id: 3, city: "Paris" },
];
console.table(users);
But you can make it work with multi-dimensional arrays by recursive calls,
function flattenMultiArray(arr) {
const flattened = [].concat(...arr);
return flattened.some((item) => Array.isArray(item))
? flattenMultiArray(flattened)
: flattened;
}
const multiDimensionalArr = [11, [22, 33], [44, [55, 66, [77, [88]],
99]]];
const flatArr = flattenMultiArray(multiDimensionalArr); // [11, 22, 33,
44, 55, 66, 77, 88, 99]
You can also use popstate event to detect the browser back button. Note: The
history entry has been activated using history.pushState method.
window.addEventListener('popstate', () => {
console.log('Clicked browser back button');
box.style.backgroundColor = 'white';
});
box.addEventListener('click', () => {
box.style.backgroundColor = 'blue';
window.history.pushState({}, null, null);
});
In the preceeding code, When the box element clicked, its background color
appears in blue color and changed to while color upon clicking the browser
back button using `popstate` event handler. The `state` property of
`popstate` contains the copy of history entry's state object.
**[ ](#table-of-contents)**
379. How do you disable right click in the web page
The right click on the page can be disabled by returning false from the
oncontextmenu attribute on the body element.
i.e, Every primitive except null and undefined have Wrapper Objects and the list of
wrapper objects are String,Number,Boolean,Symbol and BigInt.
382. What are the different ways to deal with Asynchronous Code
Below are the list of different ways to deal with Asynchronous code.
1. Callbacks
2. Promises
3. Async/await
4. Third-party libraries such as async.js,bluebird etc
fetch("http://localhost:8000", { signal })
.then((response) => {
console.log(`Request 1 is complete!`);
})
.catch((e) => {
if (e.name === "AbortError") {
// We know it's been canceled!
}
});
fetch("http://localhost:8000", { signal })
.then((response) => {
console.log(`Request 2 is complete!`);
})
.catch((e) => {
if (e.name === "AbortError") {
// We know it's been canceled!
}
});
In this API, browser is going to ask you for permission to use your microphone
Example:
console.log("Start"); //1
queueMicrotask(() => {
console.log("Inside microtask"); // 3
});
console.log("End"); //2
By using queueMicrotask, you can ensure that certain tasks or callbacks are
executed at the earliest opportunity during the JavaScript event loop, making it
useful for performing work that needs to be done asynchronously but with higher
priority than regular setTimeout or setInterval callbacks.
In the runtime, typescript will provide the type to the customLibrary variable as
any type. The another alternative without using declare keyword is below
var customLibrary: any;
Promises Observables
Emits only a single value at a Emits multiple values over a period of
time time(stream of values ranging from 0 to
multiple)
Eager in nature; they are going Lazy in nature; they require subscription
to be called immediately to be invoked
Promise is always asynchronous Observable can be either synchronous or
even though it resolved asynchronous
immediately
Doesn’t provide any operators Provides operators such as map, forEach,
filter, reduce, retry, and retryWhen etc
Cannot be canceled Canceled by using unsubscribe() method
Screenshot
Screenshot
isPrimitive(myPrimitive);
isPrimitive(myNonPrimitive);
If the value is a primitive data type, the Object constructor creates a new wrapper
object for the value. But If the value is a non-primitive data type (an object), the
Object constructor will give the same object.
1. Transform syntax
2. Polyfill features that are missing in your target environment (using
@babel/polyfill)
3. Source code transformations (or codemods)
399. Is Node.js completely single threaded
Node is a single thread, but some of the functions included in the Node.js standard
library(e.g, fs module functions) are not single threaded. i.e, Their logic runs outside
of the Node.js single thread to improve the speed and performance of a program.
402. What is the difference between Function constructor and function declaration
The functions which are created with Function constructor do not create closures
to their creation contexts but they are always created in the global scope. i.e, the
function can access its own local variables and global scope variables only. Whereas
function declarations can access outer function variables(closures) too.
Function Constructor:
var a = 100;
function createFunction() {
var a = 200;
return new Function("return a;");
}
console.log(createFunction()()); // 100
Function declaration:
var a = 100;
function createFunction() {
var a = 200;
return function func() {
return a;
};
}
console.log(createFunction()()); // 200
403. What is a Short circuit condition
Short circuit conditions are meant for condensed way of writing simple if
statements. Let’s demonstrate the scenario using an example. If you would like to
login to a portal with an authentication condition, the expression would be as below,
if (authenticate) {
loginToPorta();
}
Since the javascript logical operators evaluated from left to right, the above
expression can be simplified using && logical operator
array.length = 2;
console.log(array.length); // 2
console.log(array); // [1,2]
Screenshot
Note: Observables are not part of the JavaScript language yet but they are being
proposed to be added to the language
Classes:
const user = new User(); // ReferenceError
class User {}
Constructor Function:
const user = new User(); // No error
function User() {}
Promise.reject("error value").catch(function () {
throw new Error("error");
});
But there are many modern JavaScript environments that won’t print any errors.
You can fix this problem in different ways,
1. Add catch block at the end of each chain: You can add catch block to the
end of each of your promise chains
Promise.resolve("promised value")
.then(function () {
throw new Error("error");
})
.catch(function (error) {
console.error(error.stack);
});
But it is quite difficult to type for each promise chain and verbose too.
2. Add done method: You can replace first solution’s then and catch blocks
with done method
Promise.resolve("promised value").done(function () {
throw new Error("error");
});
Let’s say you want to fetch data using HTTP and later perform processing on
the resulting data asynchronously. You can write done block as below,
getDataFromHttp()
.then(function (result) {
return processDataAsync(result);
})
.done(function (processed) {
displayData(processed);
});
In future, if the processing library API changed to synchronous then you can
remove done block as below,
getDataFromHttp().then(function (result) {
return displayData(processDataAsync(result));
});
and then you forgot to add done block to then block leads to silent errors.
3. Extend ES6 Promises by Bluebird: Bluebird extends the ES6 Promises API
to avoid the issue in the second solution. This library has a “default”
onRejection handler which will print all errors from rejected Promises to
stderr. After installation, you can process unhandled rejections
Promise.onPossiblyUnhandledRejection(function (error) {
throw error;
});
const collection = {
one: 1,
two: 2,
three: 3,
[Symbol.iterator]() {
const values = Object.keys(this);
let i = 0;
return {
next: () => {
return {
value: this[values[i++]],
done: i > values.length,
};
},
};
},
};
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); //120
But if you use Tail recursion functions, they keep passing all the necessary data it
needs down the recursion without relying on the stack.
function factorial(n, acc = 1) {
if (n === 0) {
return acc;
}
return factorial(n - 1, n * acc);
}
console.log(factorial(5)); //120
The above pattern returns the same output as the first one. But the accumulator
keeps track of total as an argument without using stack memory on recursive calls.
function isPromise(object) {
if (Promise && Promise.resolve) {
return Promise.resolve(object) == object;
} else {
throw "Promise not supported in your environment";
}
}
var i = 1;
var promise = new Promise(function (resolve, reject) {
resolve();
});
console.log(isPromise(i)); // false
console.log(isPromise(promise)); // true
414. What are the differences between arguments object and rest parameter
There are three main differences between arguments object and rest parameters
1. The arguments object is an array-like but not an array. Whereas the rest
parameters are array instances.
2. The arguments object does not support methods such as sort, map, forEach,
or pop. Whereas these methods can be used in rest parameters.
3. The rest parameters are only the ones that haven’t been given a separate
name, while the arguments object contains all arguments passed to the
function
415. What are the differences between spread operator and rest parameter
Rest parameter collects all remaining elements into an array. Whereas Spread
operator allows iterables( arrays / objects / strings ) to be expanded into single
arguments/elements. i.e, Rest parameter is opposite to the spread operator.
console.log(Array.from(SomeObj)); // [ 1, 2, 3 ]
417. What are the built-in iterables
Below are the list of built-in iterables in javascript,
418. What are the differences between for…of and for…in statements
Both for…in and for…of statements iterate over js data structures. The only
difference is over what they iterate:
arr.newProp = "newVlue";
Since for..in loop iterates over the keys of the object, the first loop logs 0, 1, 2 and
newProp while iterating over the array object. The for..of loop iterates over the
values of a arr data structure and logs a, b, c in the console.
But Static(class) and prototype data properties must be defined outside of the
ClassBody declaration. Let’s assign the age value for Person class as below,
Person.staticAge = 30;
Person.prototype.prototypeAge = 40;
Since both IIFE and void operator discard the result of an expression, you can avoid
the extra brackets using void operator for IIFE as below,
void function (dt) {
console.log(dt.toLocaleTimeString());
}(new Date());
It is also possible to add more styles for the content. For example, the font-size can
be modified for the above text
console.log(
"%cThis is a red text with bigger font",
"color:red; font-size:20px"
);
console.group("User Details");
console.log("name: Sudheer Jonna");
console.log("job: Software Developer");
// Nested Group
console.group("Address");
console.log("Street: Commonwealth");
console.log("City: Los Angeles");
console.log("State: California");
console.log(newArray); // [ 5, 4, 3, 2, 1]
console.log(originalArray); // [ 5, 4, 3, 2, 1]
There are few solutions that won’t mutate the original array. Let’s take a look.
1. Using slice and reverse methods: In this case, just invoke the slice()
method on the array to create a shallow copy followed by reverse() method
call on the copy.
const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.slice().reverse(); //Slice an
array gives a new copy
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [ 5, 4, 3, 2, 1]
2. Using spread and reverse methods: In this case, let’s use the spread syntax
(…) to create a copy of the array followed by reverse() method call on the
copy.
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [ 5, 4, 3, 2, 1]
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [ 5, 4, 3, 2, 1]
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [ 5, 4, 3, 2, 1]
5. Using reduceRight and push methods: Here execute a right reducer
function(i.e. opposite direction of reduce method) on an array elements and
push the iterated value to the accumulator
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [ 5, 4, 3, 2, 1]
2. Use custom element just like other HTML element: Declare your custom
element as a HTML tag.
<body>
<custom-element>
</body>
function A() {
console.log("Start function A");
function B() {
console.log("In function B");
}
B();
}
A();
console.log("GlobalContext");
The debounce() function can be used on input, button and window events.
Input:
<input type="text" onkeyup="processChange()" />
Button:
<button onclick="processChange()">Click me</button>
Windows event:
window.addEventListener("scroll", processChange);
console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined
The instanceof operator is used to check the type of an array at run time. It
returns true if the type of a variable is an Array other false for other type.
const numbers = [1, 2, 3];
const user = { name: "John" };
console.log(numbers instanceof Array); // true
console.log(user instanceof Array); // false
b++;
console.log(a, b); //5, 6
In the above code snippet, the value of a is assigned to b and the variable b has been
incremented. Since there is a new space created for variable b, any update on this
variable doesn’t impact the variable a.
Pass by reference doesn’t create a new space in memory but the new variable
adopts a memory address of an initial variable. Non-primitives such as objects,
arrays and functions gets the reference of the initiable variable. i.e, updating one
value will impact the other variable.
let user1 = {
name: "John",
age: 27,
};
let user2 = user1;
user2.age = 30;
console.log(user1.age, user2.age); // 30, 30
In the above code snippet, updating the age property of one object will impact the
other property due to the same reference.
Primitives Non-primitives
These types are predefined Created by developer
These are immutable Mutable
Compare by value Compare by reference
Stored in Stack Stored in heap
Contain certain value Can contain NULL too
441. How do you create your own bind method using either call or apply method?
The custom bind function needs to be created on Function prototype inorder to use
it as other builtin functions. This custom function should return a function similar to
original bind method and the implementation of inner function needs to use apply
method call.
The function which is going to bind using custom myOwnBind method act as the
attached function(boundTargetFunction) and argument as the object for apply
method call.
Function.prototype.myOwnBind = function (whoIsCallingMe) {
if (typeof this !== "function") {
throw new Error(this + "cannot be bound as it's not callable");
}
const boundTargetFunction = this;
return function () {
boundTargetFunction.apply(whoIsCallingMe, arguments);
};
};
442. What are the differences between pure and impure functions?
Some of the major differences between pure and impure function are as below,
multiplyBy2(add(2, 3));
return {
// Return public variables or functions here.
};
})();
Let’s see an example of a module pattern for an employee with private and public
access,
const createEmployee = (function () {
// Private
const name = "John";
const department = "Sales";
const getEmployeeName = () => name;
const getDepartmentName = () => department;
// Public
return {
name,
department,
getName: () => getEmployeeName(),
getDepartment: () => getDepartmentName(),
};
})();
console.log(createEmployee.name);
console.log(createEmployee.department);
console.log(createEmployee.getName());
console.log(createEmployee.getDepartment());
Note: It mimic the concepts of classes with private variables and methods.
But you can fix this issue with an alternative IIFE (Immediately Invoked Function
Expression) to get access to the feature.
(async function () {
await Promise.resolve(console.log("Hello await")); // Hello await
})();
In ES2022, you can write top-level await without writing any hacks.
await Promise.resolve(console.log("Hello await")); //Hello await
console.log(this);
– In a global context, this refers to the global object (e.g., window in a browser).
Example 2: this in a Function
function displayThis() {
console.log(this);
}
displayThis();
person.greet();
– In a method, this refers to the object that owns the method (person in the
case).
Example 4: this in an Event Handler
document.getElementById('myButton').addEventListener('click',
function() {
console.log(this);
});
– In an event handler, this refers to the element that triggered the event (the
button in this case).
• Function Factories: Closures are often used to create functions with pre-set
parameters. This is useful when you need to create multiple functions with similar
behavior but different configurations.
• Callback Functions: Closures are frequently used in asynchronous programming,
such as handling event listeners or AJAX requests. The inner function captures
variables from the outer scope and can access them when the callback is invoked.
• iterators and Generators: Closures can be used to create iterators and generators,
which are essential for working with collections of data in modern JavaScript.
456. How do you create polyfills for map, filter and reduce methods?
The polyfills for array methods such as map, filter and reduce methods can be created
using array prototype.
1. map:
The built-in Array.map method syntax will be helpful to write polyfill. The map
method takes the callback function as an argument and that callback function can
have below three arguments passed into it.
i. Current value
ii. Index of current value(optional)
iii. array(optional)
The syntax would like below,
let newArray = arr.map(callback(currentValue[, index, arr) {
// return new array after executing the code
})
Let’s build our map polyfill based on the above syntax,
Array.prototype.myMap = function(cb) {
let newArr = [];
for(let i=0; i< this.length; i++) {
newArr.push(cb(this[i], i, this));
}
return newArr;
};
In the above code, custom method name ‘myMap’ has been used to avoid conflicts
with built-in method.
2. filter: Similar to map method, Array.filter method takes callback function as an
argument and the callback function can have three agurguments passed into it.
i. Current value
ii. Index of current value(optional)
iii. array(optional)
3. reduce:
The built-in Array.reduce method syntax will be helpful to write our own polyfill.
The reduce method takes the callback function as first argument and the initial
value as second argument.
The callback function can have four arguments passed into it.
i. Accumulator
ii. Current value
iii. Index of current value(optional)
iv. array(optional)
The syntax would like below,
arr.reduce(callback((acc, curr, i, arr) => {}), initValue);
1. Returning values: The map method returns a new array with transformed
elements whereas forEach method returns undefined eventhough both of
them are doing the same job.
const arr = [1, 2, 3, 4, 5];
arr.map(x => x * x); // [1, 4, 9, 16, 25]
arr.forEach(x => x * x); //
3. Mutation: The map method doesn’t mutate the original array by returning
new array. Whereas forEach method also doesn’t mutate the original array
but it’s callback is allowed to mutate the original array.
Note: Both these methods existed since ES5 onwards.
1. An empty statement
2. var statement
3. An expression statement
4. do-while statement
5. continue statement
6. break statement
7. return statement
8. throw statement
1. Capturing phase: This phase goes down gradually from the top of the DOM
tree to the target element when a nested element clicked. Before the click
event reaching the final destination element, the click event of each parent’s
element must be triggered.
2. Target phase: This is the phase where the event originally occurred reached
the target element .
3. Bubbling phase: This is reverse of the capturing phase. In this pase, the
event bubbles up from the target element through it’s parent element, an
ancestor and goes all the way to the global window object.
The pictorial representation of these 3 event phases in DOM looks like below,
Screenshot
function Person(name) {
this.name = name;
}
person1.age = 40;
person1.gender = "Male";
person2.gender = "Female";
person2.age = 50;
Since both the objects(person1 and person2) do not share the hidden classes, now
V8 engine cannot use Inline Caching technique for the faster access of properties.
function area(obj) {
//Calculate area
}
for(let i=0; i<100; i++) {
area(shape);
}
After few successful calls of the same area method to its same hidden class, V8 engine omits
the hidden class lookup and simply adds the offset of the property to the object pointer
itself. As a result, it increases the execution speed.
There are mainly 3 types of inline caching possible:
1. Monomorphic: This is a optimized caching technique in which there can be always
same type of objects passed.
2. Polymorphic: This ia slightly optimized caching technique in which limited number
of different types of objects can be passed.
3. Megamorphic: It is an unoptimized caching in which any number of different objects
can be passed.
463. What are the different ways to execute external scripts?
There are three different ways to execute external scripts,
1. async: The script is downloaded in parallel to parsing the page, and executed
as soon as it is available even before parsing completes. The parsing of the
page is going to be interuppted once the script is downloaded completely and
then the script is executed. Thereafter, the parsing of the remaining page will
continue.
2. defer: The script is downloaded in parallel to parsing the page, and executed
after the page has finished parsing.
Note: You should only use either async or defer attribute if the src attribute is
present.
You can also watch changes to system color scheme using addEventListener,
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", (event) => {
const theme = event.matches ? "dark" : "light";
});
function sum(a, b, c) {
return a + b +c;
}
console.log(multiply.length); //2
console.log(sum.length); //3
But there are few important rules which needs to be noted while using length property.
1. Default values: Only the parameters which exists before a default value are
considered. javascript function sum(a, b=2, c=3) { return
a + b + c; } console.log(sum.length); // 1
2. Rest params: The rest parameters are excluded with in length property.
javascript function sum(a, b, ...moreArgs) { let total
= a + b; for (const arg of moreArgs) { total +=
arg; } return total; }
console.log(sum.length); // 2
Note: The Function constructor is itself a function object and it has a length property of 1.
469. What is globalThis, and what is the importance of it?
Nowadays JavaScript language is used in a wide variety of environments and each
environment has its own object model. Due to this fact, there are different
ways(syntax) to access the global object.
1. In web browser, the global object is accessible via window, self, or frames.
2. In Node environment, you have to use global.
3. In Web workers, the global object is available through self.
The globalThis property provides a standard way of accessing the global object without
writing various code snippet to support multiple environments. For example, the global
object retuned from multiple environments as shown below,
//1. browser environment
console.log(globalThis); // => Window {...}
// This variable is PRIVATE to moduleA. It's like a tool inside a closed box.
const privateVariable = "I am private";
// This variable is PUBLIC because it's exported. Others can use it when they
import moduleA.
export const publicVariable = "I am public";
// moduleB.js