JSQuestion
JSQuestion
JSQuestion
Click :star:if you like the project and follow @SudheerJonna (https://twitter.com/SudheerJonna) for more updates. Coding questions available here. Check DataStructures and
Algorithms (https://github.com/sudheerj/datastructures-algorithms) for DSA related questions and ECMAScript (https://github.com/sudheerj/ECMAScript-features) for all ES
features.).
GreatFrontEnd JavaScript
Interview Questions
(https://www.greatfrontend.com/questions/js?utm_source=github&utm_medium=referral&utm_campaign=sudheerj-react&gnrs=sudheerj)
Nail JavaScript interviews with questions and solutions from ex-interviewers! Try GreatFrontEnd → (https://www.greatfrontend.com/questions/js?
utm_source=github&utm_medium=referral&utm_campaign=sudheerj-js&gnrs=sudheerj)
FrontEndLead JavaScript
Interview Questions
(https://www.frontendlead.com/coding-questions?utm_source=github&utm_medium=referral&ut%0Dm_campaign=sudheerj-js)
Ace Javascript interview questions with solutions from FAANG+ companies! Try FrontendLead → (https://www.frontendlead.com/coding-questions?
utm_source=github&utm_medium=referral&ut%0Dm_campaign=sudheerj-js)
(https://zerotomastery.io/?utm_source=github&utm_medium=sponsor&utm_campaign=javascript-interview-questions)
1. Take this JavaScript Projects (https://links.zerotomastery.io/jsp_sudheer) course to go from a JS beginner to confidently building your own projects
2. Take this coding interview bootcamp (https://links.zerotomastery.io/mci_sudheer2) if you’re serious about getting hired and don’t have a CS degree
3. Take this Advanced JavaScript Course (https://links.zerotomastery.io/ajs_sudheer) to learn advanced JS concepts and become a top JS developer
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
No. Questions
8 How do you compare Object and Map
9 What is the difference between == and === operators
10 What are lambda expressions or arrow functions
11 What is a first class function
12 What is a first order function
13 What is a higher order function
14 What is a unary function
15 What is the currying function
16 What is a pure function
17 What is the purpose of the let keyword
18 What is the difference between let and var
19 What is the reason to choose the name let as a keyword
20 How do you redeclare variables in a switch block without an error
21 What is the Temporal Dead Zone
22 What is an IIFE (Immediately Invoked Function Expression)
23 How do you decode or encode a URL in JavaScript?
24 What is memoization
25 What is Hoisting
26 What are classes in ES6
27 What are closures
28 What are modules
29 Why do you need modules
30 What is scope in javascript
31 What is a service worker
32 How do you manipulate DOM using a service worker
33 How do you reuse information across service worker restarts
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
71 What is typeof operator
72 What is undefined property
No. Questions
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
114 How do you parse JSON string
115 Why do you need JSON
116 What are PWAs
117 What is the purpose of clearTimeout method
118 What is the purpose of clearInterval method
119 How do you redirect new page in javascript
120 How do you check whether a string contains a substring
121 How do you validate an email in javascript
122 How do you get the current url with javascript
123 What are the various url properties of location object
124 How do get query string values in javascript
125 How do you check if a key exists in an object
126 How do you loop through or enumerate javascript object
127 How do you test for an empty object
128 What is an arguments object
129 How do you make first letter of the string in an uppercase
130 What are the pros and cons of for loops
131 How do you display the current date in javascript
132 How do you compare two date objects
133 How do you check if a string starts with another string
134 How do you trim a string in javascript
135 How do you add a key value pair in javascript
136 Is the !-- notation represents a special operator
137 How do you assign default values to variables
No. Questions
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 within a range
151 What is tree shaking
152 What is the need of tree shaking
153 Is it recommended to use eval
154 What is a Regular Expression
155 What are the string methods that accept Regular expression
156 What are modifiers in regular expression
157 What are regular expression patterns
158 What is a RegExp object
159 How do you search a string for a pattern
160 What is the purpose of exec method
161 How do you change the style of a HTML element
162 What would be the result of 1+2+'3'
163 What is a debugger statement
164 What is the purpose of breakpoints in debugging
165 Can I use reserved words as identifiers
166 How do you detect a mobile browser
167 How do you detect a mobile browser without regexp
168 How do you get the image width and height using JS
169 How do you make synchronous HTTP request
170 How do you make asynchronous HTTP request
171 How do you convert date to another timezone in javascript
172 What are the properties used to get size of window
173 What is a conditional operator in javascript
174 Can you apply chaining on conditional operator
175 What are the ways to execute javascript after page load
176 What is the difference between proto and prototype
177 Can you give an example of when you really need a semicolon
178 What is a freeze method
179 What is the purpose of freeze method
180 Why do I need to use freeze method
181 How do you detect a browser language preference
182 How to convert string to title case with javascript
183 How do you detect javascript disabled in the page
184 What are various operators supported by javascript
185 What is a rest parameter
186 What happens if you do not use rest parameter as a last argument
187 What are the bitwise operators available in javascript
188 What is a spread operator
189 How do you determine whether object is frozen or not
190 How do you determine two values same or not using object
191 What is the purpose of using object is method
192 How do you copy properties from one object to other
193 What are the applications of assign method
194 What is a proxy object
195 What is the purpose of seal method
196 What are the applications of seal method
197 What are the differences between freeze and seal methods
198 How do you determine if an object is sealed or not
199 How do you get enumerable key and value pairs
200 What is the main difference between Object.values and Object.entries method
201 How can you get the list of keys of any object
202 How do you create an object with prototype
No. Questions
203 What is a WeakSet
204 What are the differences between WeakSet and Set
205 List down the collection of methods available on WeakSet
206 What is a WeakMap
207 What are the differences between WeakMap and Map
208 List down the collection of methods available on WeakMap
209 What is the purpose of uneval
210 How do you encode an URL
211 How do you decode an URL
212 How do you print the contents of web page
213 What is the difference between uneval and eval
214 What is an anonymous function
215 What is the precedence order between local and global variables
216 What are javascript accessors
217 How do you define property on Object constructor
218 What is the difference between get and defineProperty
219 What are the advantages of Getters and Setters
220 Can I add getters and setters using defineProperty method
221 What is the purpose of switch-case
222 What are the conventions to be followed for the usage of switch case
223 What are primitive data types
224 What are the different ways to access object properties
225 What are the function parameter rules
226 What is an error object
227 When you get a syntax error
228 What are the different error names from error object
229 What are the various statements in error handling
230 What are the two types of loops in javascript
231 What is nodejs
232 What is an Intl object
233 How do you perform language specific date and time formatting
234 What is an Iterator
235 How does synchronous iteration works
236 What is an event loop
237 What is call stack
238 What is an event queue
239 What is a decorator
240 What are the properties of Intl object
241 What is an Unary operator
242 How do you sort elements in an array
243 What is the purpose of compareFunction while sorting arrays
244 How do you reversing an array
245 How do you find min and max value in an array
246 How do you find min and max values without Math functions
247 What is an empty statement and purpose of it
248 How do you get metadata of a module
249 What is a comma operator
250 What is the advantage of a comma operator
251 What is typescript
252 What are the differences between javascript and typescript
253 What are the advantages of typescript over javascript
254 What is an object initializer
255 What is a constructor method
256 What happens if you write constructor more than once in a class
257 How do you call the constructor of a parent class
258 How do you get the prototype of an object
259 What happens If I pass string type for getPrototype method
260 How do you set prototype of one object to another
261 How do you check whether an object can be extendable or not
262 How do you prevent an object to extend
263 What are the different ways to make an object non-extensible
264 How do you define multiple properties on an object
265 What is MEAN in javascript
266 What Is Obfuscation in javascript
267 Why do you need Obfuscation
No. Questions
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
289 What is the difference between java and javascript
290 Does JavaScript supports namespace
291 How do you declare namespace
292 How do you invoke javascript code in an iframe from parent page
293 How do get the timezone offset from date
294 How do you load CSS and JS files dynamically
295 What are the different methods to find HTML elements in DOM
296 What is jQuery
297 What is V8 JavaScript engine
298 Why do we call javascript as dynamic language
299 What is a void operator
300 How to set the cursor to wait
301 How do you create an infinite loop
302 Why do you need to avoid with statement
303 What is the output of the following for loops
304 List down some of the features of ES6
305 What is ES6
306 Can I redeclare let and const variables
307 Does the const variable make the value immutable
308 What are default parameters
309 What are template literals
310 How do you write multi-line strings in template literals
311 What are nesting templates
312 What are tagged templates
313 What are raw strings
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
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
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
No. Questions
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
419 How do you define instance and non-instance properties
420 What is the difference between isNaN and Number.isNaN?
421 How to invoke an IIFE without any extra brackets?
422 Is that possible to use expressions in switch cases?
423 What is the easiest way to ignore promise errors?
424 How do style the console output using CSS?
425 What is nullish coalescing operator (??)?
426 How do you group and nest console output?
427 What is the difference between dense and sparse arrays?
428 What are the different ways to create sparse arrays?
429 What is the difference between setTimeout, setImmediate and process.nextTick?
430 How do you reverse an array without modifying original array?
431 How do you create custom HTML element?
432 What is global execution context?
433 What is function execution context?
434 What is debouncing?
435 What is throttling?
436 What is optional chaining?
437 What is an environment record?
438 How to verify if a variable is an array?
439 What is pass by value and pass by reference?
440 What are the differences between primitives and non-primitives?
441 How do you create your own bind method using either call or apply method?
442 What are the differences between pure and impure functions?
443 What is referential transparency?
444 What are the possible side-effects in javascript?
445 What are compose and pipe functions?
446 What is module pattern?
447 What is Function Composition?
448 How to use await outside of async function prior to ES2022?
449 What is the purpose of the this keyword in JavaScript?
450 What are the uses of closures?
451 What are the phases of execution context?
452 What are the possible reasons for memory leaks?
453 What are the optimization techniques of V8 engine?
454 What are the examples of built-in higher order functions?
455 What are the benefits higher order functions?
456 How do you create polyfills for map, filter and reduce methods?
457 What is the difference between map and forEach functions?
458 Give an example of statements affected by automatic semicolon insertion?
459 What are the event phases of a browser?
460 What are the real world use cases of proxy?
461 What are hidden classes?
462 What is inline caching?
No. Questions
463 What are the different ways to execute external scripts?
464 What is Lexical Scope?
465 How to detect system dark mode in javascript?
466 What is the purpose of requestAnimationFrame method?
467 What is the difference between substring and substr methods?
468 How to find the number of parameters expected by a function?
469 What is globalThis, and what is the importance of it?
470 What are the array mutation methods?
The object literal syntax (or object initializer), is a comma-separated set of name-value pairs wrapped in curly braces.
var object = {
name: "Sudheer",
age: 34
};
Object literal property values can be of any data type, including array, function, and nested object.
2. Object constructor:
The simplest way to create an empty object is using the Object constructor. Currently this approach is not recommended.
The Object() is a built-in constructor function so "new" keyword is not required. The above code snippet can be re-written as:
The create method of Object is used to create a new object by passing the specified 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.
The following example creates an object along with additional new properties.
let vehicle = {
wheels: '4',
fuelType: 'Gasoline',
color: 'Green'
}
let carProps = {
type: {
value: 'Volkswagen'
},
model: {
value: 'Golf'
}
}
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");
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();
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() {}
(OR)
// If the result is a non-null object then use it otherwise just use the new instance.
console.log(result && typeof result === 'object' ? result : newInstance);
The Object.assign method is used to copy all the properties from one or more source objects and stores them into a target object.
The following code creates a new staff object by copying properties of his working company and the car he owns.
class Person {
constructor(name) {
this.name = name;
}
}
8. Singleton pattern:
A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance. This way one can ensure that they don't
accidentally create multiple instances.
The prototype on object instance is available through Object.getPrototypeOf(object) or __proto__ property whereas prototype on constructor function is available through
Object.prototype.
Screenshot
⬆ Back to Top
Call: The call() method invokes a function with a given this value and arguments provided one by one
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
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 arguments
var employee1 = { firstName: "John", lastName: "Rodson" };
var employee2 = { firstName: "Jimmy", lastName: "Baily" };
Call and Apply are pretty much interchangeable. Both execute the current function immediately. You need to decide whether it’s easier to send in an array or a comma
separated list of arguments. You can remember by treating Call is for comma (separated list) and Apply is for Array.
Bind creates a new function that will have this set to the first parameter passed to bind().
⬆ Back to Top
JSON.parse(text);
Stringification: Converting a native object to a string so that it can be transmitted across the network
JSON.stringify(object);
⬆ Back to Top
Note: Slice method doesn't mutate the original array but it returns the subset as a new array.
⬆ Back to Top
let arrayIntegers1 = arrayIntegersOriginal1.splice(0, 2); // returns [1, 2]; original array: [3, 4, 5]
let arrayIntegers2 = arrayIntegersOriginal2.splice(3); // returns [4, 5]; original array: [1, 2, 3]
let arrayIntegers3 = arrayIntegersOriginal3.splice(3, 1, "a", "b", "c"); //returns [4]; original array: [1, 2, 3, "a", "b", "c"
Note: Splice method modifies the original array and returns the deleted array.
⬆ Back to Top
Slice Splice
Doesn't modify the original array(immutable) Modifies the original array(mutable)
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
1. The keys of an Object can be Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive type.
2. The keys in a Map are ordered while keys added to Object are not. Thus, when iterating over it, a Map object returns keys in the order of insertion.
3. You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.
4. A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.
5. An Object has a prototype, so there are default keys in an object that could collide with your keys if you're not careful. As of ES5 this can be bypassed by creating an
object(which can be called a map) using Object.create(null), but this practice is seldom done.
6. A Map may perform better in scenarios involving frequent addition and removal of key pairs.
⬆ Back to Top
1. Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
2. Two numbers are strictly equal when they are numerically equal, i.e., having the same number value. There are two special cases in this,
1. NaN is not equal to anything, including NaN.
2. Positive and negative zeros are equal to one another.
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
0 == false // true
0 === false // false
1 == "1" // true
1 === "1" // false
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
NaN == NaN or NaN === NaN // false
[]==[] or []===[] //false, refer different objects in memory
{}=={} or {}==={} //false, refer different objects in memory
⬆ Back to Top
10. What are lambda expressions or arrow functions
An arrow function is a shorter/concise syntax for a function expression and does not have its own this, arguments, super, or new.target. These functions are best suited for
non-method functions, and they cannot be used as constructors.
⬆ Back to Top
For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a
variable. For example, in the below example, handler functions assigned to a listener
⬆ Back to Top
⬆ Back to Top
You can also call the function which you are passing to higher order function as callback function.
The higher order function is helpful to write the modular and reusable code.
⬆ Back to Top
const unaryFunction = (a) => console.log(a + 10); // Add 10 to the given argument and display the value
⬆ Back to Top
Let's take an example of n-ary function and how it turns into a currying function,
const multiArgFunction = (a, b, c) => a + b + c;
console.log(multiArgFunction(1, 2, 3)); // 6
Curried functions are great to improve code reusability and functional composition.
⬆ Back to Top
Let's take an example to see the difference between pure and impure functions,
//Impure
let numberArray = [];
const impureAddNumber = (number) => numberArray.push(number);
//Pure
const pureAddNumber = (number) => (argNumberArray) =>
argNumberArray.concat([number]);
As per the above code snippets, the Push function is impure itself by altering the array and returning a push number index independent of the parameter value, whereas
Concat on the other hand takes the array and concatenates it with the other array producing a whole new array without side effects. Also, the return value is a concatenation
of the previous array.
Remember that Pure functions are important as they simplify unit testing without any side effects and no need for dependency injection. They also avoid tight coupling and
make it harder to break your application by not having any side effects. These principles are coming together with the Immutability concept of ES6: giving preference to
const over let usage.
⬆ Back to Top
⬆ Back to Top
var let
It has been available from the beginning of JavaScript Introduced as part of ES6
It has function scope It has block scope
Variable declaration will be hoisted, initialized as undefined Hoisted but not initialized
var let
It is possible to re-declare the variable in the same scope It is not possible to re-declare the variable
function userDetails(username) {
if (username) {
console.log(salary); // undefined due to hoisting
console.log(age); // ReferenceError: Cannot access 'age' before initialization
let age = 30;
var salary = 10000;
}
console.log(salary); //10000 (accessible due to function scope)
console.log(age); //error: age is not defined(due to block scope)
}
userDetails("John");
⬆ Back to Top
⬆ Back to Top
let counter = 1;
switch (x) {
case 0:
let name;
break;
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
⬆ Back to Top
(function () {
// logic here
})();
The primary reason to use an IIFE is to obtain data privacy because any variables declared within the IIFE cannot be accessed by the outside world. i.e, If you try to access
variables from the IIFE then it throws an error as below,
(function () {
var message = "IIFE";
console.log(message);
})();
console.log(message); //Error: message is not defined
⬆ Back to Top
Note: If you want to encode characters such as / ? : @ & = + $ # then you need to use encodeURIComponent().
⬆ Back to Top
⬆ Back to Top
var message;
console.log(message);
message = "The variable Has been hoisted";
function message(name) {
console.log(name);
}
This hoisting makes functions to be safely used in code before they are declared.
⬆ Back to Top
Bike.prototype.getDetails = function () {
return this.model + " bike has" + this.color + " color";
};
getDetails() {
return this.model + " bike has" + this.color + " color";
}
}
⬆ Back to Top
function Welcome(name) {
var greetingInfo = function (message) {
console.log(message + " " + name);
};
return greetingInfo;
}
var myFunction = Welcome("John");
myFunction("Welcome "); //Output: Welcome John
myFunction("Hello Mr."); //output: Hello Mr. John
As per the above code, the inner function(i.e, greetingInfo) has access to the variables in the outer function scope(i.e, Welcome) even after the outer function has returned.
⬆ Back to Top
⬆ Back to Top
1. Maintainability
2. Reusability
3. Namespacing
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
1. Local storage: It stores data for current origin with no expiration date.
2. Session storage: It stores data for one session and the data is lost when the browser tab is closed.
⬆ Back to Top
⬆ Back to Top
document.cookie = "username=John";
Screenshot
⬆ Back to Top
1. When a user visits a web page, the user profile can be stored in a cookie.
2. Next time the user visits the page, the cookie remembers the user profile.
⬆ Back to Top
39. What are the options in a cookie
There are few below options available for a cookie,
1. By default, the cookie is deleted when the browser is closed but you can change this behavior by setting expiry date (in UTC time).
1. By default, the cookie belongs to a current page. But you can tell the browser what path the cookie belongs to using a path parameter.
⬆ Back to Top
document.cookie =
"username=; expires=Fri, 07 Jun 2019 00:00:00 UTC; path=/;";
Note: You should define the cookie path option to ensure that you delete the right cookie. Some browsers doesn't allow to delete a cookie unless you specify a path
parameter.
⬆ Back to Top
41. What are the differences between cookie, local storage and session storage
Below are some of the differences between cookie, local storage and session storage,
Local Session
Feature Cookie
storage storage
Accessed on client or Both server-side & client-side. The set-cookie HTTP response header is used client-side client-side
server side by server inorder to send it to user. only only
Forever until until tab is
Expiry Manually configured using Expires option
deleted closed
Not
SSL support Supported Not supported
supported
Maximum data size 4KB 5 MB 5MB
Accessible from Any window Any window Same tab
Sent with requests Yes No No
⬆ Back to Top
⬆ Back to Top
localStorage.setItem("logo", document.getElementById("logo").value);
localStorage.getItem("logo");
⬆ Back to Top
⬆ Back to Top
window.onstorage = functionRef;
Let's take the example usage of onstorage event handler which logs the storage key and it's values
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
1. Create a Web Worker File: You need to write a script to increment the count value. Let's name it as counter.js
let i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()", 500);
}
timedCount();
Here postMessage() method is used to post a message back to the HTML page
1. Create a Web Worker Object: You can create a web worker object by checking for browser support. Let's name this file as web_worker_example.js
if (typeof w == "undefined") {
w = new Worker("counter.js");
}
1. Terminate a Web Worker: Web workers will continue to listen for messages (even after the external script is finished) until it is terminated. You can use the terminate()
method to terminate listening to the messages.
w.terminate();
1. Reuse the Web Worker: If you set the worker variable to undefined you can reuse the code
w = undefined;
⬆ Back to Top
1. Window object
2. Document object
3. Parent object
⬆ Back to Top
Screenshot
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
function callbackFunction(name) {
console.log("Hello " + name);
}
function outerFunction(callback) {
let name = prompt("Please enter your name.");
callback(name);
}
outerFunction(callbackFunction);
⬆ Back to Top
function firstFunction() {
// Simulate a code delay
setTimeout(function () {
console.log("First function called");
}, 1000);
}
function secondFunction() {
console.log("Second function called");
}
firstFunction();
secondFunction();
Output;
// Second function called
// First function called
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
async1(function(){
async2(function(){
async3(function(){
async4(function(){
....
});
});
});
});
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
60. What are the events available for server sent events
Below are the list of events available for server sent events | Event | Description | |---- | --------- | onopen | It is used when a connection to the server is opened | | onmessage |
This event is used when a message is received | | onerror | It happens when an error occurs|
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
Note: Remember that the order of the promises(output the result) is maintained as per input order.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
"use strict";
x = 3.14; // This will cause an error because x is not declared
function myFunction() {
"use strict";
y = 3.14; // This will cause an error
}
⬆ Back to Top
If you don't use this expression then it returns the original value.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
user = undefined;
⬆ Back to Top
⬆ Back to Top
Null Undefined
It is an assignment value which indicates that variable It is not an assignment value where a variable has been declared but
points to no object. has not yet been assigned a value.
Type of null is object Type of undefined is undefined
The null value is a primitive value that represents the null, The undefined value is a primitive value used when a variable has
empty, or non-existent reference. not been assigned a value.
Indicates the absence of a value for a variable Indicates absence of variable itself
Converted to zero (0) while performing primitive operations Converted to NaN while performing primitive operations
⬆ Back to Top
console.log(eval("1 + 2")); // 3
⬆ Back to Top
Window Document
It is the direct child of the window object. This is also known as
It is the root level element in any web page
Document Object Model(DOM)
By default window object is available implicitly in the
You can access it via window.document or document.
page
It has methods like alert(), confirm() and properties like It provides methods like getElementById, getElementsByTagName,
document, location createElement etc
⬆ Back to Top
function goBack() {
window.history.back();
}
function goForward() {
window.history.forward();
}
⬆ Back to Top
Let's take an input element to detect the CapsLock on/off behavior with an example,
<input type="password" onmousedown="enterInput(event)" />
<p id="feedback"></p>
<script>
function enterInput(e) {
var flag = e.getModifierState("CapsLock");
if (flag) {
document.getElementById("feedback").innerHTML = "CapsLock activated";
} else {
document.getElementById("feedback").innerHTML =
"CapsLock not activated";
}
}
</script>
⬆ Back to Top
isNaN("Hello"); //true
isNaN("100"); //false
⬆ Back to Top
80. What are the differences between undeclared and undefined variables
Below are the major differences between undeclared(not defined) and undefined variables,
undeclared undefined
These variables declared in the program but have not
These variables do not exist in a program and are not declared
assigned any value
If you try to read the value of an undeclared variable, then a If you try to read the value of an undefined variable, an
runtime error is encountered undefined value is returned.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
Math.sqrt(-1);
parseInt("Hello");
⬆ Back to Top
isFinite(Infinity); // false
isFinite(NaN); // false
isFinite(-Infinity); // false
isFinite(100); // true
⬆ Back to Top
⬆ Back to Top
<div>
<button class="child">Hello</button>
</div>
<script>
const parent = document.querySelector("div");
const child = document.querySelector(".child");
parent.addEventListener("click",
function () {
console.log("Parent");
}
);
child.addEventListener("click", function () {
console.log("Child");
});
</script>
// Child
// Parent
⬆ Back to Top
You need to pass true value for addEventListener method to trigger event handlers in event capturing phase.
<div>
<button class="child">Hello</button>
</div>
<script>
const parent = document.querySelector("div");
const child = document.querySelector(".child");
parent.addEventListener("click",
function () {
console.log("Parent");
},
true
);
child.addEventListener("click", function () {
console.log("Child");
});
</script>
// Parent
// Child
⬆ Back to Top
function submit() {
document.forms[0].submit();
}
⬆ Back to Top
console.log(navigator.platform);
⬆ Back to Top
90. What is the difference between document load and DOMContentLoaded events
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for assets(stylesheets, images, and
subframes) to finish loading. Whereas The load event is fired when the whole page has loaded, including all dependent resources(stylesheets, images).
⬆ Back to Top
91. What is the difference between native, host and user objects
Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification. For example, String, Math, RegExp, Object, Function etc
core objects defined in the ECMAScript spec. Host objects are objects provided by the browser or runtime environment (Node).
For example, window, XmlHttpRequest, DOM nodes etc are considered as host objects. User objects are objects defined in the javascript code. For example, User objects
created for profile information.
⬆ Back to Top
92. What are the tools or techniques used for debugging JavaScript code
You can use below tools or techniques for debugging javascript
1. Chrome Devtools
2. debugger statement
3. Good old console.log statement
⬆ Back to Top
93. What are the pros and cons of promises over callbacks
Below are the list of pros and cons of promises over callbacks,
Pros:
Cons:
⬆ Back to Top
And after you change the value of the text field to "Good evening", it becomes like
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
<!doctype html>
<html>
<head>
<script>
function greeting() {
alert('Hello! Good morning');
}
</script>
</head>
<body>
<button type="button" onclick="greeting()">Click me</button>
</body>
</html>
⬆ Back to Top
⬆ Back to Top
document
.getElementById("link")
.addEventListener("click", function (event) {
event.preventDefault();
});
⬆ Back to Top
<script>
function firstFunc(event) {
alert("DIV 1");
event.stopPropagation();
}
function secondFunc() {
alert("DIV 2");
}
</script>
⬆ Back to Top
⬆ Back to Top
Screenshot
⬆ Back to Top
setTimeout(function () {
console.log("Good morning");
}, 2000);
⬆ Back to Top
setInterval(function () {
console.log("Good morning");
}, 2000);
⬆ Back to Top
108. Why is JavaScript treated as Single threaded
JavaScript is a single-threaded language. Because the language specification does not allow the programmer to write code so that the interpreter can run parts of it in parallel
in multiple threads or processes. Whereas languages like java, go, C++ can make multi-threaded and multi-process programs.
⬆ Back to Top
For example, if you wanted to detect field changes inside a specific form, you can use event delegation technique,
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
For example, the below setTimeout method is used to display the message after 3 seconds. This timeout can be cleared by the clearTimeout() method.
<script>
var msg;
function greeting() {
alert('Good morning');
}
function start() {
msg =setTimeout(greeting, 3000);
function stop() {
clearTimeout(msg);
}
</script>
⬆ Back to Top
For example, the below setInterval method is used to display the message for every 3 seconds. This interval can be cleared by the clearInterval() method.
<script>
var msg;
function greeting() {
alert('Good morning');
}
function start() {
msg = setInterval(greeting, 3000);
function stop() {
clearInterval(msg);
}
</script>
⬆ Back to Top
function redirect() {
window.location.href = "newPage.html";
}
⬆ Back to Top
1. Using includes: ES6 provided String.prototype.includes method to test a string contains a substring
2. Using indexOf: In an ES5 or older environment, you can use String.prototype.indexOf which returns the index of a substring. If the index value is not equal to
-1 then it means the substring exists in the main string.
3. Using RegEx: The advanced solution is using Regular expression's test method(RegExp.test), which allows for testing for against regular expressions
⬆ Back to Top
function validateEmail(email) {
var re =
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-z
return re.test(String(email).toLowerCase());
}
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
1. Using in operator: You can use the in operator whether a key exists in an object or not
"key" in obj;
and If you want to check if a key doesn't exist, remember to use parenthesis,
!("key" in obj);
2. Using hasOwnProperty method: You can use hasOwnProperty to particularly test for properties of the object instance (and not inherited properties)
obj.hasOwnProperty("key"); // true
3. Using undefined comparison: If you access a non-existing property from an object, the result is undefined. Let’s compare the properties against undefined to
determine the existence of the property.
const user = {
name: "John",
};
⬆ Back to Top
var object = {
k1: "value1",
k2: "value2",
k3: "value3",
};
1. Using Object entries(ECMA 7+): You can use object entries length along with constructor type.
Object.entries(obj).length === 0 && obj.constructor === Object; // Since date object length is 0, you need to check constructor
2. Using Object keys(ECMA 5+): You can use object keys length along with constructor type.
Object.keys(obj).length === 0 && obj.constructor === Object; // Since date object length is 0, you need to check constructor ch
3. Using for-in with hasOwnProperty(Pre-ECMA 5): You can use a for-in loop along with hasOwnProperty.
function isEmpty(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
⬆ Back to Top
function sum() {
var total = 0;
for (var i = 0, len = arguments.length; i < len; ++i) {
total += arguments[i];
}
return total;
}
Note: You can't apply array methods on arguments object. But you can convert into a regular array as below.
⬆ Back to Top
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
⬆ Back to Top
Pros
1. Works on every environment
2. You can use break and continue flow control statements
Cons
3. Too verbose
4. Imperative
5. You might face off-by-one errors.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
If your browser(<IE9) doesn't support this method then you can use below polyfill.
if (!String.prototype.trim) {
(function () {
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.prototype.trim = function () {
return this.replace(rtrim, "");
};
})();
}
⬆ Back to Top
135. How do you add a key value pair in javascript
There are two possible solutions to add new properties to an object.
var object = {
key1: value1,
key2: value2,
};
1. Using dot notation: This solution is useful when you know the name of the property
object.key3 = "value3";
2. Using square bracket notation: This solution is useful when the name of the property is dynamically determined.
obj["key3"] = "value3";
⬆ Back to Top
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
var a = b || c;
As per the above expression, variable 'a 'will get the value of 'c' only if 'b' is falsy (if is null, false, undefined, 0, empty string, or NaN), otherwise 'a' will get the value of 'b'.
⬆ Back to Top
var str =
"This is a \n\ very lengthy \n\ sentence!";
console.log(str);
But if you have a space after the '\n' character, there will be indentation inconsistencies.
⬆ Back to Top
⬆ Back to Top
fn.name = "John";
⬆ Back to Top
141. What is the way to find the number of parameters expected by a function
You can use function.length syntax to find the number of parameters expected by a function. Let's take an example of sum function to calculate the sum of numbers,
⬆ Back to Top
⬆ Back to Top
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.
⬆ Back to Top
// Output is:
// "i = 1, j = 0"
// "i = 2, j = 0"
// "i = 2, j = 1"
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
var v1 = {};
var v2 = "";
var v3 = 0;
var v4 = false;
var v5 = [];
var v6 = /()/;
var v7 = function () {};
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
150. Can you write a random integers function to print integers within a range
Yes, you can create a proper random function to return a random number between min and max (both included)
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
/pattern/modifiers;
For example, the regular expression or search pattern with case-insensitive username would be,
/John/i;
⬆ Back to Top
155. What are the string methods that accept Regular expression
There are six string methods: search(), replace(), replaceAll(), match(), matchAll(), and split().
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() and replaceAll() methods are used to return a modified string where the pattern is replaced.
The match() and matchAll() methods are used to return the matches when matching a string against a regular expression.
The split() method is used to split a string into an array of substrings, and returns the new array.
⬆ Back to Top
Modifier Description
i Perform case-insensitive matching
g Perform a global match rather than stops at first match
m Perform multiline matching
⬆ Back to Top
1. Brackets: These are used to find a range of characters. For example, below are some use cases,
1. [abc]: Used to find any of the characters between the brackets(a,b,c)
2. [0-9]: Used to find any of the digits between the brackets
3. (a|b): Used to find any of the alternatives separated with |
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, below 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. What is a RegExp object
RegExp object is a regular expression object with predefined properties and methods. Let's see the simple usage of RegExp object,
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
1. Using style property: You can modify inline style using style property
document.getElementById("title").style.fontSize = "30px";
2. Using ClassName property: It is easy to modify element class using className property
document.getElementById("title").className = "custom-title";
⬆ Back to Top
⬆ Back to Top
function getProfile() {
// code goes here
debugger;
// code goes here
}
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
window.mobilecheck = function () {
var mobileCheck = false;
(function (a) {
if (
/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kin
a
) ||
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|
a.substr(0, 4)
)
)
mobileCheck = true;
})(navigator.userAgent || navigator.vendor || window.opera);
return mobileCheck;
};
⬆ Back to Top
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. How do you get the image width and height using JS
You can programmatically get the image and check the dimensions(width and height) using Javascript.
var img = new Image();
img.onload = function () {
console.log(this.width + "x" + this.height);
};
img.src = "http://www.google.com/intl/en_ALL/images/logo.gif";
⬆ Back to Top
function httpGet(theUrl) {
var xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open("GET", theUrl, false); // false for synchronous request
xmlHttpReq.send(null);
return xmlHttpReq.responseText;
}
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
var width =
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
var height =
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
⬆ Back to Top
⬆ Back to Top
function traceValue(someParam) {
return condition1
? value1
: condition2
? value2
: condition3
? value3
: value4;
}
function traceValue(someParam) {
if (condition1) {
return value1;
} else if (condition2) {
return value2;
} else if (condition3) {
return value3;
} else {
return value4;
}
}
⬆ Back to Top
175. What are the ways to execute javascript after page load
You can execute javascript after page load in many different ways,
1. window.onload:
2. document.onload:
3. body onload:
<body onload="script();">
⬆ Back to Top
⬆ Back to Top
177. Can you give an example of when you really need a semicolon
It is recommended to use semicolons after every statement in JavaScript. For example, in the below case it throws an error ".. is not a function" at runtime due to missing
semicolon.
// define a function
var fn = (function () {
//...
})(
// semicolon missing at this line
var fn = (function () {
//...
})(function () {
//...
})();
In this case, we are passing the second function as an argument to the first function and then trying to call the result of the first function call as a function. Hence, the second
function will fail with a "... is not a function" error at runtime.
⬆ Back to Top
const obj = {
prop: 100,
};
Object.freeze(obj);
obj.prop = 200; // Throws an error in strict mode
console.log(obj.prop); //100
Remember freezing is only applied to the top-level properties in objects but not for nested objects. For example, let's try to freeze user object which has employment details as
nested object and observe that details have been changed.
const user = {
name: "John",
employment: {
department: "IT",
},
};
Object.freeze(user);
user.employment.department = "HR";
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
var language =
(navigator.languages && navigator.languages[0]) || // Chrome / Firefox
navigator.language || // All browsers
navigator.userLanguage; // IE <= 10
console.log(language);
⬆ Back to Top
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase();
});
}
toTitleCase("good morning john"); // Good Morning John
⬆ Back to Top
⬆ Back to Top
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 Operator), *= (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
For example, let's take a sum example to calculate on dynamic number of parameters,
function sum(...args) {
let total = 0;
for (const i of args) {
total += i;
}
return total;
}
⬆ Back to Top
186. What happens if you do not use rest parameter as a last argument
The rest parameter should be the last argument, as its job is to collect all the remaining arguments into an array. For example, if you define a function like below it doesn’t
make any sense and will throw an error.
function someFunc(a,…b,c){
//You code goes here
return;
}
⬆ Back to Top
⬆ Back to Top
function calculateSum(x, y, z) {
return x + y + z;
}
console.log(calculateSum(...numbers)); // 6
⬆ Back to Top
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. How do you determine two values same or not using object
The Object.is() method determines whether two values are the same value. For example, the usage with different types of values would be,
1. both undefined
2. both null
3. both true or both false
4. both strings of the same length with the same characters in the same order
5. both the same object (means both object have same reference)
6. both numbers and both +0 both -0 both NaN both non-zero and both not NaN and both have the same value.
⬆ Back to Top
⬆ Back to Top
Object.assign(target, ...sources);
Let's take example with one source and one target object,
const target = { a: 1, b: 2 };
const source = { b: 3, c: 4 };
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
⬆ Back to Top
A proxy is created with two parameters: a target object which you want to proxy and a handler object which contains methods to intercept fundamental operations. The syntax
would be as follows,
Let's take a look at below examples of proxy object and how the get method which customize the lookup behavior,
//Example1:
const person = {
name: 'Sudheer Jonna',
age: 35
};
const handler = {
get(target, prop) {
if (prop === 'name') {
return 'Mr. ' + target[prop];
}
return target[prop];
}
};
//Example2:
var handler1 = {
get: function (obj, prop) {
return prop in obj ? obj[prop] : 100;
},
};
In the above code, it uses get handler which define the behavior of the proxy when an operation is performed on it. These proxies are mainly used for some of the below
cross-cutting concerns.
1. Logging
2. Authentication or Authorization
3. Data binding and observables
4. Function parameter validation
⬆ Back to Top
const object = {
property: "Welcome JS world",
};
Object.seal(object);
object.property = "Welcome to object world";
console.log(Object.isSealed(object)); // true
delete object.property; // You cannot delete when sealed
console.log(object.property); //Welcome to object world
⬆ Back to Top
⬆ Back to Top
197. What are the differences between freeze and seal methods
If an object is frozen using the Object.freeze() method then its properties become immutable and no changes can be made in them whereas if an object is sealed using the
Object.seal() method then the changes can be made in the existing properties of the object.
⬆ Back to Top
1. If it is not extensible.
2. If all of its properties are non-configurable.
3. If it is not removable (but not necessarily non-writable). Let's see it in the action
const object = {
property: "Hello, Good morning",
};
⬆ Back to Top
const object = {
a: "Good morning",
b: 100,
};
⬆ Back to Top
200. What is the main difference between Object.values and Object.entries method
The Object.values() method's behavior is similar to Object.entries() method but it returns an array of values instead [key,value] pairs.
const object = {
a: "Good morning",
b: 100,
};
⬆ Back to Top
201. How can you get the list of keys of any object
You can use the Object.keys() method which is used to return an array of a given object's own property names, in the same order as we get with a normal loop. For
example, you can get the keys of a user object,
const user = {
name: "John",
gender: "male",
age: 40,
};
⬆ Back to Top
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 "user" object
⬆ Back to Top
new WeakSet([iterable]);
⬆ Back to Top
1. Sets can store any value Whereas WeakSets can store only collections of objects
2. WeakSet does not have size property unlike Set
3. WeakSet does not have methods such as clear, keys, values, entries, forEach.
4. WeakSet is not iterable.
⬆ Back to Top
1. add(value): A new object is appended with the given value to the weakset
2. delete(value): Deletes the value from the WeakSet collection.
3. has(value): It returns true if the value is present in the WeakSet Collection, otherwise it returns false.
⬆ Back to Top
new WeakMap([iterable]);
⬆ Back to Top
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
1. set(key, value): Sets the value for the key in the WeakMap object. Returns the WeakMap object.
2. delete(key): Removes any value associated to the key.
3. has(key): Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not.
4. get(key): Returns the value associated to the key, or undefined if there is none. Let's see the functionality of all the above methods in an example,
⬆ Back to Top
209. What is the purpose of uneval
The uneval() is an inbuilt function which is used to create a string representation of the source code of an Object. It is a top-level function and 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
⬆ Back to Top
⬆ Back to Top
Note: In most browsers, it will block while the print dialog is open.
⬆ Back to Top
function (optionalParameters) {
//do something
}
⬆ Back to Top
215. What is the precedence order between local and global variables
A local variable takes precedence over a global variable with the same name. Let's see this behavior in an example.
⬆ Back to Top
var user = {
firstName: "John",
lastName: "Abraham",
language: "en",
get lang() {
return this.language;
},
set lang(lang) {
this.language = lang;
},
};
console.log(user.lang); // getter access lang as en
user.lang = "fr";
console.log(user.lang); // setter used to set lang as fr
⬆ Back to Top
217. How do you define property on Object constructor
The Object.defineProperty() static method is used to define a new property 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,
Object.defineProperty(newObject, "newProperty", {
value: 100,
writable: false,
});
console.log(newObject.newProperty); // 100
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
// Define getters
Object.defineProperty(obj, "increment", {
get: function () {
this.counter++;
return this.counter;
},
});
Object.defineProperty(obj, "decrement", {
get: function () {
this.counter--;
return this.counter;
},
});
// Define setters
Object.defineProperty(obj, "add", {
set: function (value) {
this.counter += value;
},
});
Object.defineProperty(obj, "subtract", {
set: function (value) {
this.counter -= value;
},
});
obj.add = 10;
obj.subtract = 5;
console.log(obj.increment); //6
console.log(obj.decrement); //5
⬆ Back to Top
switch (expression)
{
case value1:
statement1;
break;
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. What are the conventions to be followed for the usage of switch case
Below are the list of conventions should be taken care,
⬆ Back to Top
1. string
2. number
3. boolean
4. null
5. undefined
6. bigint
7. symbol
⬆ Back to Top
objectName.property;
objectName["property"];
objectName[expression];
⬆ Back to Top
⬆ Back to Top
try {
greeting("Welcome");
} catch (err) {
console.log(err.name + "<br>" + err.message);
}
⬆ Back to Top
227. When you get a syntax error
A SyntaxError is thrown if you try to evaluate code with a syntax error. For example, the below missing quote for the function parameter throws a syntax error
try {
eval("greeting('welcome)"); // Missing ' will produce an error
} catch (err) {
console.log(err.name);
}
⬆ Back to Top
228. What are the different error names from error object
There are 7 different types of error names returned from error object, | Error Name | Description | |---- | --------- | AggregateError | An error indicating that multiple errors
occurred | | EvalError | An error has occurred in the eval() function | | RangeError | An error has occurred with a number "out of range" | | ReferenceError | An error due to an
illegal reference| | SyntaxError | An error due to a syntax error| | TypeError | An error due to a type error | | URIError | An error due to encodeURI() |
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
233. How do you perform language specific date and time formatting
You can use the Intl.DateTimeFormat object which is a constructor for objects that enable language-sensitive date and time formatting. Let's see this behavior with an
example,
⬆ Back to Top
⬆ Back to Top
Iterable: It is an object which can be iterated over via a method whose key is Symbol.iterator.
Iterator: It is an object returned by invoking [Symbol.iterator]() on an iterable. This iterator object wraps each iterated element in an object and returns it via next()
method one by one.
IteratorResult: It is an object returned by next() method. The object contains two properties; the value property contains an iterated element and the done property
determines whether the element is the last element or not.
⬆ Back to Top
Note: The event loop allows Node.js to perform non-blocking I/O operations, even though JavaScript is single-threaded, by offloading operations to the system kernel
whenever possible. Since most modern kernels are multi-threaded, they can handle multiple operations executing in the background.
⬆ Back to Top
1. Whenever you call a function for its execution, you are pushing it to the stack.
2. Whenever the execution is completed, the function is popped out of the stack.
function hungry() {
eatFruits();
}
function eatFruits() {
return "I'm eating fruits";
}
3. Add the hungry() function to the call stack list and execute the code.
4. Add the eatFruits() function to the call stack list and execute the code.
5. Delete the eatFruits() function from our call stack list.
6. Delete the hungry() function from the call stack list since there are no items anymore.
Screenshot
⬆ Back to Top
Whenever the call stack receives an async function, it is moved into the Web API. Based on the function, Web API executes it and awaits the result. Once it is finished, it
moves the callback into the event queue (the callback of the promise is moved into the microtask queue).
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
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
1. Collator: These are the objects that enable language-sensitive string comparison.
2. DateTimeFormat: These are the objects that enable language-sensitive date and time formatting.
3. ListFormat: These are the objects that enable language-sensitive list formatting.
4. NumberFormat: Objects that enable language-sensitive number formatting.
5. PluralRules: Objects that enable plural-sensitive formatting and language-specific rules for plurals.
6. RelativeTimeFormat: Objects that enable language-sensitive relative time formatting.
⬆ Back to Top
var a = "Hello";
var b = +a;
console.log(typeof a, typeof b, b); // string, number, NaN
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
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,
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
// Initialize an array a
for (let i = 0; i < a.length; a[i++] = 0);
⬆ Back to Top
⬆ Back to Top
var x = 1;
x = (x++, x);
console.log(x); // 2
⬆ Back to Top
You can also use the comma operator in a return statement where it processes before returning.
function myFunction() {
var a = 1;
return (a += 10), a; // 11
}
⬆ Back to Top
console.log(greeting(user));
⬆ Back to Top
⬆ Back to Top
1. TypeScript is able to find compile time errors at the development time only and it makes sures less runtime errors. Whereas javascript is an interpreted language.
2. TypeScript is strongly-typed or supports static typing which allows for checking type correctness at compile time. This is not available in javascript.
3. TypeScript compiler can compile the .ts files into ES3,ES4 and ES5 unlike ES6 features of javascript which may not be supported in some browsers.
⬆ Back to Top
console.log(initObject.a); // John
⬆ Back to Top
class Employee {
constructor() {
this.name = "John";
}
}
console.log(employeeObject.name); // John
⬆ Back to Top
256. What happens if you write constructor more than once in a class
The "constructor" in a class is a special method and it should be defined only once in a class. i.e, If you write a constructor method more than once in a class it will throw a
SyntaxError error.
class Employee {
constructor() {
this.name = "John";
}
constructor() { // Uncaught SyntaxError: A class may only have one constructor
this.age = 30;
}
}
console.log(employeeObject.name);
⬆ Back to Top
get area() {
return this.width * this.height;
}
set area(value) {
this.area = value;
}
}
⬆ Back to Top
258. How do you get the prototype of an object
You can use the Object.getPrototypeOf(obj) method to return the prototype of the specified object. i.e. The value of the internal prototype property. If there are no
inherited properties then null value is returned.
⬆ Back to Top
// ES5
Object.getPrototypeOf("James"); // TypeError: "James" is not an object
// ES2015
Object.getPrototypeOf("James"); // String.prototype
⬆ Back to Top
Object.setPrototypeOf(Square.prototype, Rectangle.prototype);
Object.setPrototypeOf({}, null);
⬆ Back to Top
Note: By default, all the objects are extendable. i.e, The new properties can be added or modified.
⬆ Back to Top
try {
Object.defineProperty(newObject, "newProperty", {
// Adding new property
value: 100,
});
} catch (e) {
console.log(e); // TypeError: Cannot define property newProperty, object is not extensible
}
⬆ Back to Top
1. Object.preventExtensions
2. Object.seal
3. Object.freeze
⬆ Back to Top
Object.defineProperties(newObject, {
newProperty1: {
value: "John",
writable: true,
},
newProperty2: {},
});
⬆ Back to Top
⬆ Back to Top
function greeting() {
console.log("Hello, welcome to JS world");
}
⬆ Back to Top
1. The Code size will be reduced. So data transfers between server and client will be fast.
2. It hides the business logic from outside world and protects the code from others
3. Reverse engineering is highly difficult
4. The download time will be reduced
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
function validateForm() {
var x = document.forms["myForm"]["uname"].value;
if (x == "") {
alert("The username shouldn't be empty");
return false;
}
}
⬆ Back to Top
<form method="post">
<input type="text" name="uname" required />
<input type="submit" value="Submit" />
</form>
Note: Automatic form validation does not work in Internet Explorer 9 or earlier.
⬆ Back to Top
274. What are the DOM methods available for constraint validation
The below DOM methods are available for constraint validation on an invalid input,
⬆ Back to Top
1. validity: It provides a list of boolean properties related to the validity of an input element.
2. validationMessage: It displays the message when the validity is false.
3. willValidate: It indicates if an input element will be validated or not.
⬆ Back to Top
⬆ Back to Top
function myOverflowFunction() {
if (document.getElementById("age").validity.rangeOverflow) {
alert("The mentioned age is not allowed");
}
}
⬆ Back to Top
⬆ Back to Top
enum Color {
RED, GREEN, BLUE
}
⬆ Back to Top
const newObject = {
a: 1,
b: 2,
c: 3,
};
console.log(Object.getOwnPropertyNames(newObject));
["a", "b", "c"];
⬆ Back to Top
const newObject = {
a: 1,
b: 2,
c: 3,
};
const descriptorsObject = Object.getOwnPropertyDescriptors(newObject);
console.log(descriptorsObject.a.writable); //true
console.log(descriptorsObject.a.configurable); //true
console.log(descriptorsObject.a.enumerable); //true
console.log(descriptorsObject.a.value); // 1
⬆ Back to Top
⬆ Back to Top
get area() {
return this.width * this.height;
}
set area(value) {
this.area = value;
}
}
⬆ Back to Top
⬆ Back to Top
285. How do you check whether an array includes a particular value or not
The Array#includes() method is used to determine whether an array includes a particular value among its entries by returning either true or false. Let's see an example to
find an element(numeric and string) within an array.
⬆ Back to Top
If you would like to compare arrays irrespective of order then you should sort them before,
⬆ Back to Top
⬆ Back to Top
function convertToThousandFormat(x) {
return x.toLocaleString(); // 12,345.679
}
console.log(convertToThousandFormat(12345.6789));
⬆ Back to Top
⬆ Back to Top
function func1() {
console.log("This is a first definition");
}
function func1() {
console.log("This is a second definition");
}
func1(); // This is a second definition
It always calls the second function definition. In this case, namespace will solve the name collision problem.
⬆ Back to Top
1. Using Object Literal Notation: Let's wrap variables and functions inside an Object literal which acts as a namespace. After that you can access them using object
notation
var namespaceOne = {
function func1() {
console.log("This is a first definition");
}
}
var namespaceTwo = {
function func1() {
console.log("This is a second definition");
}
}
namespaceOne.func1(); // This is a first definition
namespaceTwo.func1(); // This is a second definition
2. Using IIFE (Immediately invoked function expression): The outer pair of parentheses of IIFE creates a local scope for all the code inside of it and makes the
anonymous function a function expression. Due to that, you can create the same function in two different function expressions to act as a namespace.
(function () {
function fun1() {
console.log("This is a first definition");
}
fun1();
})();
(function () {
function fun1() {
console.log("This is a second definition");
}
fun1();
})();
3. 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. How do you invoke javascript code in an iframe from parent page
Initially iFrame needs to be accessed using either document.getElementBy or window.frames. After that contentWindow property of iFrame gives the access for
targetFunction
document.getElementById("targetFrame").contentWindow.targetFunction();
window.frames[0].frameElement.contentWindow.targetFunction(); // Accessing iframe this way may not work in latest versions chro
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
295. What are the different methods to find HTML elements in DOM
If you want to access any element in an HTML page, you need to start with accessing the document object. Later you can use any of the below methods to find the HTML
element,
⬆ Back to Top
$(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
⬆ Back to Top
⬆ Back to Top
void expression;
void expression;
Note: This operator is often used to obtain the undefined primitive value, using "void(0)".
⬆ Back to Top
function myFunction() {
window.document.body.style.cursor = "wait";
}
<body onload="myFunction()"></body>
⬆ Back to Top
for (;;) {}
while (true) {}
⬆ Back to Top
a.b.c.greeting = "welcome";
a.b.c.age = 32;
with (a.b.c) {
greeting = "welcome";
age = 32;
}
But this with statement creates performance problems since one cannot predict whether an argument will refer to a real variable or to a property inside the with argument.
⬆ Back to Top
Explanation: Due to the event queue/loop of javascript, the setTimeout callback function is called after the loop has been executed. Since the variable i is declared with the
var keyword it became a global variable and the value was equal to 4 using iteration when the time setTimeout function is invoked. Hence, the output of the second loop is
4 4 4 4.
Whereas in the second loop, the variable i is declared as the let keyword it becomes a block scoped variable and it holds a new value(0, 1 ,2 3) for each iteration. Hence, the
output of the first loop is 0 1 2 3.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
Explanation: The variable declaration with var keyword refers to a function scope and the variable is treated as if it were declared at the top of the enclosing scope due to
hoisting feature. So all the multiple declarations contributing to the same hoisted variable without any error. Let's take an example of re-declaring variables in the same scope
for both var and let/const variables.
var name = "John";
function myFunc() {
var name = "Nick";
var name = "Abraham"; // Re-assigned in the same function block
alert(name); // Abraham
}
myFunc();
alert(name); // John
myFunc();
alert(name);
⬆ Back to Top
⬆ Back to Top
//ES5
var calculateArea = function (height, width) {
height = height || 50;
width = width || 60;
//ES6
var calculateArea = function (height = 50, width = 60) {
return width * height;
};
console.log(calculateArea()); //300
⬆ Back to Top
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
Whereas in ES6, You don't need to mention any newline sequence character,
⬆ Back to Top
You can write the above use case without nesting template features as well. However, the nesting template feature is more compact and readable.
⬆ Back to Top
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}`;
}
⬆ Back to Top
If you don't use raw strings, the newline character sequence will be processed by displaying the output in multiple lines
Also, the raw property is available on the first argument to the tag function
function tag(strings) {
console.log(strings.raw[0]);
}
⬆ Back to Top
console.log(one); // "JAN"
console.log(two); // "FEB"
console.log(three); // "MARCH"
and you can get user properties of an object using destructuring assignment,
console.log(name); // John
console.log(age); // 32
⬆ Back to Top
Arrays destructuring:
var x, y, z;
[x = 2, y = 4, z = 6] = [10];
console.log(x); // 10
console.log(y); // 4
console.log(z); // 6
Objects destructuring:
var { x = 2, y = 4, z = 6 } = { x: 10 };
console.log(x); // 10
console.log(y); // 4
console.log(z); // 6
⬆ Back to Top
var x = 10,
y = 20;
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
1. Import a module on-demand or conditionally. For example, if you want to load a polyfill on legacy browser
if (isLegacyBrowser()) {
import(···)
.then(···);
}
2. Compute the module specifier at runtime. For example, you can use it for internationalization.
import(`messages_${getLocale()}.js`).then(···);
⬆ Back to Top
For example, you can create an array of 8-bit signed integers as below
1. Dynamic loading
2. State isolation
3. Global namespace isolation
4. Compilation hooks
5. Nested virtualization
⬆ Back to Top
1. Comparison:
var list = ["ä", "a", "z"]; // In German, "ä" sorts with "a" Whereas in Swedish, "ä" sorts after "z"
var l10nDE = new Intl.Collator("de");
var l10nSV = new Intl.Collator("sv");
console.log(l10nDE.compare("ä", "z") === -1); // true
console.log(l10nSV.compare("ä", "z") === +1); // true
2. Sorting:
var list = ["ä", "a", "z"]; // In German, "ä" sorts with "a" Whereas in Swedish, "ä" sorts after "z"
var l10nDE = new Intl.Collator("de");
var l10nSV = new Intl.Collator("sv");
console.log(list.sort(l10nDE.compare)); // [ "a", "ä", "z" ]
console.log(list.sort(l10nSV.compare)); // [ "a", "z", "ä" ]
⬆ Back to Top
⬆ Back to Top
[..."John Resig"];
The output of the array is ['J', 'o', 'h', 'n', ' ', 'R', 'e', 's', 'i', 'g']
Explanation: The string is an iterable type and the spread operator within an array maps every character of an iterable to one element. Hence, each character of a string
becomes an element within an Array.
⬆ Back to Top
326. What are the problems with postmessage target origin as wildcard
The second argument of postMessage method specifies which origin is allowed to receive the message. If you use the wildcard “*” as an argument then any origin is allowed
to receive the message. In this case, there is no way for the sender window to know if the target window is at the target origin when sending the message. If the target window
has been navigated to another origin, the other origin would receive the data. Hence, this may lead to XSS vulnerabilities.
targetWindow.postMessage(message, "*");
⬆ Back to Top
For example, let's check the sender's origin http://www.some-sender.com (http://www.some-sender.com) on receiver side www.some-receiver.com (www.some-receiver.com),
//Listener on http://www.some-receiver.com/
window.addEventListener("message", function(message){
if(/^http://www\.some-sender\.com$/.test(message.origin)){
console.log('You received the data from valid sender', message.data);
}
});
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
"ABC".charCodeAt(0); // returns 65
⬆ Back to Top
⬆ Back to Top
console.log("Welcome to JS world"[0]);
The output of the above expression is "W". Explanation: The bracket notation with specific index on a string returns the character at a specific location. Hence, it returns the
character "W" of the string. Since this is not supported in IE7 and below versions, you may need to use the .charAt() method to get the desired result.
⬆ Back to Top
You can throw user defined exceptions or errors using Error object in try...catch block as below,
try {
if (withdraw > balance)
throw new Error("Oops! You don't have enough balance");
} catch (e) {
console.log(e.name + ": " + e.message);
}
⬆ Back to Top
try {
throw new EvalError('Eval function error', 'someFile.js', 100);
} catch (e) {
console.log(e.message, e.name, e.fileName); // "Eval function error", "EvalError", "someFile.js"
⬆ Back to Top
340. 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
var n = 022;
if (someCondition) {
function f() {}
}
f(); // ReferenceError: f is not defined
Hence, the errors from above cases are helpful to avoid errors in development/production environments.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
Let's take an example of array's concatenation with veggies and fruits arrays,
⬆ Back to Top
Shallow Copy: Shallow copy is a bitwise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object
are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.
Example
var empDetails = {
name: "John",
age: 25,
expertise: "Software Developer",
};
to create a duplicate
empDetailsShallowCopy.name = "Johnson";
The above statement will also change the name of empDetails, since we have a shallow copy. That means we're losing the original data as well.
Deep copy: A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along
with the objects to which it refers.
Example
var empDetails = {
name: "John",
age: 25,
expertise: "Software Developer",
};
Create a deep copy by using the properties from the original object into new variable
var empDetailsDeepCopy = {
name: empDetails.name,
age: empDetails.age,
expertise: empDetails.expertise,
};
Now if you change empDetailsDeepCopy.name, it will only affect empDetailsDeepCopy & not empDetails
⬆ Back to Top
"Hello".repeat(4); // 'HelloHelloHelloHello'
347. How do you return all matching strings against a regular expression
The matchAll() method can be used to return an iterator of all results matching a string against a regular expression. For example, the below example returns an array of
matching string results against a regular expression,
console.log(greetingList[0][0]); //Hello1
console.log(greetingList[1][0]); //Hello2
console.log(greetingList[2][0]); //Hello3
⬆ Back to Top
⬆ Back to Top
349. What is the output of below console statement with unary operator
Let's take console statement with unary operator as given below,
console.log(+"Hello"); // NaN
The output of the above console log statement returns NaN. Because the element is prefixed by the unary operator and the JavaScript interpreter will try to convert that
element into a number type. Since the conversion fails, the value of the statement results in NaN value.
⬆ Back to Top
But sometimes we require to extend more than one, to overcome this we can use Mixin which helps to copy methods to the prototype of another class.
Say for instance, we've two classes User and CleanRoom. Suppose we need to add CleanRoom functionality to User, so that user can clean the room at demand. Here's
where concept called mixins comes into picture.
// mixin
let cleanRoomMixin = {
cleanRoom() {
alert(`Hello ${this.name}, your room is clean now`);
},
sayBye() {
alert(`Bye ${this.name}`);
},
};
// usage:
class User {
constructor(name) {
this.name = name;
}
}
⬆ Back to Top
thunk(); // 5
⬆ Back to Top
asyncThunk();
The getData function won't be called immediately but it will be invoked only when the data is available from API endpoint. The setTimeout function is also used to make our
code asynchronous. The best real time example is redux state management library which uses the asynchronous thunks to delay the actions to dispatch.
⬆ Back to Top
const circle = {
radius: 20,
diameter() {
return this.radius * 2;
},
perimeter: () => 2 * Math.PI * this.radius,
};
console.log(circle.diameter());
console.log(circle.perimeter());
Output:
The output is 40 and NaN. Remember that diameter is a regular function, whereas the value of perimeter is an arrow function. The this keyword of a regular function(i.e,
diameter) refers to the surrounding scope which is a class(i.e, Shape object). Whereas this keyword of perimeter function refers to the surrounding scope which is a window
object. Since there is no radius property on window objects it returns an undefined value and the multiple of number value returns NaN value.
⬆ Back to Top
In the above expression, g and m are for global and multiline flags.
⬆ Back to Top
⬆ Back to Top
console.log(![]); // false
⬆ Back to Top
⬆ Back to Top
console.log(+null); // 0
console.log(+undefined); // NaN
console.log(+false); // 0
console.log(+NaN); // NaN
console.log(+""); // 0
⬆ Back to Top
1. Since Arrays are truthful values, negating the arrays will produce false: ![] === false
2. As per JavaScript coercion rules, the addition of arrays together will toString them: [] + [] === ""
3. Prepend an array with + operator will convert an array to false, the negation will make it true and finally converting the result will produce value '1': +(!(+[])) === 1
s e l f
^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^
⬆ Back to Top
⬆ Back to Top
const obj = { x: 1 };
// Grabs obj.x as as { otherName }
const { x: otherName } = obj;
⬆ Back to Top
363. 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,
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" },
];
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
1. %o — It takes an object,
2. %s — It takes a string,
3. %d — It is used for a decimal or integer These placeholders can be represented in the console.log as below
⬆ Back to Top
console.log(
"%c The text has blue color, with large font and red background",
"color: blue; font-size: x-large; background: red"
);
Screenshot
⬆ Back to Top
⬆ Back to Top
Screenshot
⬆ Back to Top
372. How do you display data in a tabular format using console object
The console.table() is used to display data in the console in a tabular format to visualize complex arrays or objects.
const users = [
{ name: "John", id: 1, city: "Delhi" },
{ name: "Max", id: 2, city: "London" },
{ name: "Rod", id: 3, city: "Paris" },
];
console.table(users);
Screenshot
⬆ Back to Top
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
⬆ Back to Top
document.querySelector("#copy-button").onclick = function () {
// Select the content
document.querySelector("#copy-input").select();
// Copy to the clipboard
document.execCommand("copy");
};
⬆ Back to Top
console.log(+new Date());
console.log(Date.now());
⬆ Back to Top
const biDimensionalArr = [11, [22, 33], [44, 55], [66, 77], 88, 99];
const flattenArr = [].concat(...biDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
But you can make it work with multi-dimensional arrays by recursive calls,
function flattenMultiArray(arr) {
const flattened = [].concat(...arr);
return flattened.some((item) => Array.isArray(item))
? flattenMultiArray(flattened)
: flattened;
}
const multiDimensionalArr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];
const flatArr = flattenMultiArray(multiDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
⬆ Back to Top
⬆ Back to Top
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 color and changed to while color upon clic
⬆ Back to Top
i.e, Every primitive except null and undefined have Wrapper Objects and the list of wrapper objects are String,Number,Boolean,Symbol and BigInt.
⬆ Back to Top
381. 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. What are the different ways to deal with Asynchronous Code
Below are the list of different ways to deal with Asynchronous code.
1. Callbacks
2. Promises
3. Async/await
4. Third-party libraries such as async.js,bluebird etc
⬆ Back to Top
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!
}
});
⬆ Back to Top
1. SpeechRecognition (Asynchronous Speech Recognition or Speech-to-Text): It provides the ability to recognize voice context from an audio input and respond
accordingly. This is accessed by the SpeechRecognition interface. The example below shows how to use this API to get text from speech,
window.SpeechRecognition =
window.webkitSpeechRecognition || window.SpeechRecognition; // webkitSpeechRecognition for Chrome and SpeechRecognition for F
const recognition = new window.SpeechRecognition();
recognition.onresult = (event) => {
// SpeechRecognitionEvent type
const speechToText = event.results[0][0].transcript;
console.log(speechToText);
};
recognition.start();
In this API, browser is going to ask you for permission to use your microphone
2. SpeechSynthesis (Text-to-Speech): It provides the ability to recognize voice context from an audio input and respond. This is accessed 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 specification)
⬆ Back to Top
function runMeFirst() {
console.log("My script is initialized");
}
setTimeout(runMeFirst, 0);
console.log("Script loaded");
Script loaded
My script is initialized
function runMeFirst() {
console.log("My script is initialized");
}
runMeFirst();
console.log("Script loaded");
My script is initialized
Script loaded
⬆ Back to Top
⬆ Back to Top
387. What are tasks in event loop
A task is any javascript code/program which is scheduled to be run by the standard mechanisms such as initially starting to run a program, run an event callback, or an interval
or timeout being fired. All these tasks are scheduled on a task queue. Below are the list of use cases to add tasks to the task queue,
1. When a new javascript program is executed directly from console or running by the <script> element, the task will be added to the task queue.
2. When an event fires, the event callback added to task queue
3. When a setTimeout or setInterval is reached, the corresponding callback added to task queue
⬆ Back to Top
Note: All of these microtasks are processed in the same turn of the event loop.
⬆ Back to Top
Browser Event Loop: The Browser Event Loop is used in client-side JavaScript applications and is responsible for handling events that occur within the browser environment,
such as user interactions (clicks, keypresses, etc.), HTTP requests, and other asynchronous actions.
The Node.js Event Loop is used in server-side JavaScript applications and is responsible for handling events that occur within the Node.js runtime environment, such as file
I/O, network I/O, and other asynchronous actions.
⬆ Back to Top
Example:
console.log("Start"); //1
queueMicrotask(() => {
console.log("Inside microtask"); // 3
});
console.log("End"); //2
By using queueMicrotask, you can ensure that certain tasks or callbacks are executed at the earliest opportunity during the JavaScript event loop, making it useful for
performing work that needs to be done asynchronously but with higher priority than regular setTimeout or setInterval callbacks.
⬆ Back to Top
In the runtime, typescript will provide the type to the customLibrary variable as any type. The another alternative without using declare keyword is below
Promises Observables
Emits multiple values over a period of time(stream of values ranging
Emits only a single value at a time
from 0 to multiple)
Eager in nature; they are going to be called immediately Lazy in nature; they require subscription to be invoked
Promise is always asynchronous even though it resolved
Observable can be either synchronous or asynchronous
immediately
Provides operators such as map, forEach, filter, reduce, retry, and
Doesn't provide any operators
retryWhen etc
Cannot be canceled Canceled by using unsubscribe() method
⬆ Back to Top
Screenshot
⬆ Back to Top
Screenshot
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
397. 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,
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
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
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
402. What is the difference between Function constructor and function declaration
The functions which are created with Function constructor do not create closures to their creation contexts but they are always created in the global scope. i.e, the
function can access its own local variables and global scope variables only. Whereas function declarations can access outer function variables(closures) too.
Function Constructor:
var a = 100;
function createFunction() {
var a = 200;
return new Function("return a;");
}
console.log(createFunction()()); // 100
Function declaration:
var a = 100;
function createFunction() {
var a = 200;
return function func() {
return a;
};
}
console.log(createFunction()()); // 200
⬆ Back to Top
if (authenticate) {
loginToPorta();
}
Since the javascript logical operators evaluated from left to right, the above expression can be simplified using && logical operator
⬆ Back to Top
array.length = 2;
console.log(array.length); // 2
console.log(array); // [1,2]
⬆ Back to Top
Note: Observables are not part of the JavaScript language yet but they are being proposed to be added to the language
⬆ Back to Top
Classes:
class User {}
Constructor Function:
function User() {}
⬆ Back to Top
⬆ Back to Top
Let's say you expect to print an error to the console for all the below cases,
Promise.resolve("promised value").then(function () {
throw new Error("error");
});
Promise.reject("error value").catch(function () {
throw new Error("error");
});
But there are many modern JavaScript environments that won't print any errors. You can fix this problem in different ways,
1. Add catch block at the end of each chain: You can add catch block to the end of each of your promise chains
Promise.resolve("promised value")
.then(function () {
throw new Error("error");
})
.catch(function (error) {
console.error(error.stack);
});
But it is quite difficult to type for each promise chain and verbose too.
2. Add done method: You can replace first solution's then and catch blocks with done method
Promise.resolve("promised value").done(function () {
throw new Error("error");
});
Let's say you want to fetch data using HTTP and later perform processing on the resulting data asynchronously. You can write done block as below,
getDataFromHttp()
.then(function (result) {
return processDataAsync(result);
})
.done(function (processed) {
displayData(processed);
});
In future, if the processing library API changed to synchronous then you can remove done block as below,
getDataFromHttp().then(function (result) {
return displayData(processDataAsync(result));
});
and then you forgot to add done block to then block leads to silent errors.
3. Extend ES6 Promises by Bluebird: Bluebird extends the ES6 Promises API to avoid the issue in the second solution. This library has a “default” onRejection handler
which will print all errors from rejected Promises to stderr. After installation, you can process unhandled rejections
Promise.onPossiblyUnhandledRejection(function (error) {
throw error;
});
⬆ Back to Top
409. What is deno
Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 JavaScript engine and the Rust programming language. It solves the inherent
problems of Node.Js and has been officially released in May 2018. Unlike Node.JS, by default Deno executes the code in a sandbox, which means that runtime has no access
to below areas:
⬆ Back to Top
const collection = {
one: 1,
two: 2,
three: 3,
[Symbol.iterator]() {
const values = Object.keys(this);
let i = 0;
return {
next: () => {
return {
value: this[values[i++]],
done: i > values.length,
};
},
};
},
};
const collection = {
one: 1,
two: 2,
three: 3,
[Symbol.iterator]: function* () {
for (let key in this) {
yield this[key];
}
},
};
const iterator = collection[Symbol.iterator]();
console.log(iterator.next()); // {value: 1, done: false}
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
For example, the below classic or head recursion of factorial function relies on stack for each step. Each step need to be processed upto n * factorial(n - 1)
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); //120
But if you use Tail recursion functions, they keep passing all the necessary data it needs down the recursion without relying on the stack.
The above pattern returns the same output as the first one. But the accumulator keeps track of total as an argument without using stack memory on recursive calls.
⬆ Back to Top
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
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
function Myfunc() {
if (new.target) {
console.log("called with new");
} else {
console.log("not called with new");
}
}
⬆ Back to Top
414. What are the differences between arguments object and rest parameter
There are three main differences between arguments object and rest parameters
1. The arguments object is an array-like but not an array. Whereas the rest parameters are array instances.
2. The arguments object does not support methods such as sort, map, forEach, or pop. Whereas these methods can be used in rest parameters.
3. The rest parameters are only the ones that haven’t been given a separate name, while the arguments object contains all arguments passed to the function
⬆ Back to Top
415. What are the differences between spread operator and rest parameter
Rest parameter collects all remaining elements into an array. Whereas Spread operator allows iterables( arrays / objects / strings ) to be expanded into single
arguments/elements. i.e, Rest parameter is opposite to the spread operator.
⬆ Back to Top
function* myGenFunc() {
yield 1;
yield 2;
yield 3;
}
const genObj = myGenFunc();
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();
const SomeObj = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
},
};
console.log(Array.from(SomeObj)); // [ 1, 2, 3 ]
⬆ Back to Top
⬆ Back to Top
418. What are the differences between for...of and for...in statements
Both for...in and for...of statements iterate over js data structures. The only difference is over what they iterate:
arr.newProp = "newVlue";
Since for..in loop iterates over the keys of the object, the first loop logs 0, 1, 2 and newProp while iterating over the array object. The for..of loop iterates over the values of a
arr data structure and logs a, b, c in the console.
⬆ Back to Top
419. 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
isNaN(‘hello’); // true
Number.isNaN('hello'); // false
⬆ Back to Top
(function (dt) {
console.log(dt.toLocaleTimeString());
})(new Date());
Since both IIFE and void operator discard the result of an expression, you can avoid the extra brackets using void operator for IIFE as below,
⬆ Back to Top
⬆ Back to Top
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
⬆ Back to Top
console.group("User Details");
console.log("name: Sudheer Jonna");
console.log("job: Software Developer");
// Nested Group
console.group("Address");
console.log("Street: Commonwealth");
console.log("City: Los Angeles");
console.log("State: California");
You can also use console.groupCollapsed() instead of console.group() if you want the groups to be collapsed by default.
⬆ Back to Top
427. What is the difference between dense and sparse arrays?
An array contains items at each index starting from first(0) to last(array.length - 1) is called as Dense array. Whereas if at least one item is missing at any index, the array is
called as sparse.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
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.
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [ 5, 4, 3, 2, 1]
2. Using spread and reverse methods: In this case, let's use the spread syntax (...) to create a copy of the array followed by reverse() method call on the copy.
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [ 5, 4, 3, 2, 1]
3. Using reduce and spread methods: Here execute a reducer function on an array elements and append the accumulated array on right side using spread syntax
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
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [ 5, 4, 3, 2, 1]
5. Using reduceRight and push methods: Here execute a right reducer function(i.e. opposite direction of reduce method) on an array elements and push the iterated
value to the accumulator
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [ 5, 4, 3, 2, 1]
⬆ Back to Top
2. Use custom element just like other HTML element: Declare your custom element as a HTML tag.
<body>
<custom-element>
</body>
⬆ Back to Top
For example, the below code other than code inside any function or object is executed inside the global execution context.
var x = 10;
function A() {
console.log("Start function A");
function B() {
console.log("In function B");
}
B();
}
A();
console.log("GlobalContext");
⬆ Back to Top
⬆ Back to Top
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 function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, timeout);
};
}
function fetchResults() {
console.log("Fetching input suggestions");
}
const processChange = debounce(() => fetchResults());
The debounce() function can be used on input, button and window events.
Input:
Button:
Windows event:
window.addEventListener("scroll", processChange);
⬆ Back to Top
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.
⬆ Back to Top
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
Environment Record (https://262.ecma-international.org/12.0/#sec-environment-records) is a specification type used to define the association of Identifiers to specific
variables and functions, based upon the lexical nesting structure of ECMAScript code.
Usually an Environment Record is associated with some specific syntactic structure of ECMAScript code such as a FunctionDeclaration, a BlockStatement, or a Catch clause
of a TryStatement.
Each time such code is evaluated, a new Environment Record is created to record the identifier bindings that are created by that code.
⬆ Back to Top
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.
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.
The constructor property of the variable is used to determine whether the variable Array type or not.
⬆ Back to Top
439. What is pass by value and pass by reference?
Pass-by-value creates a new space in memory and makes a copy of a value. Primitives such as string, number, boolean etc will actually create a new copy. Hence, updating
one value doesn't impact the other value. i.e, The values are independent of each other.
let a = 5;
let b = a;
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;
In the above code snippet, updating the age property of one object will impact the other property due to the same reference.
⬆ Back to Top
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 inorder to use it as other builtin functions. This custom function should return a function similar to original
bind method and the implementation of inner function needs to use apply method call.
The function which is going to bind using custom myOwnBind method act as the attached function(boundTargetFunction) and argument as the object for apply method
call.
⬆ Back to Top
442. What are the differences between pure and impure functions?
Some of the major differences between pure and impure function are as below,
Pure function Impure function
It has no side effects It causes side effects
It is always return the same result It returns different result on each call
Easy to read and debug Difficult to read and debug because they are affected by external code
⬆ Back to Top
multiplyBy2(add(2, 3));
⬆ Back to Top
Making an HTTP request. Asynchronous functions such as fetch and promise are impure.
DOM manipulations
Mutating the input data
Printing to a screen or console: For example, console.log() and alert()
Fetching the current time
Math.random() calls: Modifies the internal state of Math object
⬆ Back to Top
⬆ Back to Top
(function () {
// Private variables or functions goes here.
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
//example
const double = (x) => x * 2;
const square = (x) => x * x;
⬆ Back to Top
But you can fix this issue with an alternative IIFE (Immediately Invoked Function Expression) to get access to the feature.
(async function () {
await Promise.resolve(console.log("Hello await")); // Hello await
})();
In ES2022, you can write top-level await without writing any hacks.
⬆ Back to Top
console.log(this);
In a global context, this refers to the global object (e.g., window in a browser).
function displayThis() {
console.log(this);
}
displayThis();
const person = {
name: 'John',
greet: function() {
console.log('Hello, ' + this.name);
}
};
person.greet();
In a method, this refers to the object that owns the method (person in the case).
document.getElementById('myButton').addEventListener('click', function() {
console.log(this);
});
In an event handler, this refers to the element that triggered the event (the button in this case).
⬆ Back to Top
Data Privacy: Closures can be used to create private variables and methods. By defining variables within a function's scope and returning inner functions that have access to
those variables, you can create a form of encapsulation, limiting access to certain data or functionality.
Function Factories: Closures are often used to create functions with pre-set parameters. This is useful when you need to create multiple functions with similar behavior but
different configurations.
Callback Functions: Closures are frequently used in asynchronous programming, such as handling event listeners or AJAX requests. The inner function captures variables
from the outer scope and can access them when the callback is invoked.
Memoization: Closures can be used for memoization, a technique to optimize performance by caching the results of expensive function calls. The inner function can
remember the results of previous calls and return the cached result if the same input is provided again.
iterators and Generators: Closures can be used to create iterators and generators, which are essential for working with collections of data in modern JavaScript.
⬆ Back to Top
The execution context is created when a function is called. The function's code is then executed in the execution context. When the function returns, the execution context is
destroyed.
⬆ Back to Top
1. The execessive usage of global variables or omitting the var keyword in local scope.
2. Forgetting to clear the timers set up by setTimeout or setInterval.
3. Closures retain references to variables from their parent scope, which leads to variables might not garbage collected even they are no longer used.
1. Inline expansion: It is a compiler optimization by replacing the function calls with the corresponding function blocks.
2. Copy elision: This is a compiler optimization method to prevent expensive extra objects from being duplicated or copied.
3. Inline caching: It is a runtime optimization technique where it caches the execution of older tasks those can be lookup while executing the same task in the future.
⬆ Back to Top
⬆ Back to Top
1. Abstraction
2. Reusability
3. Immutability
4. Modularity
⬆ Back to Top
456. How do you create polyfills for map, filter and reduce methods?
The polyfills for array methods such as map, filter and reduce methods can be created using array prototype.
1. map:
The built-in Array.map method syntax will be helpful to write polyfill. The map method takes the callback function as an argument and that callback function can have below
three arguments passed into it.
i. Current value
ii. Index of current value(optional)
iii. array(optional)
In the above code, custom method name 'myMap' has been used to avoid conflicts with built-in method.
2. filter: Similar to map method, Array.filter method takes callback function as an argument and the callback function can have three agurguments passed into it.
i. Current value
ii. Index of current value(optional)
iii. array(optional)
Array.prototype.myFilter = function(cb) {
let newArr = [];
for(let i=0; i< this.length; i++) {
if(cb(this[i], i, this)) {
newArr.push(this[i]);
}
}
return newArr;
}
3. reduce:
The built-in Array.reduce method syntax will be helpful to write our own polyfill. The reduce method takes the callback function as first argument and the initial value as
second argument.
The callback function can have four arguments passed into it.
i. Accumulator
ii. Current value
iii. Index of current value(optional)
iv. array(optional)
⬆ Back to Top
1. Returning values: The map method returns a new array with transformed elements whereas forEach method returns undefined eventhough both of them are
doing the same job.
The `forEach()` method in JavaScript always returns undefined. This is because forEach() is used to iterate over arrays and p
2. Chaining methods: The map method is chainable. i.e, It can be attached with reduce, filter, sort and other methods as well. Whereas forEach cannot be
attached with any other methods because it returns undefined value.
3. Mutation: The map method doesn't mutate the original array by returning new array. Whereas forEach method also doesn't mutate the original array but it's callback
is allowed to mutate the original array.
⬆ Back to Top
1. An empty statement
2. var statement
3. An expression statement
4. do-while statement
5. continue statement
6. break statement
7. return statement
8. throw statement
⬆ Back to Top
1. Capturing phase: This phase goes down gradually from the top of the DOM tree to the target element when a nested element clicked. Before the click event reaching
the final destination element, the click event of each parent's element must be triggered.
2. Target phase: This is the phase where the event originally occurred reached the target element .
3. Bubbling phase: This is reverse of the capturing phase. In this pase, the event bubbles up from the target element through it's parent element, an ancestor and goes
all the way to the global window object.
The pictorial representation of these 3 event phases in DOM looks like below,
Screenshot
⬆ Back to Top
⬆ Back to Top
Let's consider the following example to see how the additional properties age and gender added at runtime.
function Person(name) {
this.name = name;
}
person1.age = 40;
person1.gender = "Male";
person2.gender = "Female";
person2.age = 50;
As a result, this behavior leads to lower JavaScript performance compared to the contiguous buffer method used in non-dynamic languages. The V8 engine provided a
solution named hidden classes to optimize the access time when retrieving a property on an object. This optimization is achieved by sharing hidden classes among objects
created in a similar fashion. These hidden classes are attached to each and every object to track its shape.
When V8 engine sees the constructor function(e.g, Person) is declared, it creates a hidden class (let's say Class01) without any offsets. Once the first property assignment
statement (this.name = name) is executed, V8 engine will create a new hidden class (let's say Class02), inheriting all properties from the previous hidden class (Class01),
and assign the property to offset 0. This process enables compiler to skip dictionary lookup when you try to retrieve the same property(i.e, name). Instead, V8 will directly point
to Class02. The same procedure happens when you add new properties to the object.
For example, adding age and gender properties to Person constructor leads to transition of hidden classes(Class02 -> Class03 -> Class04). If you create a second
object(Person2) based on the same Person object, both Class01 and Class02 hidden classes are going to be shared. However, the hidden classes Class03 and Class04
cannot be shared because second object has been modified with a different order of properties assignment.
Since both the objects(person1 and person2) do not share the hidden classes, now V8 engine cannot use Inline Caching technique for the faster access of properties.
⬆ Back to Top
let shape = {width : 30, height: 20}; // Compiler store the type in cache as { width: <int>, height: <int>} after repeated calls
function area(obj) {
//Calculate area
}
for(let i=0; i<100; i++) {
area(shape);
}
After few successful calls of the same area method to its same hidden class, V8 engine omits the hidden class lookup and simply adds the offset of the property to the object pointer
itself. As a result, it increases the execution speed.
1. Monomorphic: This is a optimized caching technique in which there can be always same type of objects passed.
2. Polymorphic: This ia slightly optimized caching technique in which limited number of different types of objects can be passed.
3. Megamorphic: It is an unoptimized caching in which any number of different objects can be passed.
⬆ Back to Top
1. async: The script is downloaded in parallel to parsing the page, and executed as soon as it is available even before parsing completes. The parsing of the page is
going to be interuppted once the script is downloaded completely and then the script is executed. Thereafter, the parsing of the remaining page will continue.
2. defer: The script is downloaded in parallel to parsing the page, and executed after the page has finished parsing.
3. Neither async or defer: The script is downloaded and executed immediately by blocking parsing of the page until the script execution is completed.
Note: You should only use either async or defer attribute if the src attribute is present.
⬆ Back to Top
<script>
function x(){
var a=10;
function y(){
console.log(a); // will print a , because of lexical scope, it will first look 'a' in
//its local memory space and then in its parent functions memory space
}
y();
}
x();
</script>
⬆ Back to Top
You can also watch changes to system color scheme using addEventListener,
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", (event) => {
const theme = event.matches ? "dark" : "light";
});
Note: The matchMedia method returns MediaQueryList object stores information from a media query.
⬆ Back to Top
The two parameters of substr() are start and length, while for substring(), they are start and end.
substr()'s start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0.
Negative lengths in substr() are treated as zero, while substring() will swap the two indexes if end is less than start.
Furthermore, substr() is considered a legacy feature in ECMAScript, so it is best to avoid using it if possible.
⬆ Back to Top
function multiply(x, y) {
return x * y;
}
function sum(a, b, c) {
return a + b +c;
}
console.log(multiply.length); //2
console.log(sum.length); //3
But there are few important rules which needs to be noted while using length property.
1. Default values: Only the parameters which exists before a default value are considered.
2. Rest params: The rest parameters are excluded with in length property.
function sum(a, b, ...moreArgs) {
let total = a + b;
for (const arg of moreArgs) {
total += arg;
}
return total;
}
console.log(sum.length); // 2
console.log(func.length); // 2
Note: The Function constructor is itself a function object and it has a length property of 1.
⬆ Back to Top
1. In web browser, the global object is accessible via window, self, or frames.
2. In Node environment, you have to use global.
3. In Web workers, the global object is available through self.
The globalThis property provides a standard way of accessing the global object without writing various code snippet to support multiple environments. For example, the global
object retuned from multiple environments as shown below,
⬆ Back to Top
1. Mutating methods: These are the methods that directly modify the original array.
2. Non-mutating methods: These methods return a new array without altering the original one.
1. push: Adds one or more elements to the end of the array and returns the new length.
2. pop: Removes the last element from the array and returns that element.
3. unshift: Adds one or more elements to the beginning of the array and returns the new length..
4. shift: Removes the first element from the array and returns that element.
5. splice: Adds or removes elements from the array at a specific index position.
6. sort: Sorts the elements of the array in-place based on a given sorting criteria.
7. reverse: Reverses the order of elements in the given array.
8. fill: Fills all elements of the array with a specific value.
9. copyWithIn: Copies a sequence of elements within the array to a specified target index in the same array.
⬆ Back to Top
Coding Exercise
1. What is the output of below code
1: Undefined
2: ReferenceError
3: null
4: {model: "Honda", color: "white", year: "2010", country: "UK"}
Answer
⬆ Back to Top
function foo() {
let x = (y = 0);
x++;
y++;
return x;
}
Answer
⬆ Back to Top
function main() {
console.log("A");
setTimeout(function print() {
console.log("B");
}, 0);
console.log("C");
}
main();
1: A, B and C
2: B, A and C
3: A and C
4: A, C and B
Answer
⬆ Back to Top
1: false
2: true
Answer
⬆ Back to Top
var y = 1;
if (function f() {}) {
y += typeof f;
}
console.log(y);
1: 1function
2: 1object
3: ReferenceError
4: 1undefined
Answer
⬆ Back to Top
function foo() {
return;
{
message: "Hello World";
}
}
console.log(foo());
1: Hello World
2: Object {message: "Hello World"}
3: Undefined
4: SyntaxError
Answer
⬆ Back to Top
Answer
⬆ Back to Top
Answer
⬆ Back to Top
const obj = {
prop1: function () {
return 0;
},
prop2() {
return 1;
},
["prop" + 3]() {
return 2;
},
};
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
⬆ Back to Top
1: true, true
2: true, false
3: SyntaxError, SyntaxError,
4: false, false
Answer
⬆ Back to Top
Answer
⬆ Back to Top
1: 1, 2, 3
2: 3, 2, 3
3: SyntaxError: Duplicate parameter name not allowed in this context
4: 1, 2, 1
Answer
⬆ Back to Top
Answer
⬆ Back to Top
1: True, False
2: False, True
Answer
⬆ Back to Top
console.log(Math.max());
1: undefined
2: Infinity
3: 0
4: -Infinity
Answer
⬆ Back to Top
1: True, True
2: True, False
3: False, False
4: False, True
Answer
⬆ Back to Top
console.log(10 + "10");
console.log(10 - "10");
1: 20, 0
2: 1010, 0
3: 1010, 10-10
4: NaN, NaN
Answer
⬆ Back to Top
console.log([0] == false);
if ([0]) {
console.log("I'm True");
} else {
console.log("I'm False");
}
Answer
1: [1,2,3,4]
2: [1,2][3,4]
3: SyntaxError
4: 1,23,4
Answer
⬆ Back to Top
⬆ Back to Top
1: True
2: False
Answer
⬆ Back to Top
1: 4
2: NaN
3: SyntaxError
4: -1
Answer
⬆ Back to Top
1: 1, [2, 3, 4, 5]
2: 1, {2, 3, 4, 5}
3: SyntaxError
4: 1, [2, 3, 4]
Answer
⬆ Back to Top
Answer
⬆ Back to Top
Answer
⬆ Back to Top
function delay() {
return new Promise(resolve => setTimeout(resolve, 2000));
}
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
function delay() {
return new Promise((resolve) => setTimeout(resolve, 2000));
}
Answer
⬆ Back to Top
Answer
⬆ Back to Top
1: true, true
2: true, false
3: false, true
4: false, false
Answer
⬆ Back to Top
1: SyntaxError
2: one
3: Symbol('one')
4: Symbol
Answer
⬆ Back to Top
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
console.log(
JSON.stringify({ myArray: ["one", undefined, function () {}, Symbol("")] })
);
console.log(
JSON.stringify({ [Symbol.for("one")]: "one" }, [Symbol.for("one")])
);
Answer
⬆ Back to Top
class A {
constructor() {
console.log(new.target.name);
}
}
class B extends A {
constructor() {
super();
}
}
new A();
new B();
1: A, A
2: A, B
Answer
⬆ Back to Top
1: 1, [2, 3], 4
2: 1, [2, 3, 4], undefined
3: 1, [2], 3
4: SyntaxError
Answer
⬆ 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
⬆ Back to Top
const props = [
{ id: 1, name: "John" },
{ id: 2, name: "Jack" },
{ id: 3, name: "Tom" },
];
1: Tom
2: Error
3: undefined
4: John
Answer
⬆ Back to Top
function checkType(num = 1) {
console.log(typeof num);
}
checkType();
checkType(undefined);
checkType("");
checkType(null);
⬆ Back to Top
console.log(add("Orange"));
console.log(add("Apple"));
Answer
⬆ 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
1: ReferenceError
2: Inner
Answer
⬆ Back to Top
myFun(1, 2, 3, 4, 5);
myFun(1, 2);
Answer
⬆ Back to Top
1: ['key', 'value']
2: TypeError
3: []
4: ['key']
Answer
⬆ Back to Top
function* myGenFunc() {
yield 1;
yield 2;
yield 3;
}
var myGenObj = new myGenFunc();
console.log(myGenObj.next().value);
1: 1
2: undefined
3: SyntaxError
4: TypeError
Answer
⬆ Back to Top
function* yieldAndReturn() {
yield 1;
return 2;
yield 3;
}
1: { value: 1, done: false }, { value: 2, done: true }, { value: undefined, done: true }
2: { value: 1, done: false }, { value: 2, done: false }, { value: undefined, done: true }
3: { value: 1, done: false }, { value: 2, done: true }, { value: 3, done: true }
4: { value: 1, done: false }, { value: 2, done: false }, { value: 3, done: true }
Answer
⬆ Back to Top
Answer
⬆ Back to Top
1: SyntaxError
2: 38
Answer
⬆ 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;
};
1: undefined, undefined
2: Person, Person
3: SyntaxError
4: Window, Window
Answer
⬆ Back to Top
class Vehicle {
constructor(name) {
this.name = name;
}
start() {
console.log(`${this.name} vehicle started`);
}
}
1: SyntaxError
2: BMW vehicle started, BMW car started
3: BMW car started, BMW vehicle started
4: BMW car started, BMW car started
Answer
⬆ Back to Top
1: 30
2: 25
3: Uncaught TypeError
4: SyntaxError
Answer
⬆ Back to Top
1: false
2: true
Answer
⬆ Back to Top
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
⬆ Back to Top
msg.name = "John";
console.log(msg.name);
1: ""
2: Error
3: John
4: Undefined
Answer
⬆ 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
⬆ Back to Top
Answer
⬆ Back to Top
console.log(arr == str);
1: false
2: Error
3: true
Answer
⬆ Back to Top
getMessage();
1: Good morning
2: getMessage is not a function
3: getMessage is not defined
4: Undefined
Answer
⬆ 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
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
⬆ Back to Top
var of = ["of"];
for (var of of of) {
console.log(of);
}
1: of
2: SyntaxError: Unexpected token of
3: SyntaxError: Identifier 'of' has already been declared
4: ReferenceError: of is not defined
Answer
⬆ Back to Top
Answer
⬆ Back to Top
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
⬆ Back to Top
console.log(name);
console.log(message());
var name = "John";
(function message() {
console.log("Hello John: Welcome");
});
Answer
⬆ Back to Top
message();
function message() {
console.log("Hello");
}
function message() {
console.log("Bye");
}
Answer
⬆ Back to Top
changeCurrentCity();
1: NewYork, Singapore
2: NewYork, NewYork
3: undefined, Singapore
4: Singapore, Singapore
Answer
⬆ Back to Top
function second() {
var message;
console.log(message);
}
function first() {
var message = "first";
second();
console.log(message);
}
Answer
⬆ Back to Top
Answer
⬆ Back to Top
const user = {
name: "John",
eat() {
console.log(this);
var eatFruit = function () {
console.log(this);
};
eatFruit();
},
};
user.eat();
Answer
⬆ Back to Top
Answer
⬆ Back to Top
let user1 = {
name: "Jacob",
age: 28,
};
let user2 = {
name: "Jacob",
age: 28,
};
1: True
2: False
3: Compile time error
Answer
⬆ Back to Top
function greeting() {
setTimeout(function () {
console.log(message);
}, 5000);
const message = "Hello, Good morning";
}
greeting();
1: Undefined
2: Reference error:
3: Hello, Good morning
4: null
Answer
⬆ Back to Top
1: False
2: True
Answer
⬆ Back to Top
function add(a, b) {
console.log("The input arguments are: ", a, b);
return a + b;
}
1: Pure function
2: Impure function
Answer
⬆ Back to Top
Answer
⬆ Back to Top
try {
setTimeout(() => {
console.log("try block");
throw new Error(`An exception is thrown`);
}, 1000);
} catch (err) {
console.log("Error: ", err);
}
Answer
⬆ Back to Top
Answer
⬆ Back to Top
1: 0
2: Undefined
3: null
4:
Answer
---
⬆ Back to Top
An anagram is a word or phrase formed by rearranging all the letters of a different word or phrase exactly once. For example, the anagrams of "eat" word are "tea" and "ate".
You can split each word into characters, followed by sort action and later join them back. After that you can compare those two words to verify whether those two words are anagrams
or not.
⬆ Back to Top
printHello();
printMessage();
function printHello() {
console.log('Hello')
function printMessage() {
console.log("Good day")
}
}
Answer
---
⬆ Back to Top
console.log("Start code");
setTimeout(function() {
console.log("Callback code");
}, 5000);
console.log("After callback");
console.log("End code");
1: > 10 sec
2: Immediately
3: < 10 sec
4: <= 5sec
Answer
⬆ Back to Top
Answer
⬆ Back to Top
func(undefined);
func();
1: 1, 0
2: 0, 0
3: 0, 1
4: 1, 1
Answer
⬆ Back to Top
func(undefined);
func();
1: 1, 0
2: 0, 0
3: 0, 1
4: 1, 1
Answer
⬆ 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 questions 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!