Beginner Interview CheatSheet - 300+ Javascript Interview Q&A
Beginner Interview CheatSheet - 300+ Javascript Interview Q&A
www.amodshinde.com
Table of Contents
1. JavaScript Basics
1.1. What are the different data types in JavaScript?
1.2. How can we check the data types of JavaScript variables?
1.3. What is the difference between ‘==’ and ‘===’ in
JavaScript?
1.4. What is the output of the following?
1.5. Explain implicit type coercion in JavaScript.
1.6. Explain NaN in JavaScript.
1.7. What is the data type of NaN?
1.8. What is JSON?
1.9. How do you convert JSON data to a string and vice versa?
1.10. Explain splice() and slice() methods in JavaScript and list
their differences.
1.11. Is JavaScript a statically typed language or a dynamically
typed language?
1.12. Explain Higher Order Functions in JavaScript.
1.13. What are immediately Invoked Functions in JavaScript?
1.14. What are the possible ways to create objects in JavaScript?
1.15. What is a prototype chain?
1.16. What is the difference between Call, Apply, and Bind?
1.17. What is the difference between slice and splice?
1.18. What is a first-order function?
1.19. What is a unary function?
1.20. What is the currying function?
1.21. What is the difference between let and var?
1.22. What is the Temporal Dead Zone?
1.23. What is the benefit of using modules?
1.24. What is memoization?
1.25. What is Hoisting?
1.26. What are classes in ES6?
1.27. What are closures?
1.28. What is scope in JavaScript?
1.29. What is a service worker?
1.30. How do you manipulate DOM using a service worker?
1.31. How do you reuse information across service worker
restarts?
1.32. What is IndexedDB?
1.33. What is web storage?
1.34. What is a Cookie?
1.35. Why do you need a Cookie?
1.36. What are the config options in a cookie?
1.37. How do you delete a cookie?
1.38. What are the differences between a cookie, local storage,
and session storage?
1.39. What is the main difference between localStorage and
sessionStorage?
1.40. What are the methods available on session storage?
1.41. What is a storage event and its event handler?
1.42. Why do you need web storage?
1.43. How do you check web storage browser support?
1.44. How do you check web workers browser support?
1.45. What are the restrictions of web workers on DOM?
1.46. What is a promise?
1.47. Why do you need a promise?
1.48. What are the three states of a promise?
1.49. What is a callback function?
1.50. Why do we need callbacks?
1.51. What is a callback hell?
1.52. What are server-sent events?
1.53. How do you receive server-sent event notifications?
1.54. How do you check browser support for server-sent events?
1.55. What are the events available for server-sent events?
1.56. What are the main rules of a promise?
1.57. What is a callback in a callback?
1.58. What is promise chaining?
1.59. What is promise.all?
1.60. What is the purpose of the race method in promise?
1.61. What is strict mode in JavaScript?
1.62. Why do you need strict mode?
1.63. How do you declare strict mode?
1.64. What is the purpose of double exclamation?
1.65. What is the purpose of the delete operator?
1.66. What is the typeof operator?
1.67. What is an undefined property?
1.68. What is a null value?
1.69. What is the difference between null and undefined?
1.70. What is eval?
1.71. What is the difference between window and document?
1.72. How do you access history in JavaScript?
1.73. How do you detect caps lock key turned on or not?
1.74. What are the differences between undeclared and
undefined variables?
1.75. What are the problems with global variables?
1.76. What is the purpose of the isFinite function?
1.77. What is an event flow?
1.78. What is event bubbling?
1.79. What is event capturing?
1.80. How do you submit a form using JavaScript?
1.81. How do you find operating system details?
1.82. What is the difference between document load and
DOMContentLoaded events?
1.83. What is the difference between native, host, and user
objects?
1.84. What are the tools or techniques used for debugging
JavaScript code?
1.85. What are the pros and cons of promises over callbacks?
1.86. What is the difference between an attribute and a property?
1.87. What is the same-origin policy?
1.88. What is the purpose of void 0?
1.89. Is JavaScript a compiled or interpreted language?
1.90. Is there any relation between Java and JavaScript?
1.91. What are events?
1.92. What is the use of preventDefault method?
1.93. What is the use of stopPropagation method?
1.94. What are the steps involved in return false usage?
1.95. What is BOM?
1.96. What is the use of setTimeout?
1.97. What is the use of setInterval?
1.98. Why is JavaScript treated as Single-threaded?
1.99. What are the syntax rules of JSON?
1.100. What are PWAs (Progressive Web Apps)?
1.101. What is the purpose of clearTimeout method?
1.102. What is the purpose of clearInterval method?
1.103. How do you redirect a new page in JavaScript?
1.104. How do you check whether a string contains a substring?
1.105. How do you get the current URL with JavaScript?
1.106. What are the various URL properties of the location object?
1.107. How do you get query string values in JavaScript?
1.108. How do you check if a key exists in an object?
1.109. How do you loop through or enumerate a JavaScript
object?
1.110. How do you test for an empty object?
1.111. What is an arguments object?
1.112. What are the pros and cons of the for loop?
1.113. How do you display the current date in JavaScript?
1.114. How do you compare two date objects?
1.115. How do you check if a string starts with another string?
1.116. How do you trim a string in JavaScript?
1.117. How do you add a key-value pair in JavaScript?
1.118. Explain arrays in JavaScript?
1.119. Is there any way to force using strict mode in Node.js?
1.120. Why would you use something like the load event?
1.121. Does this event have disadvantages?
1.122. Do you know any alternatives, and why would you use
those?
1.123. What's the difference between Host objects and Native
objects?
1.124. What does "use strict" do?
1.125. What is a Polyfill?
1.126. What are escape characters in JavaScript?
1.127. What are some advantages of using JavaScript?
1.128. Explain ceil() method in JavaScript.
1.129. Explain concat() method in JavaScript.
1.130. Explain constructor() method in JavaScript.
1.131. Explain Date() method in JavaScript.
1.132. Explain Date.parse() method in JavaScript.
1.133. Explain exec() method in JavaScript.
1.134. Explain filter() method in JavaScript.
1.135. Explain localeCompare() method in JavaScript.
1.136. Explain match() method in JavaScript.
1.137. Explain pop() method in JavaScript.
1.138. Explain reduce() method in JavaScript.
1.139. Explain some() method in JavaScript.
1.140. Explain toLocaleString() method in JavaScript.
1.141. Explain toUpperCase() method in JavaScript.
1.142. Explain valueOf() method in JavaScript.
1.143. How can you convert a string to Number using unary plus?
1.144. Explain various types of error constructors supported by
JavaScript.
1.145. Explain the difference between function declaration and
function expression.
1.146. What will be the output of the JS code below? Please
explain.
1.147. What do you understand by Closures in JavaScript?
1.148. What do you mean by Event Bubbling and Event
Capturing?
1.149. How can you iterate an object?
1.150. Could you explain escape() and unescape() functions?
1.151. What are Generator functions?
1.152. What is prototypal Inheritance?
1.153. Explain sort() method.
1.154. Explain reverse() method.
1.155. Answer if the following expressions result in true or false.
1.156. What is the syntax of ‘Self-Invoking Function’?
1.157. What is an Iterator?
1.158. How does synchronous iteration work?
1.159. What is an event loop?
1.160. What is the call stack?
1.161. What is a Unary operator?
1.162. What is a decorator?
1.163. What is the purpose of compareFunction while sorting?
1.164. How do you find the min and max value in an array?
1.165. What is an empty statement, and what is the purpose of it?
1.166. How do you get metadata of a module?
1.167. What is a comma operator?
1.168. What is the advantage of a comma operator?
1.169. What is TypeScript?
1.170. What are the differences between JavaScript and
TypeScript?
1.171. What are the advantages of TypeScript over JavaScript?
1.172. What is an object initializer?
1.173. What is a constructor method?
1.174. What happens if you write a constructor more than once in
a class?
1.175. How do you call the constructor of a parent class?
1.176. How do you get the prototype of an object?
1.177. What happens if I pass a string type for getPrototype
method?
1.178. How do you set the prototype of one object to another?
1.179. How do you check whether an object can be extendable or
not?
1.180. How do you prevent an object from extending?
1.181. What are the different ways to make an object
non-extensible?
1.182. How do you define multiple properties on an object?
1.183. What is MEAN in JavaScript?
1.184. What Is Obfuscation in JavaScript?
1.185. Why do you need Obfuscation?
1.186. What is Minification?
1.187. What are the advantages of minification?
1.188. What are the differences between Obfuscation and
Encryption?
1.189. What are the common tools used for minification?
1.190. How do you perform form validation using JavaScript?
1.191. How do you perform form validation without JavaScript?
1.192. What are the DOM methods available for constraint
validation?
1.193. What are the available constraint validation DOM
properties?
1.194. What are the list of validity properties?
1.195. Give an example usage of rangeOverflow property.
1.196. Is enums feature available in JavaScript?
1.197. What is an enum?
1.198. How do you list all properties of an object?
1.199. How do you get property descriptors of an object?
1.200. What are the attributes provided by a property descriptor?
1.201. How do you extend classes?
1.202. How do I modify the URL without reloading the page?
1.203. How do you check whether an array includes a particular
value or not?
1.204. How do you compare scalar arrays?
1.205. How to get the value from get parameters?
1.206. How do you print numbers with commas as thousand
separators?
1.207. What is the difference between Java and JavaScript?
1.208. Does JavaScript support namespaces?
1.209. How do you declare namespaces?
1.210. How do you invoke JavaScript code in an iframe from the
parent page?
1.211. How do you get the timezone offset from a date?
1.212. How do you load CSS and JS files dynamically?
1.213. What are the different methods to find HTML elements in
DOM?
1.214. What is jQuery?
1.215. What is the V8 JavaScript engine?
1.216. Why do we call JavaScript a dynamic language?
1.217. What is a void operator?
1.218. How to set the cursor to wait?
1.219. How do you create an infinite loop?
1.220. What is the output of the below for loops?
1.221. List down some of the features of ES6.
1.222. What is ES6?
1.223. Can I redeclare let and const variables?
1.224. Does a const variable make the value immutable?
1.225. What are default parameters?
1.226. What are template literals?
1.227. How do you write multi-line strings in template literals?
1.228. What are nesting templates?
1.229. What are tagged templates?
1.230. What are raw strings?
1.231. What is destructuring assignment?
1.232. What are default values in destructuring assignment?
1.233. How do you swap variables in destructuring assignment?
1.234. What are enhanced object literals?
1.235. What are dynamic imports?
1.236. What are the use cases for dynamic imports?
1.237. What are typed arrays?
1.238. What is a freeze method?
1.239. What is the purpose of the freeze method?
1.240. Why do I need to use the freeze method?
1.241. How do you detect a browser language preference?
1.242. How to convert a string to title case with JavaScript?
1.243. How do you detect JavaScript disabled in the page?
1.244. What are various operators supported by JavaScript?
1.245. What is a rest parameter?
1.246. What happens if you do not use the rest parameter as the
last argument?
1.247. What are the bitwise operators available in JavaScript?
1.248. What is a spread operator?
1.249. How do you determine whether an object is frozen or not?
1.250. How do you determine two values are the same or not
using an object?
1.251. What is the purpose of using the object.is method?
1.252. How do you copy properties from one object to another?
1.253. What are the applications of the assign method?
1.254. What is a proxy object?
1.255. What is the purpose of the seal method?
1.256. What are the applications of the seal method?
1.257. What are the differences between freeze and seal
methods?
1.258. How do you determine if an object is sealed or not?
1.259. How do you get enumerable key and value pairs?
1.260. What is the main difference between Object.values and
Object.entries method?
1.261. How can you get the list of keys of any object?
1.262. What is a WeakSet?
1.263. What are the differences between WeakSet and Set?
1.264. List down the collection of methods available on WeakSet.
1.265. What is a WeakMap?
1.266. What are the differences between WeakMap and Map?
1.267. List down the collection of methods available on WeakMap.
1.268. What is the purpose of uneval?
1.269. How do you encode a URL?
1.270. How do you decode a URL?
1.271. How do you print the contents of a web page?
1.272. What is the difference between uneval and eval?
1.273. What is an anonymous function?
1.274. What is the precedence order between local and global
variables?
1.275. What are JavaScript accessors?
1.276. How do you define a property on the Object constructor?
1.277. What is the difference between get and defineProperty?
1.278. What are the advantages of Getters and Setters?
1.279. Can I add getters and setters using defineProperty
method?
1.280. What is the purpose of the switch-case?
1.281. What are the conventions to be followed for the usage of
switch case?
1.282. What are all the types of Pop up boxes available in
JavaScript?
1.283. What is the difference between an alert box and a
confirmation box?
1.284. What are escape characters?
1.285. What are the disadvantages of using innerHTML in
JavaScript?
1.286. What is break and continue statements?
1.287. Which keywords are used to handle exceptions?
1.288. What is the use of the blur function?
1.289. What is the unshift method in JavaScript?
1.290. What is the way to get the status of a CheckBox?
1.291. What is a window.onload and onDocumentReady?
1.292. How can a particular frame be targeted from a hyperlink in
JavaScript?
1.293. How are DOM utilized in JavaScript?
1.294. What is the role of deferred scripts in JavaScript?
1.295. What are Screen objects?
1.296. How to use
1.297.
1.298. Loops in JavaScript?
1.299. What are the important JavaScript Array Methods explained
with examples?
1.300. What is JavaScript Unit Testing, and what are the
challenges in JavaScript Unit Testing?
1.301. What are some important JavaScript Unit Testing
Frameworks?
1.302. What is a potential pitfall with using typeof bar === "object"
to determine if bar is an object? How can this pitfall be
avoided?
1.303. What will the code below output to the console and why?
1.304. What is the significance of, and reason for, wrapping the
entire content of a JavaScript source file in a function
block?
1.305. What is the significance, and what are the benefits, of
including 'use strict' at the beginning of a JavaScript source
file?
1.306. Consider the two functions below. Will they both return the
same thing? Why or why not?
1.307. What will the code below output? Explain your answer.
1.308. In what order will the numbers 1-4 be logged to the console
when the code below is executed? Why?
1.309. Write a sum method that will work properly when invoked
using either syntax below.
1.310. Discuss possible ways to write a function isInteger(x) that
determines if x is an integer.
1.311. What will the following code output and why?
1.312. What would the following code return?
1.313. Imagine you have this code:
1.314. How do you add an element at the beginning of an array?
How do you add one at the end?
1.315. What are the various statements in error handling?
1.316. What are the two types of loops in JavaScript?
1.317. What is Node.js?
1.318. What is an Intl object?
1.319. How do you perform language-specific date and time
formatting?
1.320. Is it possible to add CSS to console messages?
1.321. What is the purpose of the dir method of the console
object?
1.322. Is it possible to debug HTML elements in the console?
1.323. How do you display data in a tabular format using the
console object?
1.324. What is the shortcut to get a timestamp?
1.325. How do you flatten multi-dimensional arrays?
1.326. What is the easiest multi-condition checking?
1.327. How do you capture the browser back button?
1.328. How do you disable right-click in the web page?
1.329. What are wrapper objects?
1.330. What are the different ways to deal with Asynchronous
Code?
1.331. How to cancel a fetch request?
1.332. What is web speech API?
1.333. What is minimum timeout throttling?
1.334. How do you implement zero timeout in modern browsers?
1.335. What are tasks in the event loop?
1.336. What is a microtask?
1.337. What are the differences between promises and
observables?
1.338. What is heap?
1.339. What is an event table?
1.340. What is a microTask queue?
1.341. What is the difference between shim and polyfill?
1.342. How do you detect primitive or non-primitive value types?
1.343. What is Babel?
1.344. Is Node.js completely single-threaded?
1.345. What are the common use cases of observables?
1.346. What is RxJS?
1.347. What is the difference between Function constructor and
function declaration?
1.348. What is a Short circuit condition?
1.349. What is the easiest way to resize an array?
1.350. What is an observable?
1.351. What is the difference between function and class
declarations?
1.352. What is an async function?
1.353. How do you prevent promises from swallowing errors?
1.354. What are the differences between the spread operator and
rest parameter?
1.355. What are the different kinds of generators?
1.356. What are the built-in iterables?
1.357. What are the differences between for...of and for...in
statements?
1.358. How do you define instance and non-instance properties?
1.359. What is the difference between isNaN and Number.isNaN?
1.360. What is the easiest way to ignore promise errors?
What are the different data types in
javascript?
Example:
Example:
var a = 10;
var b = '10';
(a == b); //true
(a === b); //false
What is the output of the following?
A. 12<13<19
B. 19>12>2
C. 19>12>0
A => true
B=> false
C => true.
Example:
let a = 1;
let b = '1';
b + a; //returns “11”
a - b; //returns 0
What is JSON ?
JSON is a text-based data format that follows
Javascript’s object syntax. JSON is an abbreviation of
Javascript Object Notation. It is usually used when you
want to transmit data across a network.
JSON.parse(text);
Stringification:
JSON.stringify(object);
Syntax:
array.slice(start, end)
Example:
const arr = ['Apple', 'Bat' , 'Cat', 'Dog',
'Elephant'];
splice( )
Syntax:
Example:
let k = 12;
k = 'This is a string';
Example:
function HOF(fn) {
fn();
}
HOF(function () {
console.log("In Higher order Fn");
});
Syntax:
(function(){
//Do something
})();
//function declaration
function() {
//Do something
}// throws error because function
declaration should always have name
-----
//wrapping it in () to tell the compiler
that it is a function expression and not
function declaration
(function() {
});
------
//invoking the expression
(function() {
})();
What are the possible ways to create
objects in JavaScript?
There are many ways to create objects in javascript as
below
i. Object constructor:
The simplest way to create an empty object
is using the Object constructor. Currently this
approach is not recommended.
function Person(name){
this.name=name;
this.age=21;
}
var object = new Person("IronMan");
function Person(){}
Person.prototype.name = "IronMan";
var object = new Person();
var inviteEmployee1 =
invite.bind(employee1);
var inviteEmployee2 =
invite.bind(employee2);
inviteEmployee1('Hello', 'How are you?');
// Hello John Rodson, How are you?
inviteEmployee2('Hello', 'How are you?');
// Hello Jimmy Baily, How are you?
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
to due function scope)
console.log(age); //error: age is not
defined(due to block scope)
}
userDetails('John');
i. Maintainability
ii. Reusability
iii. Namespacing
What is memoization?
Memoization is a programming technique which
attempts to increase a function’s performance by
caching its previously computed results. Each time
a memoized function is called, its parameters are
used to index the cache. If the data is present, then
it can be returned, without executing the entire
function. Otherwise the function is executed and
then the result is added to the cache. Let's take an
example of adding function with memoization
What is Hoisting?
Hoisting is a JavaScript mechanism where
variables and function declarations are moved to
the top of their scope before code execution.
Remember that JavaScript only hoists declarations,
not initialisation. Let's take a simple example of
variable hoisting,
function Bike(model,color) {
this.model = model;
this.color = color;
}
Bike.prototype.getDetails = function() {
return this.model + ' bike has' +
this.color + ' color';
};
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
What is IndexedDB?
IndexedDB is a low-level API for client-side storage
of larger amounts of structured data, including
files/blobs. This API uses indexes to enable
high-performance searches of this data.
What is a Cookie?
A cookie is a piece of data that is stored on your
computer to be accessed by your browser. Cookies
are saved as key/value pairs.
window.onstorage = functionRef;
i. Window object
ii. Document object
iii. Parent object
What is a promise
A promise is an object that may produce a single
value some time in the future with either a resolved
value or a reason that it’s not resolved(for example,
network error). It will be in one of the 3 possible
states: fulfilled, rejected, or pending.
function callbackFunction(name) {
console.log('Hello ' + name);
}
function outerFunction(callback) {
let name = prompt('Please enter your
name.');
callback(name);
}
outerFunction(callbackFunction);
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
async1(function(){
async2(function(){
async3(function(){
async4(function(){
....
});
});
});
document.getElementById("output").innerHTML
+= event.data + "<br>";
};
}
How do you check browser
support for server-sent events
You can perform browser support for server-sent
events before using it as below,
Event Description
loadScript('/script1.js', function(script)
{
console.log('first script is loaded');
loadScript('/script2.js',
function(script) {
console.log('second script is
loaded');
loadScript('/script3.js',
function(script) {
console.log('third script is
loaded');
// after all scripts are loaded
});
})
});
What is promise.all
Promise.all is a promise that takes an array of
promises as an input (an iterable), and it gets
resolved when all the promises get resolved or any
one of them gets rejected. For example, the syntax
of promise.all method is below,
Promise.race([promise1,
promise2]).then(function(value) {
console.log(value); // "two" // Both
promises will resolve, but promise2 is
faster
});
"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
}
console.log(navigator.userAgent.match(/MSIE
8.0/)); // returns either an Array or null
user = undefined
null Undefined
What is eval
The eval() function evaluates JavaScript code
represented as a string. The string can be a
JavaScript expression, variable, statement, or
sequence of statements.
console.log(eval('1 + 2')); // 3
Window Document
function goBack() {
window.history.back();
}
function goForward() {
window.history.forward();
}
<input type="password"
onmousedown="enterInput(event)">
<p id="feedback"></p>
<script>
function enterInput(e) {
var flag = e.getModifierState("CapsLock");
if(flag) {
document.getElementById("feedback").innerHT
ML = "CapsLock activated";
} else {
document.getElementById("feedback").innerHT
ML = "CapsLock not activated";
}
}
</script>
Undeclared Undefined
function submit() {
document.forms[0].submit();
}
console.log(navigator.platform);
1. Chrome Devtools
2. debugger statement
3. Good old console.log statement
Cons:
const input =
document.querySelector('input');
console.log(input.getAttribute('value'));
// Good morning
console.log(input.value); // Good morning
console.log(input.getAttribute('value'));
// Good morning
console.log(input.value); // Good evening
<a href="JavaScript:void(0);"
onclick="alert('Well done!')">Click Me!</a>
Is JavaScript a compiled or
interpreted language
JavaScript is an interpreted language, not a
compiled language. An interpreter in the browser
reads over the JavaScript code, interprets each
line, and runs it. Nowadays modern browsers use a
technology known as Just-In-Time (JIT)
compilation, which compiles JavaScript to
executable bytecode just as it is about to run.
Is JavaScript a case-sensitive
language
Yes, JavaScript is a case sensitive language. The
language keywords, variables, function & object
names, and any other identifiers must always be
typed with a consistent capitalization of letters.
document.getElementById("link").addEventListener("c
lick", function(event){
event.preventDefault();
});
<div onclick="secondFunc()">DIV 2
</div>
<script>
function firstFunc(event) {
alert("DIV 1");
event.stopPropagation();
function secondFunc() {
alert("DIV 2");
</script>
What is BOM
The Browser Object Model (BOM) allows
JavaScript to "talk to" the browser. It consists of the
objects navigator, history, screen, location and
document which are children of the window. The
Browser Object Model is not standardized and can
change based on different browsers.
setInterval(function(){ console.log(
var form =
document.querySelector('#registration-form');
console.log(event.target);
}, false);
What are the syntax rules of JSON
Below are the list of syntax rules of JSON
<script>
var msg;
function greeting() {
alert('Good morning');
function start() {
function stop() {
clearTimeout(msg);
}
</script>
<script>
var msg;
function greeting() {
alert('Good morning');
function start() {
msg = setInterval(greeting, 3000);
function stop() {
clearInterval(msg);
</script>
function redirect() {
window.location.href = 'newPage.html';
}
How do you check whether a string
contains a substring
There are 3 possible ways to check whether a
string contains a substring or not,
mainString.includes(subString)
mainString.indexOf(subString) !== -1
console.log('location.href', window.location.href);
// Returns full URL
!("key" in obj)
name: 'John'
};
var object = {
"k1": "value1",
"k2": "value2",
"k3": "value3"
};
if (object.hasOwnProperty(key)) {
}
How do you test for an empty
object
There are different solutions based on ECMAScript
versions
if(obj.hasOwnProperty(prop)) {
return false;
function sum() {
var total = 0;
total += arguments[i];
}
return total;
sum(1, 2, 3) // returns 6
var argsArray =
Array.prototype.slice.call(arguments);
Pros
i. Too verbose
ii. Imperative
iii. You might face one-by-off errors
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, '');
};
})();
}
var object = {
key1: value1,
key2: value2
};
var arr = [
"hello world",
42,
true
];
"use strict";
at the top of your file in node >= 0.10.7, but if you
want your whole app to run in strict (including
external modules) you can do this
node --use_strict
function doSomething(val) {
"use strict";
x = val + 10;
}`
function doSomething(val) {
"use strict";
var x = val + 10;
What is a Polyfill?
● \b – Backspace
● \f – Form feed
● \n – Newline
● \r – Carriage return
● \t – Horizontal tabulator
● \v – Vertical tabulator
Date.now()
Returns the numeric value corresponding
to the current time
Explain Date.parse() method in
JavaScript
Parses a string representation of a date and
returns the number of milliseconds since 1
January, 1970, 00:00:00 UTC, with leap seconds
ignored.
console.log(result);
// expected output: Array ["exuberant",
"destruction", "present"]
Explain localeCompare() method
in JavaScript
The localeCompare() method returns a number
indicating whether a reference string comes
before, or after, or is the same as the given string
in sort order
EXAMPLE 1
console.log(a.localeCompare(b));
// expected output: 1
console.log(a.localeCompare(b, 'en', {
sensitivity: 'base' }));
// expected output: 0
EXAMPLE 2
Syntax: localeCompare(compareString,
locales, options)
array.reduce(function(total, currentValue,
currentIndex, arr), initialValue)
console.log(array.some(even));
// expected output: true
console.log(y);
outermost element.
This%3F%20string%20is%20encoded%21
let iterationCount = 0;
iterationCount++;
yield i;
return iterationCount;
}
What is prototypal Inheritance?
Every object has a property called a prototype,
where we can add methods to it and when you
create another object from these the newly
created object will automatically inherit its
parent’s property
(function () {
return ();
}();
What is an Iterator
An iterator is an object which defines a sequence
and a return value upon its termination. It
implements the Iterator protocol with a next()
method which returns an object with two properties:
value (the next value in the sequence) and done
(which is true if the last value in the sequence has
been consumed).
How does synchronous iteration
works
Synchronous iteration was introduced in ES6 and it
works with below set of components,
const iterator =
iterable[Symbol.iterator]();
console.log(iterator.next()); // { value:
'one', done: false }
console.log(iterator.next()); // { value:
'two', done: false }
console.log(iterator.next()); // { value:
'three', done: false }
console.log(iterator.next()); // { value:
'undefined, done: true }
function hungry() {
eatFruits(); }
function eatFruits() {
hungry();
The above code processed in a call stack as below,
var y = + x;
var a = "Hello";
var b = + a;
What is a decorator
A decorator is an expression that evaluates to a
function and that takes the target, name, and
decorator descriptor as arguments. Also, it
optionally returns a decorator descriptor to install on
the target object. Let's define admin decorator for
user class at design time,
function admin(isAdmin) {
return function(target) {
target.isAdmin = isAdmin;
@admin(true)
class User() {
console.log(User.isAdmin); //true
@admin(false)
class User() {
console.log(User.isAdmin); //false
What is the purpose of
compareFunction while sorting
arrays
The compareFunction is used to define the sort
order. If omitted, the array elements are converted
to strings, then sorted according to each character's
Unicode code point value. Let's take an example to
see the usage of compareFunction,
console.log(numbers); // [5, 4, 3, 2, 1]
function findMin(arr) {
function findMax(arr) {
console.log(findMin(marks));
console.log(findMax(marks));
What is an empty statement and
purpose of it
The empty statement is a semicolon (;) indicating
that no statement will be executed, even if
JavaScript syntax requires one. Since there is no
action with an empty statement you might think that
it's usage is quite less, but the empty statement is
occasionally useful when you want to create a loop
that has an empty body. For example, you can
initialize an array with zero values as below,
// Initialize an array a
x = (x++, x);
console.log(x); // 2
var a = 1;
What is typescript
TypeScript is a typed superset of JavaScript
created by Microsoft that adds optional types,
classes, async/await, and many other features, and
compiles to plain JavaScript. Angular built entirely
in TypeScript and used as a primary language. You
can install it globally as
npm install -g typescript
Let's see a simple example of TypeScript usage,
function greeting(name: string): string {
console.log(initObject.a); // John
constructor() {
this.name = "John";
console.log(employeeObject.name); // John
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";
this.age = 30;
}
var employeeObject = new Employee();
console.log(employeeObject.name);
constructor(length) {
super(length, length);
this.name = 'Square';
get area() {
}
set area(value) {
this.area = value;
console.log(Object.getPrototypeOf(newObject) ===
newPrototype); // true
Object.getPrototypeOf('James'); // TypeError:
"James" is not an object
// ES2015
Object.getPrototypeOf('James'); //
String.prototype
Object.setPrototypeOf({}, null)
How do you check whether an
object can be extendable or not
The Object.isExtensible() method is used to
determine if an object is extendable or not. i.e,
Whether it can have new properties added to it or
not.
const newObject = {};
console.log(Object.isExtensible(newObject));
//true
Note: By default, all the objects are extendable. i.e,
The new properties can be added or modified.
Object.preventExtensions(newObject); // NOT
extendable
try {
Object.defineProperty(newObject, 'newProperty',
{ // Adding new property
value: 100
});
} catch (e) {
iv. Object.preventExtensions
v. Object.seal
vi. Object.freeze
Object.isExtensible(newObject); // false
Object.isExtensible(sealedObject); // false
Object.isExtensible(frozenObject); // false
newProperty1: {
value: 'John',
writable: true
},
newProperty2: {}
})
What Is Obfuscation in
javascript
Obfuscation is the deliberate act of creating
obfuscated javascript code(i.e, source or machine
code) that is difficult for humans to understand. It is
something similar to encryption, but a machine can
understand the code and execute it. Let's see the
below function before Obfuscation,
function greeting() {
eval(function(p,a,c,k,e,d){e=function(c){re
turn
c};if(!''.replace(/^/,String)){while(c--){d
[c]=k[c]||c}k=[function(e){return
d[e]}];e=function(){return'\\w+'};c=1};whil
e(c--){if(k[c]){p=p.replace(new
RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return
p}('2 1(){0.3(\'4, 7 6 5
8\')}',9,9,'console|greeting|function|log|H
ello|JS|to|welcome|world'.split('|'),0,{}))
Why do you need Obfuscation
Below are the few reasons for Obfuscation,
What is Minification
Minification is the process of removing all
unnecessary characters(empty spaces are
removed) and variables will be renamed without
changing it's functionality. It is also a type of
obfuscation .
</form>
And the validation on user login is below,
function validateForm() {
var x = document.forms["myForm"]["uname"].value;
if (x == "") {
return false;
</form>
Note: Automatic form validation does not work in
Internet Explorer 9 or earlier.
function myFunction() {
if (!userName.checkValidity()) {
document.getElementById("message").innerHTML =
userName.validationMessage;
} else {
document.getElementById("message").innerHTML =
"Entered a valid username";
<button
onclick="myOverflowFunction()">OK</button>
function myOverflowFunction() {
if
(document.getElementById("age").validity.ra
ngeOverflow) {
What is an enum
An enum is a type restricting variables to one value
from a predefined set of constants. JavaScript has
no enums but typescript provides built-in enum
support.
enum Color {
RED, GREEN, BLUE
}
How do you list all properties of
an object
You can use the Object.getOwnPropertyNames()
method which returns an array of all properties
found directly in a given object. Let's the usage of it
in an example,
const newObject = {
a: 1,
b: 2,
c: 3
};
console.log(Object.getOwnPropertyNames(newObject))
; ["a", "b", "c"]
get area() {
return this.width * this.height;
}
set area(value) {
this.area = value;
}
}
console.log(convertToThousandFormat(12345.6789));
}
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.
var namespaceOne = {
function func1() {
console.log("This is a first definition");
}
}
var namespaceTwo = {
function func1() {
console.log("This is a second
definition");
}
}
namespaceOne.func1(); // This is a first
definition
namespaceTwo.func1(); // This is a second
definition
(function() {
function fun1(){
console.log("This is a first definition");
} fun1();
}());
(function() {
function fun1(){
console.log("This is a second definition");
} fun1();
}());
{
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
document.getElementsByTagName("head")[0].appendChi
ld(fileReference)
}
x. document.getElementById(id): It finds
an element by Id
xi. document.getElementsByTagName(n
ame): It finds an element by tag name
xii. document.getElementsByClassName(
name): It finds an element by class
name
What is jQuery
jQuery is a popular cross-browser JavaScript library
that provides Document Object Model (DOM)
traversal, event handling, animations and AJAX
interactions by minimizing the discrepancies across
browsers. It is widely famous with its philosophy of
“Write less, do more”. For example, you can display
welcome message on the page load using jQuery
as below,
$(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.
while(true) {
}
What is ES6
ES6 is the sixth edition of the javascript language
and it was released in June 2015. It was initially
known as ECMAScript 6 (ES6) and later renamed
to ECMAScript 2015. Almost all the modern
browsers support ES6 but for the old browsers
there are many transpilers, like Babel.js etc.
function myFunc() {
alert(name); // Abraham
myFunc();
alert(name); // John
The block-scoped multi-declaration throws syntax
error,
let name = 'John';
function myFunc() {
let name = 'Nick';
alert(name);
myFunc();
alert(name);
console.log(calculateArea()); //300
The default parameters makes the initialization
more simpler,
//ES6
console.log(calculateArea()); //300
`icon-${user.isAuthorized ? 'submit' :
'disabled'}` }`;
You can write the above use case without nesting
template features as well. However, the nesting
template feature is more compact and readable.
//Without nesting templates
var experience2 = 5;
var expertiseStr;
} else {
return
`${str0}${userExp}${str1}${expertiseStr}${str2}${s
killExp}`;
console.log(calculationString);
// The sum of numbers is
// 10
Also, the raw property is available on the first
argument to the tag function
function tag(strings) {
console.log(strings.raw[0]);
What is destructuring
assignment
The destructuring assignment is a JavaScript
expression that makes it possible to unpack values
from arrays or properties from objects into distinct
variables. Let's get the month values from an array
using destructuring assignment
var [one, two, three] = ['JAN', 'FEB', 'MARCH'];
console.log(one); // "JAN"
console.log(two); // "FEB"
console.log(three); // "MARCH"
and you can get user properties of an object using
destructuring assignment,
var {name, age} = {name: 'John', age: 32};
console.log(name); // John
console.log(age); // 3
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
console.log(x); // 20
console.log(y); // 10
var x = 10, y = 20
obj = { x, y }
//ES5
var x = 10, y = 20
obj = { x : x, y : y}
console.log(obj); // {x: 10, y:20}
if (isLegacyBrowser()) {
import(···)
.then(···);
import(`messages_${getLocale()}.js`).then(···);
prop: 100
};
Object.freeze(obj);
console.log(obj.prop); //100
Note: It causes a TypeError if the argument passed
is not an object.
navigator.userLanguage; // IE <= 10
console.log(language);
return str.replace(
/\w\S*/g,
function(txt) {
return txt.charAt(0).toUpperCase()
+ txt.substr(1).toLowerCase();
}
);
</script>
<noscript>
<a href="next_page.html?noJS=true">JavaScript
is disabled in the page. Please click Next
Page</a>
</noscript>
What are various operators
supported by javascript
An operator is capable of
manipulating(mathematical and logical
computations) a certain value or operand. There
are various operators supported by JavaScript as
below,
// ...
}
For example, let's take a sum example to calculate
on dynamic number of parameters,
function total(…args){
let sum = 0;
for(let i of args){
sum+=i;
return sum;
console.log(fun(1,2)); //3
console.log(fun(1,2,3)); //6
console.log(fun(1,2,3,4)); //13
console.log(fun(1,2,3,4,5)); //15
Note: Rest parameter is added in ES2015 or ES6
return;
return x + y + z;
console.log(calculateSum(...numbers)); // 6
1. If it is not extensible.
2. If all of its properties are
non-configurable.
3. If all its data properties are
non-writable. The usage is going to be
as follows,
const object = {
};
Object.freeze(object);
console.log(Object.isFrozen(object));
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.
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.
What are the applications of
assign method
Below are the some of main applications of
Object.assign() method,
obj[prop] :
100;
};
var p = new Proxy({}, handler);
p.a = 10;
p.b = null;
};
Object.seal(object);
object.property = 'Welcome to object world';
console.log(Object.isSealed(object)); // true
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 = {
};
console.log(Object.isSealed(object)); //
checking whether the object is sealed or not
How do you get enumerable key
and value pairs
The Object.entries() method is used to return an
array of a given object's own enumerable
string-keyed property [key, value] pairs, in the same
order as that provided by a for...in loop. Let's see
the functionality of object.entries() method in an
example,
const object = {
a: 'Good morning',
b: 100
};
// b: 100
}
Note: The order is not guaranteed as object
defined.
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
};
100}
name: 'John',
gender: 'male',
age: 40
};
console.log(Object.keys(user)); //['name',
'gender', 'age']
name: 'John',
printInfo: function () {
};
What is a WeakSet
WeakSet is used to store a collection of
weakly(weak references) held objects. The syntax
would be as follows,
new WeakSet([iterable]);
Let's see the below example to explain it's behavior,
var ws = new WeakSet();
ws.add(user);
ws.has(user); // true
// add(value)
weakSetObject.add(firstObject);
weakSetObject.add(secondObject);
console.log(weakSetObject.has(firstObject));
//true
weakSetObject.delete(secondObject);
What is a WeakMap
The WeakMap object is a collection of key/value
pairs in which the keys are weakly referenced. In
this case, keys must be objects and the values can
be arbitrary values. The syntax is looking like as
below,
new WeakMap([iterable])
Let's see the below example to explain it's behavior,
var ws = new WeakMap();
ws.set(user);
ws.has(user); // true
// set(key, value)
weakMapObject.set(firstObject, 'John');
weakMapObject.set(secondObject, 100);
console.log(weakMapObject.has(firstObject));
//true
console.log(weakMapObject.get(firstObject)); //
John
weakMapObject.delete(secondObject);
console.log(encoded); //
https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1
%8B
console.log(encoded); //
https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1
%8B
try {
console.log(decodeURI(encoded)); //
"https://mozilla.org/?x=шеллы"
console.error(e);
//do something
//do something
};
});
Let's see the above anonymous function in an
example,
var x = function (a, b) {return a * b};
console.log(z); // 50
function greeting() {
console.log(msg);
greeting();
What are javascript accessors
ECMAScript 5 introduced javascript object
accessors or computed properties through getters
and setters. Getters uses the get keyword whereas
Setters uses the set keyword.
var user = {
firstName: "John",
lastName : "Abraham",
language : "en",
get lang() {
return this.language;
set lang(lang) {
this.language = lang;
};
user.lang = 'fr';
console.log(user.lang); // setter used to set lang
as fr
Object.defineProperty(newObject, 'newProperty', {
value: 100,
writable: false
});
console.log(newObject.newProperty); // 100
// Define getters
Object.defineProperty(obj, "increment", {
});
Object.defineProperty(obj, "decrement", {
});
// Define setters
Object.defineProperty(obj, "add", {
Object.defineProperty(obj, "subtract", {
});
obj.add = 10;
obj.subtract = 5;
console.log(obj.increment); //6
console.log(obj.decrement); //5
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.
Catch(exp){
Finally{
for loop
Syntax:
for(statement1; statement2; statment3)
for/in a loop
The for/in a loop is usually used to loop
through the properties of an object. You can
give any name for the variable, but the
object’s name should be the same as an
already existing object you need to loop
through.
Syntax:
for (variablename in objectname)
{
while loop
Syntax:
while(condition)
do…while loop
Syntax:
<pre>
do
(function () {
var a = (b = 3);
})();
var b = 3;
var a = b;
b = 3;
var a = b;
b defined? true
2)
(myObject = {
foo: "bar",
func: function () {
(function () {
})();
},
};
myObject.func();
The above code will output the following to the
console:
function foo1() {
function foo2() {
return
{ bar: "hello" };
False
function areTheNumbersAlmostEqual(num1,
num2) {
return Math.abs( num1 - num2 ) <
Number.EPSILON;
}
console.log(areTheNumbersAlmostEqual(0.1 +
0.2, 0.3));
In what order will the numbers 1-4
be logged to the console when the
code below is executed? Why?
(function () {
console.log(1);
setTimeout(function () {
console.log(2);
}, 1000);
setTimeout(function () {
console.log(3);
}, 0);
console.log(4);
})();
The values will be printed in the order:
1
4
3
2
function sum(x) {
if (arguments.length == 2) {
return arguments[0] + arguments[1];
} else {
return function(y) { return x + y; };
}
}
In JavaScript, functions provide access to an
arguments object which provides access to the
actual arguments passed to a function. This
enables us to use the length property to
determine at runtime the number of arguments
passed to the function.
METHOD 2
function sum(x, y) {
if (y !== undefined) {
return x + y;
} else {
return function(y) { return x + y; };
}
}
When a function is invoked, JavaScript does not
require the number of arguments to match the
number of arguments in the function definition. If
the number of arguments passed exceeds the
number of arguments in the function definition,
the excess arguments will simply be ignored. On
the other hand, if the number of arguments
passed is less than the number of arguments in
the function definition, the missing arguments will
have a value of undefined when referenced within
the function. So, in the above example, by simply
checking if the 2nd argument is undefined, we
can determine which way the function was
invoked and proceed accordingly.
> String(1000000000000000000000)
'1e+21'
> parseInt(1000000000000000000000, 10)
1
> parseInt(1000000000000000000000, 10) ===
1000000000000000000000
false
What will the following code
output and why?
var b = 1;
function outer(){
var b = 2
function inner(){
b++;
var b = 3;
console.log(b)
inner();
outer();
Output to the console will be “3”.
There are three closures in the example, each
with it’s own var b declaration. When a variable is
invoked closures will be checked in order from
local to global until an instance is found. Since
the inner closure has a b variable of its own, that
is what will be output.
setTimeout(function () {
console.log(i);
}, i * 1000);}
4)
var x = 21;
var x = 20;
};
girl();
console.log(false == "0");
true
false
6)
var a = {},
b = { key: "b" },
c = { key: "c" };
a[b] = 123;
a[c] = 456;
console.log(a[b]);
7)
console.log(
(function f(n) {
})(10)
);
The code will output the value of 10 factorial (i.e.,
10!, or 3,628,800).
Here’s why:
8)
(function (x) {
console.log(x);
})(2);
})(1);
9)
var hero = {
getSecretIdentity: function () {
return this._name;
},
};
var stoleSecretIdentity =
hero.getSecretIdentity;
console.log(stoleSecretIdentity());
console.log(hero.getSecretIdentity());
undefined
John Doe
ES6 Way
myArray = ['start', ...myArray];
myArray = [...myArray, 'end'];
What is nodejs
Node.js is a server-side platform built on Chrome's
JavaScript runtime for easily building fast and
scalable network applications. It is an event-based,
non-blocking, asynchronous I/O runtime that uses
Google's V8 JavaScript engine and libuv library.
What is an Intl object
The Intl object is the namespace for the
ECMAScript Internationalization API, which
provides language sensitive string comparison,
number formatting, and date and time formatting. It
provides access to several constructors and
language sensitive functions.
i. Callbacks
ii. Promises
iii. Async/await
iv. Third-party libraries such as
async.js,bluebird etc
fetch("http://localhost:8000", { signal
}).then(response => {
console.log(`Request 1 is complete!`);
}).catch(e => {
if(e.name === "AbortError") {
// We know it's been canceled!
}
});
fetch("http://localhost:8000", { signal
}).then(response => {
console.log(`Request 2 is complete!`);
}).catch(e => {
if(e.name === "AbortError") {
// We know it's been canceled!
}
});
// Wait 2 seconds to abort both requests
setTimeout(() => controller.abort(), 2000);
window.SpeechRecognition =
window.webkitSpeechRecognition ||
window.SpeechRecognition; //
webkitSpeechRecognition for Chrome and
SpeechRecognition for FF
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
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)
What is minimum timeout
throttling
Both browser and NodeJS javascript environments
throttles with a minimum delay that is greater than
0ms. That means even though setting a delay of
0ms will not happen instantaneously. Browsers:
They have a minimum delay of 4ms. This throttle
occurs when successive calls are triggered due to
callback nesting(certain depth) or after a certain
number of successive intervals. Note: The older
browsers have a minimum delay of 10ms. Nodejs:
They have a minimum delay of 1ms. This throttle
happens when the delay is larger than 2147483647
or less than 1. The best example to explain this
timeout throttling behavior is the order of below
code snippet.
function runMeFirst() {
console.log('My script is initialized');
}
setTimeout(runMeFirst, 0);
console.log('Script loaded');
and the output would be in
Script loaded
My script is initialized
If you don't use setTimeout, the order of logs will be
sequential.
function runMeFirst() {
console.log('My script is initialized');
}
runMeFirst();
console.log('Script loaded');
and the output is,
My script is initialized
Script loaded
What is microtask
Microtask is the javascript code which needs to be
executed immediately after the currently executing
task/microtask is completed. They are kind of
blocking in nature. i.e, The main thread will be
blocked until the microtask queue is empty. The
main sources of microtasks are Promise.resolve,
Promise.reject, MutationObservers,
IntersectionObservers etc
Note: All of these microtasks are processed in the
same turn of the event loop.
What is heap
Heap(Or memory heap) is the memory location
where objects are stored when we define variables.
i.e, This is the place where all the memory
allocations and de-allocation take place. Both heap
and call-stack are two containers of JS runtime.
Whenever runtime comes across variables and
function declarations in the code it stores them in
the Heap.
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.
What is babel
Babel is a JavaScript transpiler to convert
ECMAScript 2015+ code into a backwards
compatible version of JavaScript in current and
older browsers or environments. Some of the main
features are listed below,
i. Transform syntax
ii. Polyfill features that are missing in
your target environment (using
@babel/polyfill)
iii. Source code transformations (or
codemods)
Is Node.js completely single
threaded
Node is a single thread, but some of the functions
included in the Node.js standard library(e.g, fs
module functions) are not single threaded. i.e, Their
logic runs outside of the Node.js single thread to
improve the speed and performance of a program.
What is RxJS
RxJS (Reactive Extensions for JavaScript) is a
library for implementing reactive programming
using observables that makes it easier to compose
asynchronous or callback-based code. It also
provides utility functions for creating and working
with observables.
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.
Let's see this difference with an example,
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
What is a Short circuit condition
Short circuit conditions are meant for condensed
way of writing simple if statements. Let's
demonstrate the scenario using an example. If you
would like to login to a portal with an authentication
condition, the expression would be as below,
if (authenticate) {
loginToPorta();
}
Since the javascript logical operators evaluated
from left to right, the above expression can be
simplified using && logical operator
authenticate && loginToPorta();
array.length = 2;
console.log(array.length); // 2
console.log(array); // [1,2]
and the array can be emptied too
var array = [1, 2, 3, 4, 5];
array.length = 0;
console.log(array.length); // 0
console.log(array); // []
What is an observable
An Observable is basically a function that can
return a stream of values either synchronously or
asynchronously to an observer over time. The
consumer can get the value by calling subscribe()
method. Let's look at a simple example of an
Observable
import { Observable } from 'rxjs';
class User {}
Constructor Function:
const user = new User(); // No error
function User() {
}
Promise.reject('error value').catch(function() {
throw new Error('error');
});
console.log(Array.from(SomeObj)); // [ 1, 2, 3 ]
arr.newProp = 'newVlue';
// key are the property keys
for (let key in arr) {
console.log(key);
}