Javascript Interview Questions & Answers: Sudheerj
Javascript Interview Questions & Answers: Sudheerj
up
sudheerj / javascript-interview-questions
Star Watch
Dismiss
Join GitHub today
GitHub is home to over 50 million
developers working together to host and
review code, manage projects, and build
software together.
Sign up
master Go to file
sudheerj Merge pull request #50 from sadanandpai… … 5 days ago 304
View code
README.md
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!
Table of Contents
No. Questions
24 What is memoization
25 What is Hoisting
34 What is IndexedDB
37 What is a cookie
51 What is a promise
64 What is promise.all
75 What is eval
79 What is isNaN
168 How do you get the image width and height using JS
175 What are the ways to execute javascript after page load
190 How do you determine two values same or not using object
197 What are the differences between freeze and seal methods
201 How can you get the list of keys of any object
228 What are the different error names from error object
246 How do you find min and max values without Math functions
274 What are the DOM methods available for constraint validation
What are the list of cases error thrown from non-strict mode to
340
strict mode
363 How do you map the array values without using map method
382 What are the different ways to deal with Asynchronous Code
i. Object constructor:
Create any function and apply the new operator to create object
instances,
function Person(name){
var object = {};
object.name=name;
object.age=21;
return object;
}
var object = new Person("Sudheer");
function Person(){}
Person.prototype.name = "Sudheer";
var object = new Person();
(OR)
class Person {
constructor(name) {
this.name = name;
}
}
Back to Top
2. What is a prototype chain
Prototype chaining is used to build new types of objects based on
existing ones. It is similar to inheritance in a class based language. The
prototype on object instance is available through
Object.getPrototypeOf(object) or proto property whereas prototype
on constructors function is available through object.prototype.
Back to Top
Call: The call() method invokes a function with a given this value
and arguments provided one by one
bind: returns a new function, allowing you to pass in an array and any
number of arguments
Call and apply are pretty 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. Whereas Bind creates a new function that will have this
set to the first parameter passed to bind().
Back to Top
JSON.stringify(object)
Back to Top
Note: Slice method won't mutate the original array but it returns the
subset as a new array.
Back to Top
Note: Splice method modifies the original array and returns the
deleted array.
Back to Top
Slice Splice
Back to Top
Back to Top
9. What
is the difference between == and ===
operators
JavaScript provides both strict(===, !==) and type-converting(==, !=)
equality comparison. The strict operators take type of variable in
consideration, while non-strict operators make type
correction/conversion based upon values of variables. The strict
operators follow the below conditions for different types,
i. Two strings are strictly equal when they have the same sequence
of characters, same length, and same characters in corresponding
positions.
ii. Two numbers are strictly equal when they are numerically equal.
i.e, Having the same number value. There are two special cases in
this,
a. NaN is not equal to anything, including NaN.
b. Positive and negative zeros are equal to one another.
iii. Two Boolean operands are strictly equal if both are true or both
are false.
iv. Two objects are strictly equal if they refer to the same Object.
v. 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
[]==[] or []===[] //false, refer different objects in memory
{}=={} or {}==={} //false, refer different objects in memory
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
var let
function userDetails(username) {
if(username) {
console.log(salary); // undefined(due to hoisting)
console.log(age); // error: age is not defined
let age = 30;
var salary = 10000;
}
console.log(salary); //10000 (accessible to due function scop
console.log(age); //error: age is not defined(due to block sc
}
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
function somemethod() {
console.log(counter1); // undefined
console.log(counter2); // ReferenceError
var counter1 = 1;
let counter2 = 2;
}
Back to Top
22. What
is IIFE(Immediately Invoked Function
Expression)
IIFE (Immediately Invoked Function Expression) is a JavaScript
function that runs as soon as it is defined. The signature of it would
be as below,
(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 with 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
i. Maintainability
ii. Reusability
iii. Namespacing
Back to Top
Back to Top
var message;
console.log(message);
message = 'The variable Has been hoisted';
Back to Top
26. What are classes in ES6
In ES6, Javascript classes are primarily syntactic sugar over JavaScript’s
existing prototype-based inheritance. For example, the prototype
based inheritance written in function expression as below,
function Bike(model,color) {
this.model = model;
this.color = color;
}
Bike.prototype.getDetails = function() {
return this.model + ' bike has' + this.color + ' color';
};
class Bike{
constructor(color, model) {
this.color= color;
this.model= model;
}
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
Back to Top
Back to Top
i. Maintainability
ii. Reusability
iii. Namespacing
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
34. What is IndexedDB
IndexedDB is a low-level API for client-side storage of larger amounts
of structured data, including files/blobs. This API uses indexes to
enable high-performance searches of this data.
Back to Top
Back to Top
Back to Top
Back to Top
i. When a user visits a web page, the user profile can be stored in a
cookie.
ii. Next time the user visits the page, the cookie remembers the
user profile.
Back to Top
i. 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
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
Local Session
Feature Cookie
storage storage
Accessed on
Both server-side client-side client-side
client or server
& client-side only only
side
As configured
until until tab
Lifetime using Expires
deleted is closed
option
Local Session
Feature Cookie
storage storage
Not Not
SSL support Supported
supported supported
Maximum data
4KB 5 MB 5MB
size
Back to Top
Back to Top
localStorage.setItem('logo', document.getElementById('logo').val
localStorage.getItem('logo');
Back to Top
44. What are the methods available on session storage
The session storage provided methods for reading, writing and
clearing the session data
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
window.onstorage = function(e) {
console.log('The ' + e.key +
' key has been changed from ' + e.oldValue +
' to ' + e.newValue + '.');
};
Back to Top
46. Why do you need web storage
Web storage is more secure, and large amounts of data can be stored
locally, without affecting website performance. Also, the information
is never transferred to the server. Hence this is a more recommended
approach than Cookies.
Back to Top
Back to Top
Back to Top
let i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
i. 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");
}
w.onmessage = function(event){
document.getElementById("message").innerHTML = event.data;
};
w.terminate();
i. Reuse the Web Worker: If you set the worker variable to
undefined you can reuse the code
w = undefined;
Back to Top
i. Window object
ii. Document object
iii. Parent object
Back to Top
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
Back to Top
Back to Top
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) {
})
});
Back to Top
}).then(function(result) {
console.log(result); // 1
return result * 2;
}).then(function(result) {
console.log(result); // 2
return result * 3;
}).then(function(result) {
console.log(result); // 6
return result * 4;
});
In the above handlers, the result is passed to the chain of .then()
handlers with the below work flow,
Back to Top
Back to Top
Promise.race([promise1, promise2]).then(function(value) {
console.log(value); // "two" // Both promises will resolve, bu
});
Back to Top
Back to Top
Back to Top
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
70. What is the purpose of the delete operator
The delete keyword is used to delete the property as well as its value.
Back to Top
Back to Top
user = undefined
Back to Top
73. What is null value
The value null represents the intentional absence of any object value.
It is one of JavaScript's primitive values. The type of null value is
object. You can empty the variable by setting the value to null.
Back to Top
Null Undefined
Back to Top
75. What is eval
The eval() function evaluates JavaScript code represented as a string.
The string can be a JavaScript expression, variable, statement, or
sequence of statements.
console.log(eval('1 + 2')); // 3
Back to Top
76. What
is the difference between window and
document
Below are the main differences between window and document,
Window Document
Back to Top
Back to Top
i. Number
ii. String
iii. Boolean
iv. Object
v. Undefined
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 and undefined
variables,
undeclared undefined
If you try to read the value of If you try to read the value of
an undeclared variable, then a 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
Back to Top
Back to Top
function submit() {
document.form[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
Back to Top
i. Chrome Devtools
ii. debugger statement
iii. 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
94. What
is the difference between an attribute and a
property
Attributes are defined on the HTML markup whereas properties are
defined on the DOM. For example, the below HTML element has 2
attributes type and value,
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
Back to Top
Back to Top
document.getElementById("link").addEventListener("click", functi
event.preventDefault();
});
Note: Remember that not all events are cancelable.
Back to Top
<script>
function firstFunc(event) {
alert("DIV 1");
event.stopPropagation();
}
function secondFunc() {
alert("DIV 2");
}
</script>
Back to Top
Back to Top
105. 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.
Back to Top
Back to Top
Back to Top
}, false);
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
function stop() {
clearTimeout(msg);
}
</script>
Back to Top
<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
Back to Top
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+
return re.test(String(email).toLowerCase());
}
Back to Top
Back to Top
Back to Top
Back to Top
"key" in obj
!("key" in obj)
obj.hasOwnProperty("key") // true
const user = {
name: 'John'
};
Back to Top
var object = {
"k1": "value1",
"k2": "value2",
"k3": "value3"
};
for (var key in object) {
if (object.hasOwnProperty(key)) {
console.log(key + " -> " + object[key]); // k1 -> value1
}
}
Back to Top
i. Using Object keys(ECMA 5+): You can use object keys length
along with constructor type.
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop)) {
return false;
}
}
Back to Top
128. What is an arguments object
The arguments object is an Array-like object accessible inside
functions that contains the values of the arguments passed to that
function. For example, let's see how to use arguments object inside
sum function,
function sum() {
var total = 0;
for (var i = 0, len = arguments.length; i < len; ++i) {
total += arguments[i];
}
return total;
}
sum(1, 2, 3) // returns 6
Note: You can't apply array methods on arguments object. But you
can convert into a regular array as below.
Back to Top
129. How
do you make first letter of the string in an
uppercase
You can create a function which uses a chain of string methods such
as charAt, toUpperCase and slice methods to generate a string with
the first letter in uppercase.
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
Back to Top
130. What are the pros and cons of for loop
The for-loop is a commonly used iteration syntax in javascript. It has
both pros and cons ####Pros
####Cons
i. Too verbose
ii. Imperative
iii. You might face one-by-off 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
var object = {
key1: value1,
key2: value2
};
i. Using dot notation: This solution is useful when you know the
name of the property
object.key3 = "value3";
obj["key3"] = "value3";
Back to Top
Back to Top
137. How do you assign default values to variables
You can use the logical or operator || in an assignment expression
to provide a default value. The syntax looks like as below,
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
But if you have a space after the '' character, the code will look exactly
the same, but it will raise a SyntaxError.
Back to Top
Back to Top
fn = function(x) {
//Function code goes here
}
fn.name = "John";
fn.profile = function(y) {
//Profile code goes here
}
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
143. What are break and continue statements
The break statement is used to "jump out" of a loop. i.e, It breaks the
loop and continues executing the code after the loop.
Back to Top
var i, j;
loop1:
for (i = 0; i < 3; i++) {
loop2:
for (j = 0; j < 3; j++) {
if (i === j) {
continue loop1;
}
console.log('i = ' + i + ', j = ' + j);
}
}
// Output 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
"users":[
{"firstName":"John", "lastName":"Abrahm"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Shane", "lastName":"Warn"}
]
Back to Top
Back to Top
150. Can
you write a random integers function to print
integers with in 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
152. What is the need of tree shaking
Tree Shaking can significantly reduce the code size in any application.
i.e, The less code we send over the wire the more performant the
application will be. For example, if we just want to create a “Hello
World” Application using SPA frameworks then it will take around a
few MBs, but by tree shaking it can bring down the size to just a few
hundred KBs. Tree shaking is implemented in Rollup and Webpack
bundlers.
Back to Top
Back to Top
/pattern/modifiers;
/John/i
Back to Top
155. What
are the string methods available in Regular
expression
Regular Expressions has two string methods: search() and replace().
The search() method uses an expression to search for a match, and
returns the position of the match.
Back to Top
Modifier Description
Back to Top
Back to Top
Back to Top
Back to Top
i. Using style property: You can modify inline style using style
property
document.getElementById("title").style.fontSize = "30px";
i. Using ClassName property: It is easy to modify element class
using className property
document.getElementById("title").style.className = "custom-titl
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\/|
return mobileCheck;
};
Back to Top
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.
Back to Top
function httpGet(theUrl)
{
var xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open( "GET", theUrl, false ); // false for synchr
xmlHttpReq.send( null );
return xmlHttpReq.responseText;
}
Back to Top
Back to Top
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
i. window.onload:
i. document.onload:
i. body onload:
<body onload="script();">
Back to Top
Back to Top
// define a function
var fn = function () {
//...
} // semicolon missing at this line
var fn = function () {
//...
}(function () {
//...
})();
Back to Top
const obj = {
prop: 100
};
Object.freeze(obj);
obj.prop = 200; // Throws an error in strict mode
console.log(obj.prop); //100
Back to Top
Back to Top
Back to Top
console.log(language);
Back to Top
function toTitleCase(str) {
return str.replace(
/\w\S*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(
}
);
}
toTitleCase("good morning john"); // Good Morning John
Back to Top
<script type="javascript">
// JS related code goes here
</script>
<noscript>
<a href="next_page.html?noJS=true">JavaScript is disabled in
</noscript>
Back to Top
Back to Top
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
Back to Top
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
const object = {
property: 'Welcome JS world'
};
Object.freeze(object);
console.log(Object.isFrozen(object));
Back to Top
i. both undefined
ii. both null
iii. both true or both false
iv. both strings of the same length with the same characters in the
same order
v. both the same object (means both object have same reference)
vi. 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
191. What is the purpose of using object is method
Some of the applications of Object's is method are follows,
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 }
Back to Top
Back to Top
var handler = {
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
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
i. If it is not extensible.
ii. If all of its properties are non-configurable.
iii. 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
};
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}.`);
}
};
Back to Top
new WeakSet([iterable]);
Back to Top
204. What are the differences between WeakSet and Set
The main difference is that references to objects in Set are strong
while references to objects in WeakSet are weak. i.e, An object in
WeakSet can be garbage collected if there is no other reference to it.
Other differences are,
i. Sets can store any value Whereas WeakSets can store only
collections of objects
ii. WeakSet does not have size property unlike Set
iii. WeakSet does not have methods such as clear, keys, values,
entries, forEach.
iv. WeakSet is not iterable.
Back to Top
205. List
down the collection of methods available on
WeakSet
Below are the list of methods available on WeakSet,
new WeakMap([iterable])
Back to Top
i. Maps can store any key type Whereas WeakMaps can store only
collections of key objects
ii. WeakMap does not have size property unlike Map
iii. WeakMap does not have methods such as clear, keys, values,
entries, forEach.
iv. WeakMap is not iterable.
Back to Top
208. List
down the collection of methods available on
WeakMap
Below are the list of methods available on WeakMap,
i. set(key, value): Sets the value for the key in the WeakMap object.
Returns the WeakMap object.
ii. delete(key): Removes any value associated to the key.
iii. has(key): Returns a Boolean asserting whether a value has been
associated to the key in the WeakMap object or not.
iv. 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
var a = 1;
uneval(a); // returns a String containing 1
uneval(function user() {}); // 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
Back to Top
function (optionalParameters) {
//do something
}
Back to Top
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
Object.defineProperty(newObject, 'newProperty', {
value: 100,
writable: false
});
console.log(newObject.newProperty); // 100
Back to Top
Back to Top
219. What are the advantages of Getters and Setters
Below are the list of benefits of Getters and Setters,
Back to Top
220. Can
I add getters and setters using defineProperty
method
Yes, You can use the Object.defineProperty() method to add
Getters and Setters. For example, the below counter object uses
increment, decrement, add and subtract properties,
// Define getters
Object.defineProperty(obj, "increment", {
get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
get : function () {this.counter--;}
});
// Define setters
Object.defineProperty(obj, "add", {
set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
set : function (value) {this.counter -= value;}
});
obj.add = 10;
obj.subtract = 5;
console.log(obj.increment); //6
console.log(obj.decrement); //5
Back to Top
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Back to Top
Back to Top
i. string
ii. number
iii. boolean
iv. null
v. undefined
Back to Top
224. What
are the different ways to access object
properties
There are 3 possible ways for accessing the property of an object.
objectName.property
i. Square brackets notation: It uses square brackets for property
access
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
try {
eval("greeting('welcome)"); // Missing ' will produce an err
}
catch(err) {
console.log(err.name);
}
Back to Top
228. What are the different error names from error object
There are 6 different types of error names returned from error object,
Back to Top
229. What are the various statements in error handling
Below are the list of statements used in an error handling,
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
Back to Top
Back to Top
i. Whenever you call a function for its execution, you are pushing it
to the stack.
ii. Whenever the execution is completed, the function is popped
out of the stack.
function hungry() {
eatFruits();
}
function eatFruits() {
return "I'm eating fruits";
}
i. Add the hungry() function to the call stack list and execute the
code.
ii. Add the eatFruits() function to the call stack list and execute
the code.
iii. Delete the eatFruits() function from our call stack list.
iv. Delete the hungry() function from the call stack list since there
are no items anymore.
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
Back to Top
var x = "100";
var y = + x;
console.log(typeof x, typeof y); // string, number
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
Back to Top
246. Howdo 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 (len--) {
if (arr[length] > max) {
max = arr[length];
}
}
return max;
}
console.log(findMin(marks));
console.log(findMax(marks));
Back to Top
247. 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
for(int 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
Object oriented
Language
programming Scripting language
paradigm
language
Back to Top
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
class Employee {
constructor() {
this.name = "John";
}
constructor() { // Uncaught SyntaxError: A class may only
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
Back to Top
259. What
happens If I pass string type for getPrototype
method
In ES5, it will throw a TypeError exception if the obj parameter isn't an
object. Whereas in ES2015, the parameter will be coerced to an
Object .
// ES5
Object.getPrototypeOf('James'); // TypeError: "James" is not an
// 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 ne
value: 100
});
} catch (e) {
console.log(e); // TypeError: Cannot define property newProper
}
Back to Top
263. What
are the different ways to make an object non-
extensible
You can mark an object non-extensible in 3 ways,
i. Object.preventExtensions
ii. Object.seal
iii. Object.freeze
Object.defineProperties(newObject, {
newProperty1: {
value: 'John',
writable: true
},
newProperty2: {}
});
Back to Top
Back to Top
function greeting() {
console.log('Hello, welcome to JS world');
}
eval(function(p,a,c,k,e,d){e=function(c){return c};if(!''.replac
Back to Top
Back to Top
Back to Top
Back to Top
270. What
are the differences between Obfuscation and
Encryption
Below are the main differences between Obfuscation and Encryption,
Target It will be
Converted into an
data converted to a
unreadable format
format complex form
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>
function myFunction() {
var userName = document.getElementById("uname");
if (!userName.checkValidity()) {
document.getElementById("message").innerHTML = userName.vali
} else {
document.getElementById("message").innerHTML = "Entered a va
}
}
Back to Top
275. What
are the available constraint validation DOM
properties
Below are the list of some of the constraint validation DOM
properties available,
Back to Top
Back to Top
Back to Top
enum Color {
RED, GREEN, BLUE
}
Back to Top
const newObject = {
a: 1,
b: 2,
c: 3
};
Back to Top
const newObject = {
a: 1,
b: 2,
c: 3
};
const descriptorsObject = Object.getOwnPropertyDescriptors(newOb
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
Back to Top
Back to Top
Back to Top
console.log(convertToThousandFormat(12345.6789));
Back to Top
It's a strongly
Typed It's a dynamic typed language
typed language
Back to Top
}
function func1() {
console.log("This is a second definition");
}
func1(); // This is a second definition
Back to Top
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.
Back to Top
document.getElementById('targetFrame').contentWindow.targetFunct
window.frames[0].frameElement.contentWindow.targetFunction(); //
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
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
Back to Top
function myFunction() {
window.document.body.style.cursor = "wait";
}
<body onload="myFunction()">
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;
}
Back to Top
Back to Top
Back to Top
Back to Top
306. Can I redeclare let and const variables
No, you cannot redeclare let and const variables. If you do, it throws
below error
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
Note: You can use multi-line strings and string interpolation features
with template literals.
Back to Top
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}${skillEx
}
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"
console.log(name); // John
console.log(age); // 32
Back to Top
Arrays destructuring:
var x, y, z;
Objects destructuring:
console.log(x); // 10
console.log(y); // 4
console.log(z); // 6
Back to Top
Back to Top
//ES6
var x = 10, y = 20
obj = { x, y }
console.log(obj); // {x: 10, y:20}
//ES5
var x = 10, y = 20
obj = { x : x, y : y}
console.log(obj); // {x: 10, y:20}
Back to Top
Back to Top
if (isLegacyBrowser()) {
import(···)
.then(···);
}
import(`messages_${getLocale()}.js`).then(···);
Back to Top
For example, you can create an array of 8-bit signed integers as below
Back to Top
i. Dynamic loading
ii. State isolation
iii. Global namespace isolation
iv. Compilation hooks
v. Nested virtualization
Back to Top
i. Comparison:
var list = [ "ä", "a", "z" ]; // In German, "ä" sorts with "a"
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
i. Sorting:
var list = [ "ä", "a", "z" ]; // In German, "ä" sorts with "a"
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
Back to Top
targetWindow.postMessage(message, '*');
Back to Top
//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',
}
});
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
console.log(document.getElementById(‘checkboxname’).checked); //
Back to Top
Back to Top
"ABC".charCodeAt(0) // returns 65
Back to Top
Back to Top
console.log("Welcome to JS world"[0])
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); // "E
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;
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
Back to Top
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
}
Back to Top
'Hello'.repeat(4); // 'HelloHelloHelloHello'
console.log(greetingList[0]); //Hello1
console.log(greetingList[1]); //Hello2
console.log(greetingList[2]); //Hello3
Back to Top
348. How do you trim a string at the beginning or ending
The trim method of string prototype is used to trim on both sides of
a string. But if you want to trim especially at the beginning or ending
of the string then you can use trimStart/trimLeft and
trimEnd/trimRight methods. Let's see an example of these methods
on a greeting message,
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');
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
thunk() // 5
Back to Top
function fetchData(fn){
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => fn(json))
}
asyncThunk()
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:
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
i. Since Arrays are truthful values, negating the arrays will produce
false: ![] === false
ii. As per JavaScript coercion rules, the addition of arrays together
will toString them: [] + [] === ""
iii. 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
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
364. How do you empty an array
You can empty an array quickly by setting the array length to zero.
Back to Top
Back to Top
Back to Top
Back to Top
i. %o — It takes an object,
ii. %s — It takes a string,
iii. %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
Back to Top
370. What is the purpose of dir method of console object
The console.dir() is used to display an interactive list of the
properties of the specified JavaScript object as JSON.
Back to Top
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.
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,
const flattenArr = [].concat(...biDimensionalArr); // [11, 22, 3
function flattenMultiArray(arr) {
const flattened = [].concat(...arr);
return flattened.some(item => Array.isArray(item)) ? flatten
}
const multiDimensionalArr = [11, [22, 33], [44, [55, 66, [77, [8
const flatArr = flattenMultiArray(multiDimensionalArr); // [11,
Back to Top
// Verbose approach
if (input === 'first' || input === 1 || input === 'second' || in
someFunction();
}
// Shortcut
if (['first', 1, 'second', 2].indexOf(input) !== -1) {
someFunction();
}
Back to Top
window.onbeforeunload = function() {
alert("You work will be lost");
};
Back to Top
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
Back to Top
i. Callbacks
ii. Promises
iii. Async/await
iv. Third-party libraries such as async.js,bluebird etc
Back to Top
Back to Top
In this API, browser is going to ask you for permission to use your
microphone
function runMeFirst() {
console.log('My script is initialized');
}
setTimeout(runMeFirst, 0);
console.log('Script loaded');
Script loaded
My script is initialized
My script is initialized
Script loaded
Back to Top
386. How
do you implement zero timeout in modern
browsers
You can't use setTimeout(fn, 0) to execute the code immediately due
to minimum delay of greater than 0ms. But you can use
window.postMessage() to achieve this behavior.
Back to Top
Note: All of these microtasks are processed in the same turn of the
event loop. Back to Top
Back to Top
392. What
are the differences between promises and
observables
Some of the major difference in a tabular form
Promises Observables
Promise is always
Observable can be either
asynchronous even though
synchronous or asynchronous
it resolved immediately
Back to Top
Back to Top
Back to Top
Back to Top
isPrimitive(myPrimitive);
isPrimitive(myNonPrimitive);
Back to Top
i. Transform syntax
ii. Polyfill features that are missing in your target environment
(using @babel/polyfill)
iii. Source code transformations (or codemods)
Back to Top
Back to Top
Back to Top
Back to Top
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
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,
i. 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.
ii. 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);
});
getDataFromHttp()
.then(function(result) {
return displayData(processDataAsync(result));
})
and then you forgot to add done block to then block leads to
silent errors.
Promise.onPossiblyUnhandledRejection(function(error){
throw error;
});
Back to Top
Back to Top
410. How do you make an object iterable in javascript
By default, plain objects are not iterable. But you can make the object
iterable by defining a Symbol.iterator property on it.
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: tr
Back to Top
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(p)); // 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
Back to Top
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();
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
417. What are the built-in iterables
Below are the list of built-in iterables in javascript,
Back to Top
arr.newProp = 'newVlue';
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 insider constructor as
below,
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
Person.staticAge = 30;
Person.prototype.prototypeAge = 40;
Back to Top
420. What
is the difference between isNaN and
Number.isNaN?
i. isNaN: The global function isNaN converts the argument to a
Number and returns true if the resulting value is NaN.
ii. Number.isNaN: This method does not convert the argument. But
it returns true when the type is a Number and value is NaN.
Let's see the difference with an example,
isNaN(‘hello’); // true
Number.isNaN('hello'); // false
Coding Exercise
1: Undefined
2: ReferenceError
3: null
4: {model: "Honda", color: "white", year: "2010", country: "UK"}
Answer
function foo() {
let x = y = 0;
x++;
y++;
return x;
}
Answer
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
1: false
2: true
Answer
5. What is the output of below code
var y = 1;
if (function f(){}) {
y += typeof f;
}
console.log(y);
1: 1function
2: 1object
3: ReferenceError
4: 1undefined
Answer
function foo() {
return
{
message: "Hello World"
};
}
console.log(foo());
1: Hello World
2: Object {message: "Hello World"}
3: Undefined
4: SyntaxError
Answer
Answer
Answer
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
1: true, true
2: true, false
3: SyntaxError, SyntaxError,
4: false, false
Answer
Answer
1: 1, 2, 3
2: 3, 2, 3
3: SyntaxError: Duplicate parameter name not allowed in this context
4: 1, 2, 1
Answer
Answer
14. What is the output of below code
1: True, False
2: False, True
Answer
console.log(Math.max());
1: undefined
2: Infinity
3: 0
4: -Infinity
Answer
console.log(10 == [10]);
console.log(10 == [[[[[[[10]]]]]]]);
1: True, True
2: True, False
3: False, False
4: False, True
Answer
console.log(10 + '10');
console.log(10 - '10');
1: 20, 0
2: 1010, 0
3: 1010, 10-10
4: NaN, NaN
Answer
console.log([0] == false);
if([0]) {
console.log("I'm True");
} else {
console.log("I'm False");
}
Answer
Answer
Answer
1: True
2: False
Answer
1: 4
2: NaN
3: SyntaxError
4: -1
Answer
1: 1, [2, 3, 4, 5]
2: 1, {2, 3, 4, 5}
3: SyntaxError
4: 1, [2, 3, 4]
Answer
1: Promise {: 10}
2: 10
3: SyntaxError
4: Promise {: 10}
Answer
1: Promise {: 10}
2: 10
3: SyntaxError
4: Promise {: undefined}
Answer
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
function delay() {
return new Promise(resolve => setTimeout(resolve, 2000));
}
Answer
Answer
1: true, true
2: true, false
3: false, true
4: false, false
Answer
1: SyntaxError
2: one
3: Symbol('one')
4: Symbol
Answer
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
Answer
class A {
constructor() {
console.log(new.target.name)
}
}
new A();
new B();
1: A, A
2: A, B
Answer
1: 1, [2, 3, 4]
2: 1, [2, 3]
3: 1, [2]
4: SyntaxError
Answer
console.log(x);
console.log(y);
1: 30, 20
2: 10, 20
3: 10, undefined
4: 30, undefined
Answer
area();
1: 200
2: Error
3: undefined
4: 0
Answer
1: Tom
2: Error
3: undefined
4: John
Answer
function checkType(num = 1) {
console.log(typeof num);
}
checkType();
checkType(undefined);
checkType('');
checkType(null);
Answer
console.log(add('Orange'));
console.log(add('Apple'));
Answer
greet('Hello', 'John');
greet('Hello', 'John', 'Good morning!');
1: SyntaxError
2: ['Hello', 'John', 'Hello John'], ['Hello', 'John', 'Good morning!']
Answer
1: ReferenceError
2: Inner
Answer
myFun(1, 2, 3, 4, 5);
myFun(1, 2);
Answer
1: ['key', 'value']
2: TypeError
3: []
4: ['key']
Answer
45. What is the output of below code
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
function* yieldAndReturn() {
yield 1;
return 2;
yield 3;
}
Answer
Answer
1: SyntaxError
2: 38
Answer
49. What is the output of below code
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
function Person() { }
Person.prototype.walk = function() {
return this;
}
Person.run = function() {
return this;
}
1: undefined, undefined
2: Person, Person
3: SyntaxError
4: Window, Window
Answer
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
1: 30
2: 25
3: Uncaught TypeError
4: SyntaxError
Answer
Back to Top
1: false
2: true
Answer
Back to Top
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
Releases
No releases published
Packages
No packages published
Contributors 23
+ 12 contributors
Languages
JavaScript 100.0%
© 2020 GitHub, Inc. Terms Privacy Security Status Help Contact GitHub Pricing
API Training Blog About