Js Interview
Js Interview
1. What is a CDN?
2. What is AJAX?
3. What are the differences between HTML and XHTML?
4. What is responsive design?
5. What are the different types of CSS selectors?
6. What is a pseudo-class?
7. What is a CSS reset?
8. What is a CSS grid system?
9. What is a CSS preprocessor?
10. What are the benefits of using a CSS preprocessor?
11. What is Bootstrap?
12. What are the benefits of using bootstrap?
13. What is a task runner?
14. What are the benefits of using a task runner?
15. What made you become a front-end developer?
16. What is your favorite thing about being a front-end
developer?
CSS
• What is CSS selector specificity and how does it work?
• What is the difference between "resetting" and "normalizing" CSS?
Which would you choose, and why?
• Describe Floats and how they work.
• Describe z-index and how stacking context is formed.
• Describe BFC (Block Formatting Context) and how it works.
• What are the various clearing techniques and which is appropriate for
what context?
• How would you approach fixing browser-specific styling issues?
• How do you serve your pages for feature-constrained browsers?
• What techniques/processes do you use?
• What are the different ways to visually hide content (and make it
available only for screen readers)?
• Have you ever used a grid system, and if so, what do you prefer?
• Have you used or implemented media queries or mobile specific
layouts/CSS?
• Are you familiar with styling SVG?
• Can you give an example of an @media property other than screen?
• What are some of the "gotchas" for writing efficient CSS?
• What are the advantages/disadvantages of using CSS preprocessors?
• Describe what you like and dislike about the CSS preprocessors you have
used.
• How would you implement a web design comp that uses non-standard
fonts?
• Explain how a browser determines what elements match a CSS selector.
• Describe pseudo-elements and discuss what they are used for.
• Explain your understanding of the box model and how you would tell the
browser in CSS to render your layout in different box models.
• What does * { box-sizing: border-box; } do? What are its advantages?
• What is the CSS display property and can you give a few examples of its
use?
• What is the difference between inline and inline-block?
• What is the difference between the "nth-of-type()" and
"nth-child()" selectors?
• What is the difference between a relative, fixed,
absolute and statically positioned element?
• What existing CSS frameworks have you used locally, or
in production? How would you change/improve them?
• Have you used CSS Grid?
• Can you explain the difference between coding a web
site to be responsive versus using a mobile-first
strategy?
• Have you ever worked with retina graphics? If so, when
and what techniques did you use?
• Is there any reason you'd want to use translate() instead
of absolute positioning, or vice-versa? And why?
• How is clearfix css property useful?
• Can you explain the difference between px, em and rem
as they relate to font sizing?
• Can you give an example of a pseudo class? Can you
provide an example use case for a pseudo class?
• What is the difference between a block level element
and an inline element. Can you provide examples of
each type of element?
• What is the difference between CSS Grid and Flexbox?
When would you use one over the other?
• What is the difference between fixed, fluid and
responsive layouts?
JS
Table of Contents
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 an Object with a Map
9 What is the difference between == and === operators
10 What are lambda 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 switch block without an error
21 What is the Temporal Dead Zone
22 What is 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
1
No. Questions
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
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
69 What is the purpose of double exclamation
70 What is the purpose of the delete operator
2
No. Questions
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
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
3
No. Questions
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 convert the first letter of a string to uppercase
130 What are the pros and cons of 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 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
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 with in 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 available in Regular expression
156 What are modifiers in regular expression
157 What are regular expression patterns
4
No. Questions
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
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 Give an example where do you really need 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
5
No. Questions
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 a WeakSet and a Set
205 List down the collection of methods available on WeakSet
206 What is a WeakMap
207 What are the differences between a WeakMap and a Map
208 List down the collection of methods available on WeakMap
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 the synchronous iteration work
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
244 How do you reversing an array
6
No. Questions
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
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
7
No. Questions
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 below for loops
304 List down some of the features of ES6
305 What is ES6
306 Can I redeclare let and const variables
307 Is const variable makes 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
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
8
No. Questions
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
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
9
No. Questions
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
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
10
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 What are hidden classes?
442 What is inline caching?
443 How do you create your own bind method using either call or apply
method?
444 What are the differences between pure and impure functions?
445 What is referential transparency?
446 What are the possible side-effects in javascript?
447 What are compose and pipe functions?
448 What is module pattern?
449 What is Function Composition?
450 How to use await outside of async function prior to ES2022?
1.
11
var object = {
name: "Sudheer",
age: 34
};
Object literal property values can be of any data type, including array, function,
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 Object() is a built-in constructor function so “new” keyword is
not required. The above code snippet can be re-written as:
var object = Object();
3. Object’s create method:
The create method of Object is used to create a new object by passing
the specificied prototype object and properties as arguments, i.e., this
pattern is helpful to create new objects based on existing objects. The
second argument is optional and it is used to create properties on a
newly created 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");
5. Function constructor with prototype:
This is similar to function constructor but it uses prototype for their
properties and methods,
function Person() {}
Person.prototype.name = "Sudheer";
var object = new Person();
12
This is equivalent to creating an instance with Object.create method
with a function prototype and then calling that function with an
instance and parameters as arguments.
function func() {}
// If the result is a non-null object then use it otherwise just use the new instan
console.log(result && typeof result === 'object' ? result : newInstance);
6. ES6 Class syntax:
ES6 introduces class feature to create objects.
class Person {
constructor(name) {
this.name = name;
}
}
13
available through Object.prototype.
Screenshot
� Back to Top
3.
invite.call(employee1, "Hello", "How are you?"); // Hello John Rodson, How are you?
invite.call(employee2, "Hello", "How are you?"); // Hello Jimmy Baily, How are you?
Apply: Invokes the function with a given this value and allows you to
pass in arguments as an array
var employee1 = { firstName: "John", lastName: "Rodson" };
var employee2 = { firstName: "Jimmy", lastName: "Baily" };
invite.apply(employee1, ["Hello", "How are you?"]); // Hello John Rodson, How are you?
invite.apply(employee2, ["Hello", "How are you?"]); // Hello Jimmy Baily, How are you?
Bind: returns a new function, allowing you to pass any number of argu-
ments
var employee1 = { firstName: "John", lastName: "Rodson" };
var employee2 = { firstName: "Jimmy", lastName: "Baily" };
14
console.log(
greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2
);
}
15
let arrayIntegers = [1, 2, 3, 4, 5];
let arrayIntegers1 = arrayIntegers.slice(0, 2); // returns [1,2]
let arrayIntegers2 = arrayIntegers.slice(2, 3); // returns [3]
let arrayIntegers3 = arrayIntegers.slice(4); //returns [5]
Note: Slice method doesn’t mutate the original array but it returns the
subset as a new array.
� Back to Top
6.
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
� Back to Top
16
8.
17
3. Two Boolean operands are strictly equal if both are true or both are
false.
4. Two objects are strictly equal if they refer to the same Object.
5. Null and Undefined types are not equal with ===, but equal with
==, i.e, null===undefined –> false, but null==undefined –> true
Some of the example which covers the above cases:
0 == false // true
0 === false // false
1 == "1" // true
1 === "1" // false
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
[]==[] or []===[] //false, refer different objects in memory
{}=={} or {}==={} //false, refer different objects in memory
� Back to Top
10.
18
What is a first order function
A first-order function is a function that doesn’t accept another function
as an argument and doesn’t return a function as its return value.
const firstOrder = () => console.log("I am a first order function!");
� Back to Top
13.
19
curryUnaryFunction(1)(2); // returns a function: c => 3 + c
curryUnaryFunction(1)(2)(3); // returns the number 6
Curried functions are great to improve code reusability and functional
composition.
� Back to Top
16.
20
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, state-
ment, 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.
Let’s take an example to demonstrate the usage,
let counter = 30;
if (counter === 30) {
let counter = 31;
console.log(counter); // 31
}
console.log(counter); // 30 (because the variable in if block won't exist here)
� Back to Top
18.
var let
It has been available from the beginning of Introduced as part of ES6
JavaScript
It has function scope It has block scope
Variables will be hoisted Hoisted but not
initialized
21
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.
� Back to Top
20.
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;
}
}
� Back to Top
21.
22
What is the Temporal Dead Zone
The Temporal Dead Zone is a behavior in JavaScript that occurs when
declaring a variable with the let and const keywords, but not with var. In
ECMAScript 6, accessing a let or const variable before its declaration
(within its scope) causes a ReferenceError. The time span when that
happens, between the creation of a variable’s binding and its declaration,
is called the temporal dead zone.
Let’s see this behavior with an example,
function somemethod() {
console.log(counter1); // undefined
console.log(counter2); // ReferenceError
var counter1 = 1;
let counter2 = 2;
}
� Back to Top
22.
23
function is used to decode an URL. This function requires an encoded
URL string as parameter and return that decoded string.
Note: If you want to encode characters such as / ? : @ & = + $ # then
you need to use encodeURIComponent().
let uri = "employeeDetails?name=john&occupation=manager";
let encoded_uri = encodeURI(uri);
let decoded_uri = decodeURI(encoded_uri);
� Back to Top
24.
What is memoization
Memoization is a functional programming technique which attempts to
increase a function’s performance by caching its previously computed re-
sults. Each time a memoized function is called, its parameters are used to
index the cache. If the data is present, then it can be returned, without
executing the entire function. Otherwise the function is executed and then
the result is added to the cache. Let’s take an example of adding function
with memoization,
const memoizAddition = () => {
let cache = {};
return (value) => {
if (value in cache) {
console.log("Fetching from cache");
return cache[value]; // Here, cache.value cannot be used as property name starts
} else {
console.log("Calculating result");
let result = value + 20;
cache[value] = result;
return result;
}
};
};
// returned function from memoizAddition
const addition = memoizAddition();
console.log(addition(20)); //output: 40 calculated
console.log(addition(20)); //output: 40 cached
� Back to Top
25.
24
What is Hoisting
Hoisting is a JavaScript mechanism where variables, function declarations
and classes are moved to the top of their scope before code execution. Re-
member that JavaScript only hoists declarations, not initialisation. Let’s
take a simple example of variable hoisting,
console.log(message); //output : undefined
var message = "The variable Has been hoisted";
The above code looks like as below to the interpreter,
var message;
console.log(message);
message = "The variable Has been hoisted";
In the same fashion, function declarations are hoisted too
message("Good morning"); //Good morning
function message(name) {
console.log(name);
}
This hoisting makes functions to be safely used in code before they are
declared.
� Back to Top
26.
Bike.prototype.getDetails = function () {
return this.model + " bike has" + this.color + " color";
};
Whereas ES6 classes can be defined as an alternative
class Bike {
constructor(color, model) {
this.color = color;
this.model = model;
25
}
getDetails() {
return this.model + " bike has" + this.color + " color";
}
}
� Back to Top
27.
26
Why do you need modules
Below are the list of benefits using modules in javascript ecosystem
1. Maintainability
2. Reusability
3. Namespacing
� Back to Top
30.
27
� Back to Top
34.
What is IndexedDB
IndexedDB is a low-level API for client-side storage of larger amounts of
structured data, including files/blobs. This API uses indexes to enable
high-performance searches of this data.
� Back to Top
35.
What is a Cookie
A cookie is a piece of data that is stored on your computer to be accessed
by your browser. Cookies are saved as key/value pairs. For example, you
can create a cookie named username as below,
document.cookie = "username=John";
28
Screenshot
� Back to Top
38.
29
What are the differences between cookie, local storage and ses-
sion storage
Below are some of the differences between cookie, local storage and session
storage,
Local Session
Feature Cookie storage storage
Accessed on client or Both server-side & client-side client-side
server side client-side only only
Lifetime As configured using until until tab is
Expires option deleted closed
SSL support Supported Not Not
supported supported
Maximum data size 4KB 5 MB 5MB
� Back to Top
42.
30
What are the methods available on session storage
The session storage provided methods for reading, writing and clearing
the session data
// Save data to sessionStorage
sessionStorage.setItem("key", "value");
31
Why do you need web storage
Web storage is more secure, and large amounts of data can be stored locally,
without affecting website performance. Also, the information is never
transferred to the server. Hence this is a more recommended approach
than Cookies.
� Back to Top
47.
function timedCount() {
i = i + 1;
32
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");
}
and we can receive messages from web worker
w.onmessage = function (event) {
document.getElementById("message").innerHTML = event.data;
};
1. Terminate a Web Worker: Web workers will continue to listen for
messages (even after the external script is finished) until it is termi-
nated. 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;
� Back to Top
50.
33
What is a promise
A promise is an object that may produce a single value some time in the
future with either a resolved value or a reason that it’s not resolved(for
example, network error). It will be in one of the 3 possible states: fulfilled,
rejected, or pending.
The syntax of Promise creation looks like below,
const promise = new Promise(function (resolve, reject) {
// promise description
});
The usage of a promise would be as below,
const promise = new Promise(
(resolve) => {
setTimeout(() => {
resolve("I'm a Promise!");
}, 5000);
},
(reject) => {}
);
34
3. Rejected: This state indicates that the operation did not complete.
In this case an error value will be thrown.
� Back to Top
54.
function outerFunction(callback) {
let name = prompt("Please enter your name.");
callback(name);
}
outerFunction(callbackFunction);
� Back to Top
55.
Output;
35
// 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.
� Back to Top
56.
36
source.onmessage = function (event) {
document.getElementById("output").innerHTML += event.data + "<br>";
};
}
� Back to Top
59.
37
What is callback in callback
You can nest one callback inside in another callback to execute the actions
sequentially one by one. This is known as callbacks in callbacks.
loadScript("/script1.js", function (script) {
console.log("first script is loaded");
38
2. After that .then handler is called by logging the result(1) and then
return a promise with the value of result * 2.
3. After that the value passed to the next .then handler by logging the
result(2) and return a promise with result * 3.
4. Finally the value passed to the last .then handler by logging the
result(6) and return a promise with result * 4.
� Back to Top
64.
What is promise.all
Promise.all is a promise that takes an array of promises as an input (an
iterable), and it gets resolved when all the promises get resolved or any
one of them gets rejected. For example, the syntax of promise.all method
is below,
Promise.all([Promise1, Promise2, Promise3]) .then(result) => { console.log(result) })
Note: Remember that the order of the promises(output the result) is
maintained as per input order.
� Back to Top
65.
39
What is a strict mode in javascript
Strict Mode is a new feature in ECMAScript 5 that allows you to place
a program, or a function, in a “strict” operating context. This way it
prevents certain actions from being taken and throws more exceptions.
The literal expression "use strict"; instructs the browser to use the
javascript code in the Strict mode.
� Back to Top
67.
function myFunction() {
"use strict";
y = 3.14; // This will cause an error
}
� Back to Top
69.
40
otherwise, it will be true. For example, you can test IE version using this
expression as below,
let isIE8 = false;
isIE8 = !!navigator.userAgent.match(/MSIE 8.0/);
console.log(isIE8); // returns true or false
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
Note: The expression !! is not an operator, but it is just twice of !
operator.
� Back to Top
70.
41
Any variable can be emptied by setting the value to undefined.
user = undefined;
� Back to Top
73.
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
� Back to Top
75.
What is eval
The eval() function evaluates JavaScript code represented as a string. The
string can be a JavaScript expression, variable, statement, or sequence of
statements.
console.log(eval("1 + 2")); // 3
42
� Back to Top
76.
Window Document
It is the root level element in any It is the direct child of the window object.
web page This is also known as Document Object
Model(DOM)
By default window object is You can access it via window.document
available implicitly in the page or document.
It has methods like alert(), It provides methods like getElementById,
confirm() and properties like getElementsByTagName, createElement
document, location etc
� Back to Top
77.
43
<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>
� Back to Top
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
� Back to Top
80.
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.
� Back to Top
44
81.
isFinite(100); // true
� Back to Top
85.
45
What is an event flow
Event flow is the order in which event is received on the web page. When
you click an element that is nested in various other elements, before your
click actually reaches its destination, or target element, it must trigger the
click event for each of its parent elements first, starting at the top with
the global window object. There are two ways of event flow
1. Top to Bottom(Event Capturing)
2. Bottom to Top (Event Bubbling)
� Back to Top
86.
46
How do you find operating system details
The window.navigator object contains information about the visitor’s
browser OS details. Some of the OS properties are available under
platform property,
console.log(navigator.platform);
� Back to Top
90.
47
What are the pros and cons of promises over callbacks
Below are the list of pros and cons of promises over callbacks,
Pros:
1. It avoids callback hell which is unreadable
2. Easy to write sequential asynchronous code with .then()
3. Easy to write parallel asynchronous code with Promise.all()
4. Solves some of the common problems of callbacks(call the callback
too late, too early, many times and swallow errors/exceptions)
Cons:
1. It makes little complex code
2. You need to load a polyfill if ES6 is not supported
� Back to Top
94.
48
96.
49
100.
50
document
.getElementById("link")
.addEventListener("click", function (event) {
event.preventDefault();
});
Note: Remember that not all events are cancelable.
� Back to Top
103.
<script>
function firstFunc(event) {
alert("DIV 1");
event.stopPropagation();
}
function secondFunc() {
alert("DIV 2");
}
</script>
� Back to Top
104.
51
What is BOM
The Browser Object Model (BOM) allows JavaScript to “talk to” the
browser. It consists of the objects navigator, history, screen, location and
document which are children of the window. The Browser Object Model
is not standardized and can change based on different browsers.
Screenshot
� Back to Top
106.
52
What is an event delegation
Event delegation is a technique for listening to events where you delegate
a parent element as the listener for all of the events that happen inside it.
For example, if you wanted to detect field changes in inside a specific form,
you can use event delegation technique,
var form = document.querySelector("#registration-form");
What is ECMAScript
ECMAScript is the scripting language that forms the basis of JavaScript.
ECMAScript standardized by the ECMA International standards organi-
zation in the ECMA-262 and ECMA-402 specifications. The first edition
of ECMAScript was released in 1997.
� Back to Top
111.
What is JSON
JSON (JavaScript Object Notation) is a lightweight format that is used
for data interchanging. It is based on a subset of JavaScript language in
the way objects are built in JavaScript.
� Back to Top
112.
53
3. Curly braces hold objects
4. Square brackets hold arrays
� Back to Top
113.
54
� Back to Top
117.
function stop() {
clearTimeout(msg);
}
</script>
� Back to Top
118.
55
function start() {
msg = setInterval(greeting, 3000);
function stop() {
clearInterval(msg);
}
</script>
� Back to Top
119.
56
var mainString = "hello",
regex = /hell/;
regex.test(mainString);
� Back to Top
121.
57
8. hash - The anchor portion of the URL
� Back to Top
124.
58
How do you loop through or enumerate javascript object
You can use the for-in loop to loop through javascript object. You can
also make sure that the key you get is an actual property of an object,
and doesn’t come from the prototype using hasOwnProperty method.
var object = {
k1: "value1",
k2: "value2",
k3: "value3",
};
59
What is an arguments object
The arguments object is an Array-like object accessible inside functions
that contains the values of the arguments passed to that function. For
example, let’s see how to use arguments object inside sum function,
function sum() {
var total = 0;
for (var i = 0, len = arguments.length; i < len; ++i) {
total += arguments[i];
}
return total;
}
Pros
1. Works on every environment
2. You can use break and continue flow control statements
60
Cons
1. Too verbose
2. Imperative
3. You might face one-by-off errors
� Back to Top
131.
61
134.
62
Is the !– notation represents a special operator
No,that’s not a special operator. But it is a combination of 2 standard
operators one after the other,
1. A logical not (!)
2. A prefix decrement (–)
At first, the value decremented by one and then tested to see if it is equal
to zero or not for determining the truthy/falsy value.
� Back to Top
137.
63
� Back to Top
140.
fn.name = "John";
What is a polyfill
A polyfill is a piece of JS code used to provide modern functionality on
older browsers that do not natively support it. For example, Silverlight
plugin polyfill can be used to mimic the functionality of an HTML Canvas
element on Microsoft Internet Explorer 7.
� Back to Top
143.
64
What are break and continue statements
The break statement is used to “jump out” of a loop. i.e, 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>";
}
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>";
}
� Back to Top
144.
// Output is:
// "i = 1, j = 0"
// "i = 2, j = 0"
// "i = 2, j = 1"
� Back to Top
65
145.
66
� Back to Top
148.
67
What is tree shaking
Tree shaking is a form of dead code elimination. It means that unused
modules will not be included in the bundle during the build process and for
that it relies on the static structure of ES2015 module syntax,( i.e. import
and export). Initially this has been popularized by the ES2015 module
bundler rollup.
� Back to Top
152.
68
What are the string methods available in Regular expression
Regular Expressions has 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 John";
var n = msg.search(/John/i); // 6
The replace() method is used to return a modified string where the pattern
is replaced.
var msg = "Hello John";
var n = msg.replace(/John/i, "Buttler"); // Hello Buttler
� Back to Top
156.
Modifier Description
i Perform case-insensitive matching
g Perform a global match rather than stops at first match
m Perform multiline matching
69
2. Metacharacters: These are characters with a special meaning For
example, below are some use cases,
1. \d: Used to find a digit
2. \s: Used to find a whitespace character
3. \b: Used to find a match at the beginning or ending of a word
3. Quantifiers: These are useful to define quantities For example, be-
low are some use cases,
1. n+: Used to find matches for any string that contains at least
one n
2. n*: Used to find matches for any string that contains zero or
more occurrences of n
3. n?: Used to find matches for any string that contains zero or one
occurrences of n
� Back to Top
158.
70
� Back to Top
161.
71
What is the purpose of breakpoints in debugging
You can set breakpoints in the javascript code once the debugger state-
ment is executed and the debugger window pops up. At each breakpoint,
javascript will stop executing, and let you examine the JavaScript values.
After examining values, you can resume the execution of code using the
play button.
� Back to Top
165.
72
How do you detect a mobile browser without regexp
You can detect mobile browsers by simply running through a list of devices
and checking if the useragent matches anything. This is an alternative
solution for RegExp usage,
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;
}
}
� Back to Top
168.
73
return xmlHttpReq.responseText;
}
� Back to Top
170.
74
var height =
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
� Back to Top
173.
function traceValue(someParam) {
if (condition1) {
return value1;
} else if (condition2) {
return value2;
} else if (condition3) {
return value3;
} else {
return value4;
75
}
}
� Back to Top
175.
� Back to Top
177.
76
Give an example where do you really need 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
77
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";
Note: It causes a TypeError if the argument passed is not an object.
� Back to Top
179.
78
var language =
(navigator.languages && navigator.languages[0]) || // Chrome / Firefox
navigator.language || // All browsers
navigator.userLanguage; // IE <= 10
console.log(language);
� Back to Top
182.
79
1. Arithmetic Operators: Includes + (Addition),– (Subtraction), *
(Multiplication), / (Division), % (Modulus), + + (Increment) and –
– (Decrement)
2. Comparison Operators: Includes = =(Equal),!= (Not Equal),
===(Equal with type), > (Greater than),> = (Greater than or
Equal to),< (Less than),<= (Less than or Equal to)
3. Logical Operators: Includes &&(Logical AND),||(Logical
OR),!(Logical NOT)
4. Assignment Operators: Includes = (Assignment Operator), +=
(Add and Assignment Operator), – = (Subtract and Assignment Op-
erator), *= (Multiply and Assignment), /= (Divide and Assignment),
%= (Modules and Assignment)
5. Ternary Operators: It includes conditional(: ?) Operator
6. typeof Operator: It uses to find type of variable. The syntax looks
like typeof variable
� Back to Top
185.
80
186.
console.log(calculateSum(...numbers)); // 6
� Back to Top
189.
81
How do you determine whether object is frozen or not
Object.isFrozen() method is used to determine if an object is frozen or
not.An object is frozen if all of the below conditions hold true,
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));
� Back to Top
190.
82
� Back to Top
192.
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.
� Back to Top
193.
83
var handler = {
get: function (obj, prop) {
return prop in obj ? obj[prop] : 100;
},
};
84
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.
� Back to Top
198.
85
Note: The order is not guaranteed as object defined.
� Back to Top
200.
86
const user = {
name: "John",
printInfo: function () {
console.log(`My name is ${this.name}.`);
},
};
admin.name = "Nick"; // Remember that "name" is a property set on "admin" but not on "u
What is a WeakSet
WeakSet is used to store a collection of weakly(weak references) held ob-
jects. The syntax would be as follows,
new WeakSet([iterable]);
Let’s see the below example to explain it’s behavior,
var ws = new WeakSet();
var user = {};
ws.add(user);
ws.has(user); // true
ws.delete(user); // removes user from the set
ws.has(user); // false, user has been removed
� Back to Top
204.
87
� Back to Top
205.
What is a WeakMap
The WeakMap object is a collection of key/value pairs in which the keys
are weakly referenced. In this case, keys must be objects and the values
can be arbitrary values. The syntax is looking like as below,
new WeakMap([iterable]);
Let’s see the below example to explain it’s behavior,
var ws = new WeakMap();
var user = {};
ws.set(user);
ws.has(user); // true
ws.delete(user); // removes user from the map
ws.has(user); // false, user has been removed
� Back to Top
207.
88
What are the differences between WeakMap and Map
The main difference is that references to key objects in Map are strong
while references to key objects in WeakMap are weak. i.e, A key object
in WeakMap can be garbage collected if there is no other reference to it.
Other differences are,
1. Maps can store any key type Whereas WeakMaps can store only
collections of key objects
2. WeakMap does not have size property unlike Map
3. WeakMap does not have methods such as clear, keys, values, entries,
forEach.
4. WeakMap is not iterable.
� Back to Top
208.
89
is not associated with any object. Let’s see the below example to know
more about it’s functionality,
var a = 1;
uneval(a); // returns a String containing 1
uneval(function user() {}); // returns "(function user(){})"
The uneval() function has been deprecated. It is recommended to use
toString() for functions and JSON.toStringify() for other cases.
function user() {}
console.log(user.toString()); // returns "(function user(){})"
� Back to Top
210.
90
How do you print the contents of web page
The window object provided a print() method which is used to print the
contents of the current window. It opens a Print dialog box which lets
you choose between various printing options. Let’s see the usage of print
method in an example,
<input type="button" value="Print" onclick="window.print()" />
Note: In most browsers, it will block while the print dialog is open.
� Back to Top
213.
91
var x = function (a, b) {
return a * b;
};
var z = x(5, 10);
console.log(z); // 50
� Back to Top
215.
92
How do you define property on Object constructor
The Object.defineProperty() static method is used to define a new prop-
erty directly on an object, or modify an existing property on an object, and
returns the object. Let’s see an example to know how to define property,
const newObject = {};
Object.defineProperty(newObject, "newProperty", {
value: 100,
writable: false,
});
console.log(newObject.newProperty); // 100
93
ment, add and subtract properties,
var obj = { counter: 0 };
// Define getters
Object.defineProperty(obj, "increment", {
get: function () {
this.counter++;
},
});
Object.defineProperty(obj, "decrement", {
get: function () {
this.counter--;
},
});
// Define setters
Object.defineProperty(obj, "add", {
set: function (value) {
this.counter += value;
},
});
Object.defineProperty(obj, "subtract", {
set: function (value) {
this.counter -= value;
},
});
obj.add = 10;
obj.subtract = 5;
console.log(obj.increment); //6
console.log(obj.decrement); //5
� Back to Top
221.
94
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
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.
� Back to Top
222.
95
� Back to Top
224.
96
� Back to Top
227.
97
and While Loop comes under this category.
2. Exit Controlled Loops: In this kind of loop type, the test condi-
tion is tested or evaluated at the end of the loop body. i.e, the loop
body will execute at least once irrespective of test condition true or
false. For example, do-while loop comes under this category.
� Back to Top
231.
What is nodejs
Node.js is a server-side platform built on Chrome’s JavaScript runtime for
easily building fast and scalable network applications. It is an event-based,
non-blocking, asynchronous I/O runtime that uses Google’s V8 JavaScript
engine and libuv library.
� Back to Top
232.
What is an Iterator
An iterator is an object which defines a sequence and a return value upon
its termination. It implements the Iterator protocol with a next() method
which returns an object with two properties: value (the next value in the
98
sequence) and done (which is true if the last value in the sequence has
been consumed).
� Back to Top
235.
99
237.
100
The event loop constantly checks whether or not the call stack is empty.
Once the call stack is empty and there is a callback in the event queue,
the event loop moves the callback into the call stack. But if there is a
callback in the microtask queue as well, it is moved first. The microtask
queue has a higher priority than the event queue.
� Back to Top
239.
What is a decorator
A decorator is an expression that evaluates to a function and that takes the
target, name, and decorator descriptor as arguments. Also, it optionally
returns a decorator descriptor to install on the target object. Let’s define
admin decorator for user class at design time,
function admin(isAdmin) {
return function(target) {
target.isAdmin = isAdmin;
}
}
@admin(true)
class User() {
}
console.log(User.isAdmin); //true
@admin(false)
class User() {
}
console.log(User.isAdmin); //false
� Back to Top
240.
101
5. PluralRules: Objects that enable plural-sensitive formatting and
language-specific rules for plurals.
6. RelativeTimeFormat: Objects that enable language-sensitive rel-
ative time formatting.
� Back to Top
241.
var a = "Hello";
var b = +a;
console.log(typeof a, typeof b, b); // string, number, NaN
� Back to Top
242.
102
� Back to Top
244.
console.log(findMin(marks));
console.log(findMax(marks));
� Back to Top
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;
103
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));
� Back to Top
247.
104
<script type="module" src="welcome-module.js"></script>;
console.log(import.meta); // { url: "file:///home/user/welcome-module.js" }
� Back to Top
249.
console.log(x); // 2
� Back to Top
250.
What is typescript
TypeScript is a typed superset of JavaScript created by Microsoft that
adds optional types, classes, async/await, and many other features, and
compiles to plain JavaScript. Angular built entirely in TypeScript and
used as a primary language. You can install it globally as
105
npm install -g typescript
Let’s see a simple example of TypeScript usage,
function greeting(name: string): string {
return "Hello, " + name;
}
console.log(greeting(user));
The greeting method allows only string type as argument.
� Back to Top
252.
� Back to Top
253.
106
� Back to Top
254.
console.log(initObject.a); // John
� Back to Top
255.
console.log(employeeObject.name); // John
� Back to Top
256.
107
}
constructor() { // Uncaught SyntaxError: A class may only have one constructor
this.age = 30;
}
}
console.log(employeeObject.name);
� Back to Top
257.
get area() {
return this.width * this.height;
}
set area(value) {
this.area = value;
}
}
� Back to Top
258.
108
� Back to Top
259.
109
future extensions to the object. Let’s see the usage of this property,
const newObject = {};
Object.preventExtensions(newObject); // NOT extendable
try {
Object.defineProperty(newObject, "newProperty", {
// Adding new property
value: 100,
});
} catch (e) {
console.log(e); // TypeError: Cannot define property newProperty, object is not exten
}
� Back to Top
263.
Object.defineProperties(newObject, {
110
newProperty1: {
value: "John",
writable: true,
},
newProperty2: {},
});
� Back to Top
265.
111
return "\\w+";
};
c = 1;
}
while (c--) {
if (k[c]) {
p = p.replace(new RegExp("\\b" + e(c) + "\\b", "g"), k[c]);
}
}
return p;
})(
"2 1(){0.3('4, 7 6 5 8')}",
9,
9,
"console|greeting|function|log|Hello|JS|to|welcome|world".split("|"),
0,
{}
)
);
� Back to Top
267.
What is Minification
Minification is the process of removing all unnecessary characters(empty
spaces are removed) and variables will be renamed without changing it’s
functionality. It is also a type of obfuscation .
� Back to Top
269.
112
What are the advantages of minification
Normally it is recommended to use minification for heavy traffic and in-
tensive requirements of resources. It reduces file sizes with below benefits,
1. Decreases loading times of a web page
2. Saves bandwidth usages
� Back to Top
270.
� Back to Top
271.
113
<form name="myForm" onsubmit="return validateForm()" method="post">
User name: <input type="text" name="uname" />
<input type="submit" value="Submit" />
</form>
And the validation on user login is below,
function validateForm() {
var x = document.forms["myForm"]["uname"].value;
if (x == "") {
alert("The username shouldn't be empty");
return false;
}
}
� Back to Top
273.
114
document.getElementById("message").innerHTML =
userName.validationMessage;
} else {
document.getElementById("message").innerHTML =
"Entered a valid username";
}
}
� Back to Top
275.
115
277.
What is an enum
An enum is a type restricting variables to one value from a predefined set
of constants. JavaScript has no enums but typescript provides built-in
enum support.
enum Color {
RED, GREEN, BLUE
}
� Back to Top
280.
116
const newObject = {
a: 1,
b: 2,
c: 3,
};
console.log(Object.getOwnPropertyNames(newObject));
["a", "b", "c"];
� Back to Top
281.
117
283.
get area() {
return this.width * this.height;
}
set area(value) {
this.area = value;
}
}
� Back to Top
284.
118
var numericArray = [1, 2, 3, 4];
console.log(numericArray.includes(3)); // true
119
288.
console.log(convertToThousandFormat(12345.6789));
� Back to Top
289.
120
It always calls the second function definition. In this case, namespace will
solve the name collision problem.
� Back to Top
291.
(function () {
function fun1() {
console.log("This is a second definition");
}
fun1();
})();
121
1. Using a block and a let/const declaration: In ECMAScript 6,
you can simply use a block and a let declaration to restrict the scope
of a variable to a block.
{
let myFunction = function fun1() {
console.log("This is a first definition");
};
myFunction();
}
//myFunction(): ReferenceError: myFunction is not defined.
{
let myFunction = function fun1() {
console.log("This is a second definition");
};
myFunction();
}
//myFunction(): ReferenceError: myFunction is not defined.
� Back to Top
292.
122
How do you load CSS and JS files dynamically
You can create both link and script elements in the DOM and append
them as child to head tag. Let’s create a function to add script and style
resources as below,
function loadAssets(filename, filetype) {
if (filetype == "css") {
// External CSS file
var fileReference = document.createElement("link");
fileReference.setAttribute("rel", "stylesheet");
fileReference.setAttribute("type", "text/css");
fileReference.setAttribute("href", filename);
} else if (filetype == "js") {
// External JavaScript file
var fileReference = document.createElement("script");
fileReference.setAttribute("type", "text/javascript");
fileReference.setAttribute("src", filename);
}
if (typeof fileReference != "undefined")
document.getElementsByTagName("head")[0].appendChild(fileReference);
}
� Back to Top
295.
What is jQuery
jQuery is a popular cross-browser JavaScript library that provides Doc-
ument Object Model (DOM) traversal, event handling, animations and
AJAX interactions by minimizing the discrepancies across browsers. It is
widely famous with its philosophy of “Write less, do more”. For example,
you can display welcome message on the page load using jQuery as below,
123
$(document).ready(function () {
// It selects the document and apply the function on page load
alert("Welcome to jQuery world");
});
Note: You can download it from jquery’s official site or install it from
CDNs, like google.
� Back to Top
297.
124
Note: This operator is often used to obtain the undefined primitive value,
using “void(0)”.
� Back to Top
300.
125
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.
� Back to Top
303.
126
9. Enhanced Object Literals
10. Promises
11. Classes
12. Modules
� Back to Top
305.
What is ES6
ES6 is the sixth edition of the javascript language and it was released
in June 2015. It was initially known as ECMAScript 6 (ES6) and later
renamed to ECMAScript 2015. Almost all the modern browsers support
ES6 but for the old browsers there are many transpilers, like Babel.js etc.
� Back to Top
306.
127
myFunc();
alert(name);
� Back to Top
307.
console.log(calculateArea()); //300
� Back to Top
309.
128
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,
var greeting = `Welcome to JS World, Mr. ${firstName} ${lastName}.`;
In ES5, you need break string like below,
var greeting = 'Welcome to JS World, Mr. ' + firstName + ' ' + lastName.`
Note: You can use multi-line strings and string interpolation features
with template literals.
� Back to Top
310.
129
//Without nesting templates
const iconStyles = `icon ${
isMobilePlatform()
? ""
: user.isAuthorized
? "icon-submit"
: "icon-disabled"
}`;
� Back to Top
312.
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}`;
}
130
var output1 = myInfoTag`Mr/Ms. ${user1} is a/an ${experience1} in ${skill1}`;
var output2 = myInfoTag`Mr/Ms. ${user2} is a/an ${experience2} in ${skill2}`;
console.log(one); // "JAN"
131
console.log(two); // "FEB"
console.log(three); // "MARCH"
and you can get user properties of an object using destructuring assign-
ment,
var { name, age } = { name: "John", age: 32 };
console.log(name); // John
console.log(age); // 32
� Back to Top
315.
[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
� Back to Top
316.
132
[x, y] = [y, x];
console.log(x); // 20
console.log(y); // 10
� Back to Top
317.
133
1. Import a module on-demand or conditionally. For example, if you
want to load a polyfill on legacy browser
if (isLegacyBrowser()) {
import(···)
.then(···);
}
1. Compute the module specifier at runtime. For example, you can use
it for internationalization.
import(`messages_${getLocale()}.js`).then(···);
1. Import a module from within a regular script instead a module.
� Back to Top
320.
134
5. Nested virtualization
� Back to Top
322.
What is collation
Collation is used for sorting a set of strings and searching within a set of
strings. It is parameterized by locale and aware of Unicode. Let’s take
comparison and sorting features,
1. Comparison:
var list = ["ä", "a", "z"]; // In German, "ä" sorts with "a" Whereas in Swedish, "ä" s
var l10nDE = new Intl.Collator("de");
var l10nSV = new Intl.Collator("sv");
console.log(l10nDE.compare("ä", "z") === -1); // true
console.log(l10nSV.compare("ä", "z") === +1); // true
1. Sorting:
var list = ["ä", "a", "z"]; // In German, "ä" sorts with "a" Whereas in Swedish, "ä" s
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", "ä" ]
� Back to Top
323.
135
What is the output of below spread operator array
[..."John Resig"];
The output of the array is [‘J’, ‘o’, ‘h’, ‘n’, ’‘, ’R’, ‘e’, ‘s’, ‘i’, ‘g’] Expla-
nation: 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.
� Back to Top
325.
Is PostMessage secure
Yes, postMessages can be considered very secure as long as the program-
mer/developer is careful about checking the origin and source of an arriv-
ing message. But if you try to send/receive a message without verifying
its source will create cross-site scripting attacks.
� Back to Top
326.
136
//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);
}
});
� Back to Top
328.
Is postMessages synchronous
The postMessages are synchronous in IE8 browser but they are asyn-
chronous in IE9 and all other modern browsers (i.e, IE9+, Firefox, Chrome,
Safari).Due to this asynchronous behaviour, we use a callback mechanism
when the postMessage is returned.
� Back to Top
330.
137
� Back to Top
332.
138
� Back to Top
336.
What is ArrayBuffer
An ArrayBuffer object is used to represent a generic, fixed-length raw
binary data buffer. You can create it as below,
let buffer = new ArrayBuffer(16); // create a buffer of length 16
alert(buffer.byteLength); // 16
To manipulate an ArrayBuffer, we need to use a “view” object.
//Create a DataView referring to the buffer
let view = new DataView(buffer);
� Back to Top
337.
139
� Back to Top
339.
What are the list of cases error thrown from non-strict mode to
strict mode
When you apply ‘use strict’; syntax, some of the below cases will throw a
SyntaxError before executing the script
1. When you use Octal syntax
var n = 022;
1. Using with statement
2. When you use delete operator on a variable name
3. Using eval or arguments as variable or function argument name
4. When you use newly reserved keywords
5. When you declare a function in a block
if (someCondition) {
function f() {}
}
Hence, the errors from above cases are helpful to avoid errors in develop-
ment/production environments.
� Back to Top
341.
140
Do all objects have prototypes
No. All objects have prototypes except for the base object which is created
by the user, or an object that is created using the new keyword.
� Back to Top
342.
141
var veggies = ["Tomato", "Carrot", "Cabbage"];
var fruits = ["Apple", "Orange", "Pears"];
var veggiesAndFruits = veggies.concat(fruits);
console.log(veggiesAndFruits); // Tomato, Carrot, Cabbage, Apple, Orange, Pears
� Back to Top
345.
142
var empDetailsDeepCopy = {
name: empDetails.name,
age: empDetails.age,
expertise: empDetails.expertise,
};
Now if you change empDetailsDeepCopy.name, it will only affect
empDetailsDeepCopy & not empDetails
� Back to Top
346.
console.log(greetingList[0]); //Hello1
console.log(greetingList[1]); //Hello2
console.log(greetingList[2]); //Hello3
� Back to Top
348.
143
string then you can use trimStart/trimLeft and trimEnd/trimRight
methods. Let’s see an example of these methods on a greeting message,
var greeting = " Hello, Goodmorning! ";
144
},
sayBye() {
alert(`Bye ${this.name}`);
},
};
// usage:
class User {
constructor(name) {
this.name = name;
}
}
thunk(); // 5
� Back to Top
352.
145
}
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 func-
tion 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.
� Back to Top
353.
146
How to remove all line breaks from a string
The easiest approach is using regular expressions to detect and replace
newlines in the string. In this case, we use replace function along with
string to replace with, which in our case is an empty string.
function remove_linebreaks( var message ) {
return message.replace( /[\r\n]+/gm, "" );
}
In the above expression, g and m are for global and multiline flags.
� Back to Top
355.
147
console.log(["a"] + ["b"]); // "ab"
console.log([] + []); // ""
console.log(![] + []); // "false", because ![] returns false.
� Back to Top
358.
148
(![] + [])[+[]]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(![]+[])[+!+[]+!+[]+!+[]]+(![]+[])[+!+[]+!+[]+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]+(![]+[])[
� Back to Top
360.
How do you map the array values without using map method
You can map the array values without using the map method by just using
the from method of Array. Let’s map city names from Countries array,
149
const countries = [
{ name: "India", capital: "Delhi" },
{ name: "US", capital: "Washington" },
{ name: "Russia", capital: "Moscow" },
{ name: "Singapore", capital: "Singapore" },
{ name: "China", capital: "Beijing" },
{ name: "France", capital: "Paris" },
];
150
How do you create an array with some data
You can create an array with some data or an array with the same values
using fill method.
var newArray = new Array(5).fill("0");
console.log(newArray); // ["0", "0", "0", "0", "0"]
� Back to Top
368.
151
What is the purpose of dir method of console object
The console.dir() is used to display an interactive list of the properties
of the specified JavaScript object as JSON.
const user = { name: "John", id: 1, city: "Delhi" };
console.dir(user);
The user object displayed in JSON representation Screenshot
� Back to Top
371.
152
How do you verify that an argument is a Number or not
The combination of IsNaN and isFinite methods are used to confirm
whether an argument is a number or not.
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
� Back to Top
374.
153
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,
Also you can use the flat method of Array.
const arr = [1, [2, 3], 4, 5, [6, 7]];
const fllattenArr = arr.flat(); // [1, 2, 3, 4, 5, 6, 7]
154
How do you capture browser back button
The beforeunload event is triggered when the window, the document and
its resources are about to be unloaded. This event is helpful to warn users
about losing the current data and detect back button event.
window.addEventListener('beforeunload', () => {
console.log('Clicked browser back button');
});
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 c
155
let name = "john";
What is AJAX
AJAX stands for Asynchronous JavaScript and XML and it is a group of
related technologies(HTML, CSS, JavaScript, XMLHttpRequest API etc)
used to display data asynchronously. i.e. We can send data to the server
and get data from the server without reloading the web page.
� Back to Top
382.
156
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!
}
});
157
recognition.start();
In this API, browser is going to ask you for permission to use your micro-
phone
1. SpeechSynthesis (Text-to-Speech): It provides the ability to rec-
ognize voice context from an audio input and respond. This is ac-
cessed by the SpeechSynthesis interface. For example, the below
code is used to get voice/speech from text,
if ("speechSynthesis" in window) {
var speech = new SpeechSynthesisUtterance("Hello World!");
speech.lang = "en-US";
window.speechSynthesis.speak(speech);
}
The above examples can be tested on chrome(33+) browser’s developer
console. Note: This API is still a working draft and only available in
Chrome and Firefox browsers(ofcourse Chrome only implemented the spec-
ification)
� Back to Top
385.
158
function runMeFirst() {
console.log("My script is initialized");
}
runMeFirst();
console.log("Script loaded");
and the output is,
My script is initialized
Script loaded
� Back to Top
386.
What is microtask
Microtask is the javascript code which needs to be executed immediately
after the currently executing task/microtask is completed. They are kind
of blocking in nature. i.e, The main thread will be blocked until the micro-
task queue is empty. The main sources of microtasks are Promise.resolve,
Promise.reject, MutationObservers, IntersectionObservers etc
159
Note: All of these microtasks are processed in the same turn of the event
loop. � Back to Top
389.
- The Node.js Event Loop is used in server-side JavaScript applications and is responsible f
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 call-
backs.
� Back to Top
391.
160
How do you use javascript libraries in typescript file
It is known that not all JavaScript libraries or frameworks have TypeScript
declaration files. But if you still want to use libraries or frameworks in
our TypeScript files without getting compilation errors, the only solution
is declare keyword along with a variable declaration. For example, let’s
imagine you have a library called customLibrary that doesn’t have a
TypeScript declaration and have a namespace called customLibrary in
the global namespace. You can use this library in typescript code as
below,
declare var customLibrary;
In the runtime, typescript will provide the type to the customLibrary
variable as any type. The another alternative without using declare key-
word is below
var customLibrary: any;
� Back to Top
392.
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
� Back to Top
393.
What is heap
Heap(Or memory heap) is the memory location where objects are stored
when we define variables. i.e, This is the place where all the memory
161
allocations and de-allocation take place. Both heap and call-stack are two
containers of JS runtime. Whenever runtime comes across variables and
function declarations in the code it stores them in the Heap.
Screenshot
� Back to Top
394.
162
How do you detect primitive or non primitive value type
In JavaScript, primitive types include boolean, string, number, BigInt,
null, Symbol and undefined. Whereas non-primitive types include the
Objects. But you can easily identify them with the below function,
var myPrimitive = 30;
var myNonPrimitive = {};
function isPrimitive(val) {
return Object(val) !== val;
}
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.
� Back to Top
398.
What is babel
Babel is a JavaScript transpiler to convert ECMAScript 2015+ code into a
backwards compatible version of JavaScript in current and older browsers
or environments. Some of the main features are listed below,
1. Transform syntax
2. Polyfill features that are missing in your target environment (using
@babel/polyfill)
3. Source code transformations (or codemods)
� Back to Top
399.
163
What are the common use cases of observables
Some of the most common use cases of observables are web sockets with
push notifications, user input changes, repeating intervals, etc
� Back to Top
401.
What is RxJS
RxJS (Reactive Extensions for JavaScript) is a library for implementing
reactive programming using observables that makes it easier to compose
asynchronous or callback-based code. It also provides utility functions for
creating and working with observables.
� Back to Top
402.
164
403.
array.length = 2;
console.log(array.length); // 2
console.log(array); // [1,2]
and the array can be emptied too
var array = [1, 2, 3, 4, 5];
array.length = 0;
console.log(array.length); // 0
console.log(array); // []
� Back to Top
405.
What is an observable
An Observable is basically a function that can return a stream of values
either synchronously or asynchronously to an observer over time. The
consumer can get the value by calling subscribe() method. Let’s look at
a simple example of an Observable
165
import { Observable } from "rxjs";
class User {}
Constructor Function:
const user = new User(); // No error
function User() {}
� Back to Top
407.
166
console.log(data);
}
logger();
It is basically syntax sugar over ES2015 promises and generators.
� Back to Top
408.
Promise.reject("error value").catch(function () {
throw new Error("error");
});
167
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 un-
handled rejections
Promise.onPossiblyUnhandledRejection(function (error) {
throw error;
});
and discard a rejection, just handle it with an empty catch
Promise.reject("error value").catch(function () {});
� Back to Top
409.
What is deno
Deno is a simple, modern and secure runtime for JavaScript and Type-
Script that uses V8 JavaScript engine and the Rust programming lan-
guage.
� Back to Top
168
410.
169
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false}
console.log(iterator.next()); // {value: undefined, done: true}
� Back to Top
411.
170
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
Another way is to check for .then() handler type
function isPromise(value) {
return Boolean(value && typeof value.then === "function");
}
var i = 1;
var promise = new Promise(function (resolve, reject) {
resolve();
});
console.log(isPromise(i)); // false
console.log(isPromise(promise)); // true
� Back to Top
413.
171
}
What are the differences between spread operator and rest pa-
rameter
Rest parameter collects all remaining elements into an array. Whereas
Spread operator allows iterables( arrays / objects / strings ) to be ex-
panded into single arguments/elements. i.e, Rest parameter is opposite to
the spread operator.
� Back to Top
416.
172
}
const genObj = myGenFunc();
2. Generator function expressions:
const myGenFunc = function* () {
yield 1;
yield 2;
yield 3;
};
const genObj = myGenFunc();
3. Generator method definitions in object literals:
const myObj = {
*myGeneratorMethod() {
yield 1;
yield 2;
yield 3;
},
};
const genObj = myObj.myGeneratorMethod();
4. Generator method definitions in class:
class MyClass {
*myGeneratorMethod() {
yield 1;
yield 2;
yield 3;
}
}
const myObject = new MyClass();
const genObj = myObject.myGeneratorMethod();
5. Generator as a computed property:
const SomeObj = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
},
};
console.log(Array.from(SomeObj)); // [ 1, 2, 3 ]
� Back to Top
417.
173
What are the built-in iterables
Below are the list of built-in iterables in javascript,
1. Arrays and TypedArrays
2. Strings: Iterate over each character or Unicode code-points
3. Maps: iterate over its key-value pairs
4. Sets: iterates over their elements
5. arguments: An array-like special variable in functions
6. DOM collection such as NodeList
� Back to Top
418.
arr.newProp = "newVlue";
174
How do you define instance and non-instance properties
The Instance properties must be defined inside of class methods. For
example, name and age properties defined inside constructor as below,
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
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;
� Back to Top
420.
175
void (function (dt) {
console.log(dt.toLocaleTimeString());
})(new Date());
� Back to Top
422.
176
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"
);
� Back to Top
425.
// Nested Group
console.group("Address");
console.log("Street: Commonwealth");
console.log("City: Los Angeles");
console.log("State: California");
177
// Close outer group
console.groupEnd();
You can also use console.groupCollapsed() instead of console.group()
if you want the groups to be collapsed by default.
� Back to Top
427.
178
const justiceLeague = ["Superman", "Aquaman", "Batman"];
delete justiceLeague[1];
console.log(justiceLeague); // ['Superman', empty, ,'Batman']
4. Increase length property: Increasing length property of an array
const justiceLeague = ["Superman", "Aquaman", "Batman"];
justiceLeague.length = 5;
console.log(justiceLeague); // ['Superman', 'Aquaman', 'Batman', empty, empty]
� Back to Top
429.
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
179
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.
const originalArray = [1, 2, 3, 4, 5];
const newArray = [...originalArray].reverse();
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [ 5, 4, 3, 2, 1]
3. Using reduce and spread methods: Here execute a reducer func-
tion on an array elements and append the accumulated array on right
side using spread syntax
const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.reduce((accumulator, value) => {
return [value, ...accumulator];
}, []);
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [ 5, 4, 3, 2, 1]
4. Using reduceRight and spread methods: Here execute a right
reducer function(i.e. opposite direction of reduce method) on an array
elements and append the accumulated array on left side using spread
syntax
const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.reduceRight((accumulator, value) => {
return [...accumulator, value];
}, []);
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
const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.reduceRight((accumulator, value) => {
accumulator.push(value);
return accumulator;
}, []);
180
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [ 5, 4, 3, 2, 1]
� Back to Top
431.
function A() {
console.log("Start function A");
181
function B() {
console.log("In function B");
}
B();
}
A();
console.log("GlobalContext");
� Back to Top
433.
What is debouncing?
Debouncing is a programming pattern that allows delaying execution of
some piece of code until a specified time to avoid unnecessary CPU cycles,
API calls and improve performance. The debounce function make sure
that your code is only triggered once per user input. The common usecases
are Search box suggestions, text-field auto-saves, and eliminating double-
button clicks.
Let’s say you want to show suggestions for a search query, but only after
a visitor has finished typing it. So here you write a debounce function
where the user keeps writing the characters with in 500ms then previous
timer cleared out using clearTimeout and reschedule API call/DB query
for a new time—300 ms in the future.
function debounce(func, timeout = 500) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, timeout);
182
};
}
function fetchResults() {
console.log("Fetching input suggestions");
}
const processChange = debounce(() => fetchResults());
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);
� Back to Top
435.
What is throttling?
Throttling is a technique used to limit the execution of an event handler
function, even when this event triggers continuously due to user actions.
The common use cases are browser resizing, window scrolling etc.
The below example creates a throttle function to reduce the number of
events for each pixel change and trigger scroll event for each 100ms except
for the first event.
const throttle = (func, limit) => {
let inThrottle;
return (...args) => {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
};
window.addEventListener("scroll", () => {
throttle(handleScrollAnimation, 100);
});
� Back to Top
436.
183
What is optional chaining?
According to MDN official docs, the optional chaining operator (?.) per-
mits reading the value of a property located deep within a chain of con-
nected objects without having to expressly validate that each reference in
the chain is valid.
The ?. operator is like the . chaining operator, except that instead of
causing an error if a reference is nullish (null or undefined), the expression
short-circuits with a return value of undefined. When used with function
calls, it returns undefined if the given function does not exist.
const adventurer = {
name: "Alice",
cat: {
name: "Dinah",
},
};
console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined
� Back to Top
437.
184
How to verify if a variable is an array?
It is possible to check if a variable is an array instance using 3 different
ways,
1. Array.isArray() method:
The Array.isArray(value) utility function is used to determine
whether value is an array or not. This function returns a true boolean
value if the variable is an array and a false value if it is not.
const numbers = [1, 2, 3];
const user = { name: "John" };
Array.isArray(numbers); // true
Array.isArray(user); //false
2. instanceof operator:
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
3. Checking constructor type:
The constructor property of the variable is used to determine whether
the variable Array type or not.
const numbers = [1, 2, 3];
const user = { name: "John" };
console.log(numbers.constructor === Array); // true
console.log(user.constructor === Array); // false
� Back to Top
439.
185
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;
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
� Back to Top
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 in-
order to use it as other builtin functions. This custom function should
186
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);
};
};
� Back to Top
442.
� Back to Top
445.
187
multiplyBy2(add(2, 3));
� Back to Top
446.
188
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.
� Back to Top
449.
189
var output_final = square(double(2));
console.log(output_final);
� Back to Top
450.
Coding Exercise
1. What is the output of below code
var car = new Vehicle("Honda", "white", "2010", "UK");
console.log(car);
190
� Back to Top
Answer: 3 Of course the return value of foo() is 1 due to the increment op-
erator. But the statement let x = y = 0 declares a local variable x. Whereas
y declared as a global variable accidentally. This statement is equivalent to,
let x;
window.y = 0;
x = window.y;
Since the block scoped variable x is undefined outside of the function, the type
will be undefined too. Whereas the global variable y is available outside the
function, the value is 0 and type is number.
� Back to Top
191
• 4: A, C and B
Answer
Answer: 4 The statements order is based on the event loop mechanism. The
order of statements follows the below order,
1. At first, the main function is pushed to the stack.
2. Then the browser pushes the first statement of the main function( i.e, A’s
console.log) to the stack, executing and popping out immediately.
3. But setTimeout statement moved to Browser API to apply the delay for
callback.
4. In the meantime, C’s console.log added to stack, executed and popped
out.
5. The callback of setTimeout moved from Browser API to message queue.
6. The main function popped out from stack because there are no statements
to execute
7. The callback moved from message queue to the stack since the stack is
empty.
8. The console.log for B is added to the stack and display on the console.
� Back to Top
Answer: 1 This is due to the float point math problem. Since the float-
ing point numbers are encoded in binary format, the addition operations on
them lead to rounding errors. Hence, the comparison of floating points doesn’t
give expected results. You can find more details about the explanation here
0.30000000000000004.com/
� Back to Top
192
}
console.log(y);
• 1: 1function
• 2: 1object
• 3: ReferenceError
• 4: 1undefined
Answer
� Back to Top
193
colon, it is automatically inserted immediately. Hence, the function returned as
undefined.
Whereas if the opening curly brace is along with the return keyword then the
function is going to be returned as expected.
function foo() {
return {
message: "Hello World",
};
}
console.log(foo()); // {message: "Hello World"}
� Back to Top
Answer: 3 The delete operator will delete the object property but it will
not reindex the array or change its length. So the number or elements or length
of the array won’t be changed. If you try to print myChars then you can observe
that it doesn’t set an undefined value, rather the property is removed from the
array. The newer versions of Chrome use empty instead of undefined to make
the difference a bit clearer.
� Back to Top
194
console.log(array2);
Answer: 2 The latest chrome versions display sparse array(they are filled
with holes) using this empty x n notation. Whereas the older versions have
undefined x n notation. Note: The latest version of FF displays n empty
slots notation.
� Back to Top
console.log(obj.prop1());
console.log(obj.prop2());
console.log(obj.prop3());
• 1: 0, 1, 2
• 2: 0, { return 1 }, 2
• 3: 0, { return 1 }, { return 2 }
• 4: 0, 1, undefined
Answer
195
� Back to Top
Answer: 2 The important point is that if the statement contains the same
operators(e.g, < or >) then it can be evaluated from left to right. The first
statement follows the below order,
1. console.log(1 < 2 < 3);
2. console.log(true < 3);
3. console.log(1 < 3); // True converted as 1 during comparison
4. True
Whereas the second statement follows the below order,
1. console.log(3 > 2 > 1);
2. console.log(true > 1);
3. console.log(1 > 1); // False converted as 0 during comparison
4. False
� Back to Top
196
Answer: 2 In non-strict mode, the regular JavaScript functions allow dupli-
cate named parameters. The above code snippet has duplicate parameters on
1st and 3rd parameters. The value of the first parameter is mapped to the third
argument which is passed to the function. Hence, the 3rd argument overrides
the first parameter.
Note: In strict mode, duplicate parameters will throw a Syntax Error.
� Back to Top
Answer: 3 Unlike regular functions, the arrow functions doesn’t not al-
low duplicate parameters in either strict or non-strict mode. So you can see
SyntaxError in the console.
� Back to Top
197
variable is not defined outside of the arrow function. Hence, you will receive a
reference error.
Where as the normal function provides the number of arguments passed to the
function
const func = function () {
return arguments.length;
};
console.log(func(1, 2, 3));
But If you still want to use an arrow function then rest operator on arguments
provides the expected arguments
const arrowFunc = (...args) => args.length;
console.log(arrowFunc(1, 2, 3));
� Back to Top
� Back to Top
198
Answer: 4 -Infinity is the initial comparant because almost every other value
is bigger. So when no arguments are provided, -Infinity is going to be returned.
Note: Zero number of arguments is a valid case.
� Back to Top
� Back to Top
199
� Back to Top
� Back to Top
200
• 2: {1, 2, 3, 4}, {“F”, “i”, “r”, “e”, “o”, “x”}
• 3: [1, 2, 3, 4], [“F”, “i”, “r”, “e”, “o”, “x”]
• 4: {1, 1, 2, 3, 4}, {“F”, “i”, “r”, “e”, “f”, “o”, “x”}
Answer
� Back to Top
Answer: 2 JavaScript follows IEEE 754 spec standards. As per this spec,
NaNs are never equal for floating-point numbers.
� Back to Top
201
let numbers = [1, 2, 3, 4, NaN];
console.log(numbers.findIndex(Number.isNaN)); // 4
console.log(numbers.includes(NaN)); // true
� Back to Top
Answer: 3 When using rest parameters, trailing commas are not allowed and
will throw a SyntaxError. If you remove the trailing comma then it displays 1st
answer
let [a, ...b] = [1, 2, 3, 4, 5];
console.log(a, b); // 1, [2, 3, 4, 5]
� Back to Top
Answer: 1 Async functions always return a promise. But even if the re-
turn value of an async function is not explicitly a promise, it will be implicitly
wrapped in a promise. The above async function is equivalent to below expres-
sion,
202
function func() {
return Promise.resolve(10);
}
� Back to Top
� Back to Top
203
})
}
processArray([1, 2, 3, 4]);
• 1: SyntaxError
• 2: 1, 2, 3, 4
• 3: 4, 4, 4, 4
• 4: 4, 3, 2, 1
Answer
� Back to Top
Answer: 4 The forEach method will not wait until all items are finished but
it just runs the tasks and goes next. Hence, the last statement is displayed first
followed by a sequence of promise resolutions.
204
But you control the array sequence using for..of loop,
async function processArray(array) {
for (const item of array) {
await delayedLog(item);
}
console.log("Process completed!");
}
� Back to Top
� Back to Top
205
Answer: 3 Symbol follows below conventions,
1. Every symbol value returned from Symbol() is unique irrespective of the
optional string.
2. Symbol.for() function creates a symbol in a global symbol registry list.
But it doesn’t necessarily create a new symbol on every call, it checks
first if a symbol with the given key is already present in the registry and
returns the symbol if it is found. Otherwise a new symbol created in the
registry.
Note: The symbol description is just useful for debugging purposes.
� Back to Top
� Back to Top
206
console.log("It is a number!");
}
• 1: SyntaxError
• 2: It is not a string!, It is not a number!
• 3: It is not a string!, It is a number!
• 4: It is a string!, It is a number!
Answer
� Back to Top
207
2. All Symbol-keyed properties will be completely ignored. Hence it returns
an empty object({}).
� Back to Top
class B extends A {
constructor() {
super();
}
}
new A();
new B();
• 1: A, A
• 2: A, B
Answer
� Back to Top
208
Answer: 4 It throws a syntax error because the rest element should not have
a trailing comma. You should always consider using a rest operator as the last
element.
� Back to Top
console.log(x);
console.log(y);
• 1: 30, 20
• 2: 10, 20
• 3: 10, undefined
• 4: 30, undefined
Answer
� Back to Top
area();
• 1: 200
• 2: Error
• 3: undefined
• 4: 0
Answer
209
Answer: 2 If you leave out the right-hand side assignment for the destructur-
ing object, the function will look for at least one argument to be supplied when
invoked. Otherwise you will receive an error Error: Cannot read property
'length' of undefined as mentioned above.
You can avoid the error with either of the below changes,
1. Pass at least an empty object:
function area({ length = 10, width = 20 }) {
console.log(length * width);
}
area({});
2. Assign default empty object:
function area({ length = 10, width = 20 } = {}) {
console.log(length * width);
}
area();
� Back to Top
210
� Back to Top
checkType();
checkType(undefined);
checkType("");
checkType(null);
• 1: number, undefined, string, object
• 2: undefined, undefined, string, object
• 3: number, number, string, object
• 4: number, number, number, number
Answer
� Back to Top
console.log(add("Orange"));
console.log(add("Apple"));
• 1: [‘Orange’], [‘Orange’, ‘Apple’]
• 2: [‘Orange’], [‘Apple’]
Answer
211
Answer: 2 Since the default argument is evaluated at call time, a new object
is created each time the function is called. So in this case, the new array is
created and an element pushed to the default empty array.
� Back to Top
greet("Hello", "John");
greet("Hello", "John", "Good morning!");
• 1: SyntaxError
• 2: [‘Hello’, ‘John’, ‘Hello John’], [‘Hello’, ‘John’, ‘Good morning!’]
Answer
� Back to Top
Answer: 1 The functions and variables declared in the function body cannot
be referred from default value parameter initializers. If you still try to access,
it throws a run-time ReferenceError(i.e, inner is not defined).
� Back to Top
212
43. What is the output of below code
function myFun(x, y, ...manyMoreArgs) {
console.log(manyMoreArgs);
}
myFun(1, 2, 3, 4, 5);
myFun(1, 2);
• 1: [3, 4, 5], undefined
• 2: SyntaxError
• 3: [3, 4, 5], []
• 4: [3, 4, 5], [undefined]
Answer
� Back to Top
� Back to Top
213
yield 3;
}
var myGenObj = new myGenFunc();
console.log(myGenObj.next().value);
• 1: 1
• 2: undefined
• 3: SyntaxError
• 4: TypeError
Answer
Answer: 4 Generators are not constructible type. But if you still proceed to
do, there will be an error saying “TypeError: myGenFunc is not a constructor”
� Back to Top
214
� Back to Top
Answer: 4 The generator should not be re-used once the iterator is closed.
i.e, Upon exiting a loop(on completion or using break & return), the generator
is closed and trying to iterate over it again does not yield any more results.
Hence, the second loop doesn’t print any value.
� Back to Top
215
� Back to Top
class Square {
constructor(length) {
this.length = length;
}
get area() {
return this.length * this.length;
}
set area(value) {
this.area = value;
}
}
• 1: 100
• 2: ReferenceError
Answer
� Back to Top
Person.prototype.walk = function () {
return this;
};
Person.run = function () {
return this;
};
216
let user = new Person();
let walk = user.walk;
console.log(walk());
� Back to Top
start() {
console.log(`${this.name} vehicle started`);
}
}
217
• 4: BMW car started, BMW car started
Answer
� Back to Top
� Back to Top
Answer: 2 Emojis are unicodes and the unicode for smile symbol is
“U+1F642”. The unicode comparision of same emojies is equivalent to string
comparison. Hence, the output is always true.
� Back to Top
218
54. What is the output of below code?
console.log(typeof typeof typeof true);
• 1: string
• 2: boolean
• 3: NaN
• 4: number
Answer
� Back to Top
if (zero) {
console.log("If");
} else {
console.log("Else");
}
• 1: If
• 2: Else
• 3: NaN
• 4: SyntaxError
Answer
Answer: 1
1. The type of operator on new Number always returns object. i.e, typeof
new Number(0) –> object.
2. Objects are always truthy in if block
Hence the above code block always goes to if section.
� Back to Top
219
let msg = "Good morning!!";
msg.name = "John";
console.log(msg.name);
• 1: “”
• 2: Error
• 3: John
• 4: Undefined
Answer
Answer: 4 It returns undefined for non-strict mode and returns Error for
strict mode. In non-strict mode, the wrapper object is going to be created and
get the mentioned property. But the object get disappeared after accessing the
property in next line.
� Back to Top
(function innerFunc() {
if (count === 10) {
let count = 11;
console.log(count);
}
console.log(count);
})();
• 1: 11, 10
• 2: 11, 11
• 3: 10, 11
• 4: 10, 10
Answer
220
� Back to Top
� Back to Top
console.log(arr == str);
• 1: false
• 2: Error
• 3: true
Answer
� Back to Top
221
59. What is the output of below code?
getMessage();
Answer: 2 Hoisting will move variables and functions to be the top of scope.
Even though getMessage is an arrow function the above function will considered
as a varible due to it’s variable declaration or assignment. So the variables will
have undefined value in memory phase and throws an error ‘getMessage is not
a function’ at the code execution phase.
� Back to Top
console.log("program finished");
• 1: program finished
• 2: Cannot predict the order
• 3: program finished, promise finished
• 4: promise finished, program finished
Answer
� Back to Top
222
61. What is the output of below code?
console
.log("First line")
[("a", "b", "c")].forEach((element) => console.log(element));
console.log("Third line");
• 1: First line, then print a, b, c in a new line, and finally print Third
line as next line
• 2: First line, then print a, b, c in a first line, and print Third line
as next line
• 3: Missing semi-colon error
• 4: Cannot read properties of undefined
Answer
� Back to Top
223
"b",
"c",
"d",
"e",
"f",
];
const HEX_PREFIX = "#";
const HEX_LENGTH = 6;
function generateRandomHex() {
let randomHex = "";
function generateRandomHex() {
return (
HEX_PREFIX +
Math.floor(Math.random() * 0xffffff)
.toString(HEX_RADIX)
.padStart(HEX_LENGTH, "0")
);
}
� Back to Top
224
• 3: SyntaxError: Identifier ‘of’ has already been declared
• 4: ReferenceError: of is not defined
Answer
� Back to Top
� Back to Top
225
65. What is the output order of below code?
setTimeout(() => {
console.log("1");
}, 0);
Promise.resolve("hello").then(() => console.log("2"));
console.log("3");
• 1: 1, 2, 3
• 2: 1, 3, 2
• 3: 3, 1, 2
• 4: 3, 2, 1
Answer
Answer: 4 When the JavaScript engine parses the above code, the first two
statements are asynchronous which will be executed later and third statement is
synchronous statement which will be moved to callstack, executed and prints the
number 3 in the console. Next, Promise is native in ES6 and it will be moved to
Job queue which has high priority than callback queue in the execution order. At
last, since setTimeout is part of WebAPI the callback function moved to callback
queue and executed. Hence, you will see number 2 printed first followed by 1.
� Back to Top
226
console.log(name);
console.log(message());
var name = 'John';
var message = function () {
console.log('Hello John: Welcome');
});
� Back to Top
function message() {
console.log("Hello");
}
function message() {
console.log("Bye");
}
• 1: Reference error: message is not defined
• 2: Hello
• 3: Bye
• 4: Compile time error
Answer
� Back to Top
changeCurrentCity();
• 1: NewYork, Singapore
227
• 2: NewYork, NewYork
• 3: undefined, Singapore
• 4: Singapore, Singapore
Answer
Answer: 3 Due to hositing feature, the variables declared with var will have
undefined value in the creation phase so the outer variable currentCity will
get same undefined value. But after few lines of code JavaScript engine found
a new function call(changeCurrentCity()) to update the current city with var
re-declaration. Since each function call will create a new execution context,
the same variable will have undefined value before the declaration and new
value(Singapore) after the declarion. Hence, the value undefined print first
followed by new value Singapore in the execution phase.
� Back to Top
function first() {
var message = "first";
second();
console.log(message);
}
228
� Back to Top
� Back to Top
229
function so this keyword refers to user object but eatFruit has been invoked
by eat function and this will have default Window object.
The above pit fall fixed by three ways,
1. In ES6, the arrow function will make this keyword as lexically scoped.
Since the surrounding object of this object is user object, the eatFruit
function will contain user object for this object.
const user = {
name: "John",
eat() {
console.log(this);
var eatFruit = () => {
console.log(this);
};
eatFruit();
},
};
user.eat();
The next two solutions have been used before ES6 introduced.
2. It is possible create a reference of this into a separate variable and use
that new variable inplace of this keyword inside eatFruit function. This
is a common practice in jQuery and AngularJS before ES6 introduced.
const user = {
name: "John",
eat() {
console.log(this);
var self = this;
var eatFruit = () => {
console.log(self);
};
eatFruit();
},
};
user.eat();
3. The eatFruit function can bind explicitly with this keyword where it
refers Window object.
const user = {
name: "John",
eat() {
console.log(this);
var eatFruit = function () {
console.log(this);
};
230
return eatFruit.bind(this);
},
};
user.eat()();
� Back to Top
� Back to Top
let user2 = {
name: "Jacob",
age: 28,
};
231
console.log(user1 === user2);
• 1: True
• 2: False
• 3: Compile time error
Answer
� Back to Top
� Back to Top
232
const a = new Number(10);
const b = 10;
console.log(a === b);
• 1: False
• 2: True
Answer
Answer: 1 Eventhough both variables a and b refer a number value, the first
declaration is based on constructor function and the type of the variable is going
to be object type. Whereas the second declaration is primitive assignment with
a number and the type is number type. Hence, the equality operator === will
output false value.
� Back to Top
Answer: 2 Eventhough the above function returns the same result for the
same arguments(input) that are passed in the function, the console.log()
statement causes a function to have side effects because it affects the state of
an external code. i.e, the console object’s state and depends on it to perform
the job. Hence, the above function considered as impure function.
� Back to Top
233
• 2: [{status: “fullfilled”, value: undefined}, Uncaught(in promise)]
• 3: Uncaught (in promise)
• 4: [Uncaught(in promise), Uncaught(in promise)]
Answer
Answer: 3 The above promises settled at the same time but one of them
resolved and other one rejected. When you use .all method on these promises,
the result will be short circuted by throwing an error due to rejection in sec-
ond promise. But If you use .allSettled method then result of both the
promises will be returned irrespective of resolved or rejected promise status
without throwing any error.
Promise.allSettled([promiseOne, promiseTwo]).then((data) => console.log(data));
� Back to Top
Answer: 3 If you put setTimeout and setInterval methods inside the try
clause and an exception is thrown, the catch clause will not catch any of them.
This is because the try…catch statement works synchronously, and the function
in the above code is executed asynchronously after a certain period of time.
Hence, you will see runtime exception without catching the error. To resolve
this issue, you have to put the try…catch block inside the function as below,
setTimeout(() => {
try {
console.log("try block");
throw new Error(`An exception is thrown`);
} catch (err) {
234
console.log("Error: ", err);
}
}, 1000);
You can use .catch() function in promises to avoid these issues with asyn-
chronous code.
� Back to Top
Answer: 2 The variable “a” declared inside “if” has block scope and does not
affect the value of the outer “a” variable.
� Back to Top
Answer: 4 The length of the array ‘arr’ has been set to 0, so the array
becomes empty.
235
� Back to Top
Disclaimer
The questions provided in this repository are the summary of frequently asked
questions across numerous companies. We cannot guarantee that these ques-
tions will actually be asked during your interview process, nor should you focus
on memorizing all of them. The primary purpose is for you to get a sense of
what some companies might ask — do not get discouraged if you don’t know
the answer to all of them — that is ok!
Good luck with your interview �
236