400+ JavaScript Interview QnA
400+ JavaScript Interview QnA
var object = {
name: "Sudheer",
age: 34
};
In this approach, create any function and apply the new operator
to create object instances.
function Person(name) {
this.name = name;
this.age = 21;
}
var object = new Person("Sudheer");
function Person() {}
Person.prototype.name = "Sudheer";
var object = new Person();
function func() {}
(OR)
class Person {
constructor(name) {
this.name = name;
}
}
Call: The call() method invokes a function with a given this value and
arguments provided one by one
var employee1 = { firstName: "John", lastName: "Rodson" };
var employee2 = { firstName: "Jimmy", lastName: "Baily" };
Apply: Invokes the function with a given this value and allows you to
pass in arguments as an array
var employee1 = { firstName: "John", lastName: "Rodson" };
var employee2 = { firstName: "Jimmy", lastName: "Baily" };
Call and Apply are pretty much interchangeable. Both execute the
current function immediately. You need to decide whether it’s easier to
send in an array or a comma separated list of arguments. You can
remember by treating Call is for comma (separated list) and Apply is
for Array.
Bind creates a new function that will have this set to the first
parameter passed to bind().
JSON.parse(text);
JSON.stringify(object);
Note: Slice method doesn't mutate the original array but it returns the
subset as a new array.
Note: Splice method modifies the original array and returns the
deleted array.
Slice Splice
Returns the subset of original array Returns the deleted elements as array
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
Let's take an example of n-ary function and how it turns into a currying
function,
Let's take an example to see the difference between pure and impure
functions,
//Impure
let numberArray = [];
const impureAddNumber = (number) => numberArray.push(number);
//Pure
const pureAddNumber = (number) => (argNumberArray) =>
argNumberArray.concat([number]);
As per the above code snippets, the Push function is impure itself by
altering the array and returning a push number index independent of
the parameter value, whereas Concat on the other hand takes the
array and concatenates it with the other array producing a whole new
array without side effects. Also, the return value is a concatenation of
the previous array.
var let
It has been available from the beginning of JavaScript Introduced as part of ES6
function userDetails(username) {
if (username) {
console.log(salary); // undefined due to hoisting
console.log(age); // ReferenceError: Cannot access 'age' before
initialization
let age = 30;
var salary = 10000;
}
console.log(salary); //10000 (accessible due to function scope)
console.log(age); //error: age is not defined(due to block scope)
}
userDetails("John");
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;
}
}
(function () {
// logic here
})();
(function () {
var message = "IIFE";
console.log(message);
})();
console.log(message); //Error: message is not defined
var message;
console.log(message);
message = "The variable Has been hoisted";
function message(name) {
console.log(name);
}
This hoisting makes functions to be safely used in code before they are
declared.
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";
}
}
function Welcome(name) {
var greetingInfo = function (message) {
console.log(message + " " + name);
};
return greetingInfo;
}
var myFunction = Welcome("John");
myFunction("Welcome "); //Output: Welcome John
myFunction("Hello Mr."); //output: Hello Mr.John
As per the above code, the inner function(i.e, greetingInfo) has access
to the variables in the outer function scope(i.e, Welcome) even after
the outer function has returned.
i. Maintainability
ii. Reusability
iii. Namespacing
document.cookie = "username=John";
ii. By default, the cookie belongs to a current page. But you can tell
the browser what path the cookie belongs to using a path
parameter.
document.cookie =
"username=; expires=Fri, 07 Jun 2019 00:00:00 UTC; path=/;";
Note: You should define the cookie path option to ensure that you
delete the right cookie. Some browsers doesn't allow to delete a cookie
unless you specify a path parameter.
Not Not
SSL support Supported
supported supported
window.onstorage = functionRef;
Let's take the example usage of onstorage event handler which logs
the storage key and it's values
let i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()", 500);
}
timedCount();
ii. 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");
}
iii. Terminate a Web Worker: Web workers will continue to listen for
messages (even after the external script is finished) until it is
terminated. You can use the terminate() method to terminate
listening to the messages.
w.terminate();
iv. Reuse the Web Worker: If you set the worker variable to
undefined you can reuse the code
w = undefined;
i. Window object
ii. Document object
iii. Parent object
51. 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
As observed from the output, javascript didn't wait for the response of
the first function and the remaining code block got executed. So
callbacks are used in a way to make sure that certain code doesn’t
execute until the other code finishes execution.
async1(function(){
async2(function(){
async3(function(){
async4(function(){
....
});
});
});
});
Event Description
"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
}
If you don't use this expression then it returns the original value.
user = undefined;
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.
Null Undefined
The null value is a primitive value that The undefined value is a primitive value
represents the null, empty, or non- used when a variable has not been
existent reference. assigned a value.
console.log(eval("1 + 2")); // 3
Window Document
It is the root level element in It is the direct child of the window object. This is
any web page also known as Document Object Model(DOM)
function goBack() {
window.history.back();
}
function goForward() {
window.history.forward();
}
<p id="feedback"></p>
<script>
function enterInput(e) {
var flag = e.getModifierState("CapsLock");
if (flag) {
document.getElementById("feedback").innerHTML = "CapsLock
activated";
} else {
document.getElementById("feedback").innerHTML =
"CapsLock not activated";
}
}
</script>
isNaN("Hello"); //true
isNaN("100"); //false
If you try to read the value of an If you try to read the value of an
undeclared variable, then a runtime error undefined variable, an undefined value
is encountered is returned.
Math.sqrt(-1);
parseInt("Hello");
isFinite(Infinity); // false
isFinite(NaN); // false
isFinite(-Infinity); // false
isFinite(100); // true
console.log(navigator.platform);
i. Chrome Devtools
ii. debugger statement
iii. Good old console.log statement
Pros:
Cons:
<!doctype html>
<html>
<head>
<script>
function greeting() {
alert('Hello! Good morning');
}
</script>
</head>
<body>
<button type="button" onclick="greeting()">Click me</button>
</body>
</html>
document
.getElementById("link")
.addEventListener("click", function (event) {
event.preventDefault();
});
<script>
function firstFunc(event) {
alert("DIV 1");
event.stopPropagation();
}
function secondFunc() {
alert("DIV 2");
}
</script>
104. What are the steps involved in return false
usage
The return false statement in event handlers performs the below steps,
setTimeout(function () {
console.log("Good morning");
}, 2000);
setInterval(function () {
console.log("Good morning");
}, 2000);
<script>
var msg;
function greeting() {
alert('Good morning');
}
function start() {
msg =setTimeout(greeting, 3000);
function stop() {
clearTimeout(msg);
}
</script>
118. What is the purpose of clearInterval method
The clearInterval() function is used in javascript to clear the interval
which has been set by setInterval() function. i.e, The return value
returned by setInterval() function is stored in a variable and it’s passed
into the clearInterval() function to clear the interval.
<script>
var msg;
function greeting() {
alert('Good morning');
}
function start() {
msg = setInterval(greeting, 3000);
function stop() {
clearInterval(msg);
}
</script>
function validateEmail(email) {
var re =
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\
[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+
[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
"key" in obj;
!("key" in obj);
ii. Using hasOwnProperty method: You can
use hasOwnProperty to particularly test for properties of the object
instance (and not inherited properties)
obj.hasOwnProperty("key"); // true
const user = {
name: "John",
};
ii. 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;
}
}
function sum() {
var total = 0;
for (var i = 0, len = arguments.length; i < len; ++i) {
total += arguments[i];
}
return total;
}
Note: You can't apply array methods on arguments object. But you
can convert into a regular array as below.
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
Pros
Cons
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, "");
};
})();
}
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";
As per the above expression, variable 'a 'will get the value of 'c' only if
'b' is falsy (if is null, false, undefined, 0, empty string, or NaN),
otherwise 'a' will get the value of 'b'.
138. How do you define multiline strings
You can define multiline string literals using the '\' character followed
by line terminator.
var str =
"This is a \
very lengthy \
sentence!";
But if you have a space after the '\' character, the code will look
exactly the same, but it will raise a SyntaxError.
fn = function (x) {
//Function code goes here
};
fn.name = "John";
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"
var v1 = {};
var v2 = "";
var v3 = 0;
var v4 = false;
var v5 = [];
var v6 = /()/;
var v7 = function () {};
"users":[
{"firstName":"John", "lastName":"Abrahm"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Shane", "lastName":"Warn"}
]
/pattern/modifiers;
/John/i;
Modifier Description
i. Using style property: You can modify inline style using style
property
document.getElementById("title").style.fontSize = "30px";
document.getElementById("title").className = "custom-title";
162. What would be the result of 1+2+'3'
The output is going to be 33. Since 1 and 2 are numeric values, the
result of the first two digits is going to be a numeric value 3. The next
digit is a string type value because of that the addition of numeric
value 3 and string type value 3 is just going to be a concatenation
value 33.
function getProfile() {
// code goes here
debugger;
// code goes here
}
window.mobilecheck = function () {
var mobileCheck = false;
(function (a) {
if (
/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|
compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |
maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|
phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.
(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
a
) ||
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|
s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|
attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|
bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|
craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|
ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|
g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|
hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|
go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|
v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|
xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|
xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|
t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|
n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|
op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|
pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-
[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|
va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|
sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|
v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|
tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|
v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|
80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|
your|zeto|zte\-/i.test(
a.substr(0, 4)
)
)
mobileCheck = true;
})(navigator.userAgent || navigator.vendor || window.opera);
return mobileCheck;
};
167. How do you detect a mobile browser without
regexp
You can detect mobile browsers by simply running through a list of
devices and checking if the useragent matches anything. This is an
alternative solution for RegExp usage,
function detectmob() {
if (
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPad/i) ||
navigator.userAgent.match(/iPod/i) ||
navigator.userAgent.match(/BlackBerry/i) ||
navigator.userAgent.match(/Windows Phone/i)
) {
return true;
} else {
return false;
}
}
function httpGet(theUrl) {
var xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open("GET", theUrl, false); // false for synchronous
request
xmlHttpReq.send(null);
return xmlHttpReq.responseText;
}
var width =
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
var height =
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
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;
}
}
175. What are the ways to execute javascript after
page load
You can execute javascript after page load in many different ways,
i. window.onload:
ii. document.onload:
<body onload="script();">
// define a function
var fn = (function () {
//...
})(
// semicolon missing at this line
var fn = (function () {
//...
})(function () {
//...
})();
const obj = {
prop: 100,
};
Object.freeze(obj);
obj.prop = 200; // Throws an error in strict mode
console.log(obj.prop); //100
const user = {
name: "John",
employment: {
department: "IT",
},
};
Object.freeze(user);
user.employment.department = "HR";
var language =
(navigator.languages && navigator.languages[0]) || // Chrome /
Firefox
navigator.language || // All browsers
navigator.userLanguage; // IE <= 10
console.log(language);
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() +
txt.substring(1).toLowerCase();
});
}
toTitleCase("good morning john"); // Good Morning John
function sum(...args) {
let total = 0;
for (const i of args) {
total += i;
}
return total;
}
function someFunc(a,…b,c){
//You code goes here
return;
}
function calculateSum(x, y, z) {
return x + y + z;
}
console.log(calculateSum(...numbers)); // 6
189. How do you determine whether object is
frozen or not
Object.isFrozen() method is used to determine if an object is frozen or
not.An object is frozen if all of the below conditions hold true,
i. If it is not extensible.
ii. If all of its properties are non-configurable.
iii. If all its data properties are non-writable. The usage is going to
be as follows,
const object = {
property: "Welcome JS world",
};
Object.freeze(object);
console.log(Object.isFrozen(object));
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.
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 }
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
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
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",
};
const object = {
a: "Good morning",
b: 100,
};
const object = {
a: "Good morning",
b: 100,
};
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,
};
const user = {
name: "John",
printInfo: function () {
console.log(`My name is ${this.name}.`);
},
};
new WeakSet([iterable]);
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.
205. List down the collection of methods available
on WeakSet
Below are the list of methods available on WeakSet,
new WeakMap([iterable]);
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.
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,
var a = 1;
uneval(a); // returns a String containing 1
uneval(function user() {}); // returns "(function user(){})"
function (optionalParameters) {
//do something
}
Object.defineProperty(newObject, "newProperty", {
value: 100,
writable: false,
});
console.log(newObject.newProperty); // 100
// 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
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
The above multi-way branch statement provides an easy way to
dispatch execution to different parts of code based on the value of the
expression.
i. string
ii. number
iii. boolean
iv. null
v. undefined
vi. bigint
vii. symbol
objectName.property;
objectName["property"];
objectName[expression];
try {
greeting("Welcome");
} catch (err) {
console.log(err.name + "<br>" + err.message);
}
try {
eval("greeting('welcome)"); // Missing ' will produce an error
} catch (err) {
console.log(err.name);
}
ReferenceErro
An error due to an illegal reference
r
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";
}
iii. Add the hungry() function to the call stack list and execute the
code.
iv. Add the eatFruits() function to the call stack list and execute the
code.
v. Delete the eatFruits() function from our call stack list.
vi. Delete the hungry() function from the call stack list since there
are no items anymore.
238. What is an event queue
The event queue follows the queue data structure. It stores async
callbacks to be added to the call stack. It is also known as the Callback
Queue or Macrotask Queue.
The event loop constantly checks whether or not the call stack is
empty. Once the call stack is empty and there is a callback in the
event queue, the event loop moves the callback into the call stack. But
if there is a callback in the microtask queue as well, it is moved first.
The microtask queue has a higher priority than the event queue.
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
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
242. How do you sort elements in an array
The sort() method is used to sort the elements of an array in place and
returns the sorted array. The example usage would be as below,
console.log(findMin(marks));
console.log(findMax(marks));
function findMax(arr) {
var length = arr.length;
var max = -Infinity;
while (length--) {
if (arr[length] > max) {
max = arr[length];
}
}
return max;
}
console.log(findMin(marks));
console.log(findMax(marks));
// Initialize an array a
for (let i = 0; i < a.length; a[i++] = 0);
var x = 1;
x = (x++, x);
console.log(x); // 2
You can also use the comma operator in a return statement where it
processes before returning.
function myFunction() {
var a = 1;
return (a += 10), a; // 11
}
console.log(greeting(user));
console.log(initObject.a); // John
class Employee {
constructor() {
this.name = "John";
}
}
console.log(employeeObject.name); // John
console.log(employeeObject.name);
get area() {
return this.width * this.height;
}
set area(value) {
this.area = value;
}
}
Note: By default, all the objects are extendable. i.e, The new
properties can be added or modified.
try {
Object.defineProperty(newObject, "newProperty", {
// Adding new property
value: 100,
});
} catch (e) {
console.log(e); // TypeError: Cannot define property newProperty,
object is not extensible
}
i. Object.preventExtensions
ii. Object.seal
iii. Object.freeze
Object.defineProperties(newObject, {
newProperty1: {
value: "John",
writable: true,
},
newProperty2: {},
});
function greeting() {
console.log("Hello, welcome to JS world");
}
eval(
(function (p, a, c, k, e, d) {
e = function (c) {
return c;
};
if (!"".replace(/^/, String)) {
while (c--) {
d[c] = k[c] || c;
}
k = [
function (e) {
return d[e];
},
];
e = function () {
return "\\w+";
};
c = 1;
}
while (c--) {
if (k[c]) {
p = p.replace(new RegExp("\\b" + e(c) + "\\b", "g"), k[c]);
}
}
return p;
})(
"2 1(){0.3('4, 7 6 5 8')}",
9,
9,
"console|greeting|function|log|Hello|JS|to|welcome|
world".split("|"),
0,
{}
)
);
function validateForm() {
var x = document.forms["myForm"]["uname"].value;
if (x == "") {
alert("The username shouldn't be empty");
return false;
}
}
function myFunction() {
var userName = document.getElementById("uname");
if (!userName.checkValidity()) {
document.getElementById("message").innerHTML =
userName.validationMessage;
} else {
document.getElementById("message").innerHTML =
"Entered a valid username";
}
}
enum Color {
RED, GREEN, BLUE
}
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));
Object oriented
Paradigm Prototype based programming
programming
function func1() {
console.log("This is a first definition");
}
function func1() {
console.log("This is a second definition");
}
func1(); // This is a second definition
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).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.
function myFunction() {
window.document.body.style.cursor = "wait";
}
<body onload="myFunction()"></body>
for (;;) {}
while (true) {}
a.b.c.greeting = "welcome";
a.b.c.age = 32;
myFunc();
alert(name);
//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
Note: You can use multi-line strings and string interpolation features
with template literals.
318. How do you write multi-line strings in
template literals
In ES5, you would have to use newline escape characters('\n') and
concatenation symbols(+) in order to get multi-line strings.
You can write the above use case without nesting template features as
well. However, the nesting template feature is more compact and
readable.
var expertiseStr;
if (experienceExp > 10) {
expertiseStr = "expert developer";
} else if (skillExp > 5 && skillExp <= 10) {
expertiseStr = "senior developer";
} else {
expertiseStr = "junior developer";
}
return `${str0}${userExp}${str1}${expertiseStr}${str2}${skillExp}`;
}
If you don't use raw strings, the newline character sequence will be
processed by displaying the output in multiple lines
Also, the raw property is available on the first argument to the tag
function
function tag(strings) {
console.log(strings.raw[0]);
}
console.log(one); // "JAN"
console.log(two); // "FEB"
console.log(three); // "MARCH"
console.log(name); // John
console.log(age); // 32
Arrays destructuring:
var x, y, z;
[x = 2, y = 4, z = 6] = [10];
console.log(x); // 10
console.log(y); // 4
console.log(z); // 6
Objects destructuring:
var { x = 2, y = 4, z = 6 } = { x: 10 };
console.log(x); // 10
console.log(y); // 4
console.log(z); // 6
var x = 10,
y = 20;
//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}
if (isLegacyBrowser()) {
import(···)
.then(···);
}
ii. Compute the module specifier at runtime. For example, you can
use it for internationalization.
import(`messages_${getLocale()}.js`).then(···);
For example, you can create an array of 8-bit signed integers as below
i. Dynamic loading
ii. State isolation
iii. Global namespace isolation
iv. Compilation hooks
v. Nested virtualization
i. Comparison:
var list = ["ä", "a", "z"]; // In German, "ä" sorts with "a" Whereas
in Swedish, "ä" sorts after "z"
var l10nDE = new Intl.Collator("de");
var l10nSV = new Intl.Collator("sv");
console.log(l10nDE.compare("ä", "z") === -1); // true
console.log(l10nSV.compare("ä", "z") === +1); // true
ii. Sorting:
var list = ["ä", "a", "z"]; // In German, "ä" sorts with "a" Whereas
in Swedish, "ä" sorts after "z"
var l10nDE = new Intl.Collator("de");
var l10nSV = new Intl.Collator("sv");
console.log(list.sort(l10nDE.compare)); // [ "a", "ä", "z" ]
console.log(list.sort(l10nSV.compare)); // [ "a", "z", "ä" ]
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.
targetWindow.postMessage(message, "*");
//Listener on http://www.some-receiver.com/
window.addEventListener("message", function(message){
if(/^http://www\.some-sender\.com$/.test(message.origin)){
console.log('You received the data from valid sender',
message.data);
}
});
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);
}
try {
throw new EvalError('Eval function error', 'someFile.js', 100);
} catch (e) {
console.log(e.message, e.name, e.fileName); // "Eval
function error", "EvalError", "someFile.js"
348. What are the list of cases error thrown from
non-strict mode to strict mode
When you apply 'use strict'; syntax, some of the below cases will throw
a SyntaxError before executing the script
var n = 022;
if (someCondition) {
function f() {}
}
Hence, the errors from above cases are helpful to avoid errors in
development/production environments.
Example
var empDetails = {
name: "John",
age: 25,
expertise: "Software Developer",
};
to create a duplicate
empDetailsShallowCopy.name = "Johnson";
The above statement will also change the name of empDetails, since we
have a shallow copy. That means we're losing the original data as well.
Deep copy: A deep copy copies all fields, and makes copies of
dynamically allocated memory pointed to by the fields. A deep copy
occurs when an object is copied along with the objects to which it
refers.
Example
var empDetails = {
name: "John",
age: 25,
expertise: "Software Developer",
};
Create a deep copy by using the properties from the original object
into new variable
var empDetailsDeepCopy = {
name: empDetails.name,
age: empDetails.age,
expertise: empDetails.expertise,
};
console.log(greetingList[0]); //Hello1
console.log(greetingList[1]); //Hello2
console.log(greetingList[2]); //Hello3
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.
Say for instance, we've two classes User and CleanRoom. Suppose we
need to add CleanRoom functionality to User, so that user can clean the
room at demand. Here's where concept called mixins comes into
picture.
// mixin
let cleanRoomMixin = {
cleanRoom() {
alert(`Hello ${this.name}, your room is clean now`);
},
sayBye() {
alert(`Bye ${this.name}`);
},
};
// usage:
class User {
constructor(name) {
this.name = name;
}
}
thunk(); // 5
function fetchData(fn) {
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json())
.then((json) => fn(json));
}
asyncThunk();
const circle = {
radius: 20,
diameter() {
return this.radius * 2;
},
perimeter: () => 2 * Math.PI * this.radius,
};
console.log(circle.diameter());
console.log(circle.perimeter());
Output:
In the above expression, g and m are for global and multiline flags.
console.log(+null); // 0
console.log(+undefined); // NaN
console.log(+false); // 0
console.log(+NaN); // NaN
console.log(+""); // 0
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
^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^
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
console.log(
"%c The text has blue color, with large font and red background",
"color: blue; font-size: x-large; background: red"
);
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
document.querySelector("#copy-button").onclick = function () {
// Select the content
document.querySelector("#copy-input").select();
// Copy to the clipboard
document.execCommand("copy");
};
const biDimensionalArr = [11, [22, 33], [44, 55], [66, 77], 88, 99];
const flattenArr = [].concat(...biDimensionalArr); // [11, 22, 33, 44,
55, 66, 77, 88, 99]
function flattenMultiArray(arr) {
const flattened = [].concat(...arr);
return flattened.some((item) => Array.isArray(item))
? flattenMultiArray(flattened)
: flattened;
}
const multiDimensionalArr = [11, [22, 33], [44, [55, 66, [77, [88]],
99]]];
const flatArr = flattenMultiArray(multiDimensionalArr); // [11, 22, 33,
44, 55, 66, 77, 88, 99]
You can also use popstate event to detect the browser back
button. Note: The history entry has been activated
using history.pushState method.
window.addEventListener('popstate', () => {
console.log('Clicked browser back button');
box.style.backgroundColor = 'white';
});
box.addEventListener('click', () => {
box.style.backgroundColor = 'blue';
window.history.pushState({}, null, null);
});
In the preceeding code, When the box element clicked, its background color
appears in blue color and changed to while color upon clicking the browser
back button using `popstate` event handler. The `state` property of
`popstate` contains the copy of history entry's state object.
**[ ](#table-of-contents)**
i.e, Every primitive except null and undefined have Wrapper Objects
and the list of wrapper objects are String,Number,Boolean,Symbol and
BigInt.
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!
}
});
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);
}
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
Note: All of these microtasks are processed in the same turn of the
event loop.
**[ ](#table-of-contents)**
Example:
console.log("Start"); //1
queueMicrotask(() => {
console.log("Inside microtask"); // 3
});
console.log("End"); //2
Eager in nature; they are going to be Lazy in nature; they require subscription to
called immediately be invoked
isPrimitive(myPrimitive);
isPrimitive(myNonPrimitive);
i. Transform syntax
ii. Polyfill features that are missing in your target environment
(using @babel/polyfill)
iii. Source code transformations (or codemods)
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
if (authenticate) {
loginToPorta();
}
Since the javascript logical operators evaluated from left to right, the
above expression can be simplified using && logical operator
array.length = 2;
console.log(array.length); // 2
console.log(array); // [1,2]
Note: Observables are not part of the JavaScript language yet but they
are being proposed to be added to the language
Classes:
class User {}
Constructor Function:
function User() {}
407. What is an async function
An async function is a function declared with the async keyword which
enables asynchronous, promise-based behavior to be written in a
cleaner style by avoiding promise chains. These functions can contain
zero or more await expressions.
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
But it is quite difficult to type for each promise chain and verbose
too.
viii. Add done method: You can replace first solution's then and
catch blocks with done method
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);
});
and then you forgot to add done block to then block leads to silent
errors.
const collection = {
one: 1,
two: 2,
three: 3,
[Symbol.iterator]() {
const values = Object.keys(this);
let i = 0;
return {
next: () => {
return {
value: this[values[i++]],
done: i > values.length,
};
},
};
},
};
const collection = {
one: 1,
two: 2,
three: 3,
[Symbol.iterator]: function* () {
for (let key in this) {
yield this[key];
}
},
};
const iterator = collection[Symbol.iterator]();
console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false}
console.log(iterator.next()); // {value: undefined, done: true}
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.
412. How do you check an object is a promise or
not
If you don't know if a value is a promise or not, wrapping the value
as Promise.resolve(value) which returns a promise
function isPromise(object) {
if (Promise && Promise.resolve) {
return Promise.resolve(object) == object;
} else {
throw "Promise not supported in your environment";
}
}
var i = 1;
var promise = new Promise(function (resolve, reject) {
resolve();
});
console.log(isPromise(i)); // false
console.log(isPromise(promise)); // true
console.log(isPromise(i)); // false
console.log(isPromise(promise)); // true
function Myfunc() {
if (new.target) {
console.log("called with new");
} else {
console.log("not called with new");
}
}
arr.newProp = "newVlue";
Since for..in loop iterates over the keys of the object, the first loop logs
0, 1, 2 and newProp while iterating over the array object. The for..of
loop iterates over the values of a arr data structure and logs a, b, c in
the console.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
Person.staticAge = 30;
Person.prototype.prototypeAge = 40;
isNaN(‘hello’); // true
Number.isNaN('hello'); // false
(function (dt) {
console.log(dt.toLocaleTimeString());
})(new Date());
Since both IIFE and void operator discard the result of an expression,
you can avoid the extra brackets using void operator for IIFE as below,
void (function (dt) {
console.log(dt.toLocaleTimeString());
})(new Date());
It is also possible to add more styles for the content. For example, the
font-size can be modified for the above text
console.log(
"%cThis is a red text with bigger font",
"color:red; font-size:20px"
);
console.group("User Details");
console.log("name: Sudheer Jonna");
console.log("job: Software Developer");
// Nested Group
console.group("Address");
console.log("Street: Commonwealth");
console.log("City: Los Angeles");
console.log("State: California");
console.log(newArray); // [ 5, 4, 3, 2, 1]
console.log(originalArray); // [ 5, 4, 3, 2, 1]
There are few solutions that won't mutate the original array. Let's take
a look.
vi. Using spread and reverse methods: In this case, let's use the
spread syntax (...) to create a copy of the array followed
by reverse() method call on the copy.
vii. const originalArray = [1, 2, 3, 4, 5];
viii. const newArray = [...originalArray].reverse();
ix.
x. console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [ 5, 4, 3, 2, 1]
<body>
<custom-element>
</body>
For example, the below code other than code inside any function or
object is executed inside the global execution context.
var x = 10;
function A() {
console.log("Start function A");
function B() {
console.log("In function B");
}
B();
}
A();
console.log("GlobalContext");
433. What is function execution context?
Whenever a function is invoked, the JavaScript engine creates a
different type of Execution Context known as a Function Execution
Context (FEC) within the Global Execution Context (GEC) to evaluate
and execute the code within that function.
Let's say you want to show suggestions for a search query, but only
after a visitor has finished typing it. So here you write a debounce
function where the user keeps writing the characters with in 500ms
then previous timer cleared out using clearTimeout and reschedule API
call/DB query for a new time—300 ms in the future.
function debounce(func, timeout = 500) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, timeout);
};
}
function fetchResults() {
console.log("Fetching input suggestions");
}
const processChange = debounce(() => fetchResults());
Input:
Button:
window.addEventListener("scroll", processChange);
const adventurer = {
name: "Alice",
cat: {
name: "Dinah",
},
};
console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined
i. Array.isArray() method:
let a = 5;
let b = a;
b++;
console.log(a, b); //5, 6
Pass by reference doesn't create a new space in memory but the new
variable adopts a memory address of an initial variable. Non-primitives
such as objects, arrays and functions gets the reference of the initiable
variable. i.e, updating one value will impact the other variable.
let user1 = {
name: "John",
age: 27,
};
let user2 = user1;
user2.age = 30;
console.log(user1.age, user2.age); // 30, 30
In the above code snippet, updating the age property of one object will
impact the other property due to the same reference.
Primitives Non-primitives
The function which is going to bind using custom myOwnBind method act
as the attached function(boundTargetFunction) and argument as the
object for apply method call.
Function.prototype.myOwnBind = function (whoIsCallingMe) {
if (typeof this !== "function") {
throw new Error(this + "cannot be bound as it's not callable");
}
const boundTargetFunction = this;
return function () {
boundTargetFunction.apply(whoIsCallingMe, arguments);
};
};
Easy to read and Difficult to read and debug because they are
debug affected by extenal code
multiplyBy2(add(2, 3));
(function () {
// Private variables or functions goes here.
return {
// Return public variables or functions here.
};
})();
// Public
return {
name,
department,
getName: () => getEmployeeName(),
getDepartment: () => getDepartmentName(),
};
})();
console.log(createEmployee.name);
console.log(createEmployee.department);
console.log(createEmployee.getName());
console.log(createEmployee.getDepartment());
//example
const double = (x) => x * 2;
const square = (x) => x * x;
But you can fix this issue with an alternative IIFE (Immediately Invoked
Function Expression) to get access to the feature.
(async function () {
await Promise.resolve(console.log("Hello await")); // Hello await
})();
In ES2022, you can write top-level await without writing any hacks.
console.log(this);
function displayThis() {
console.log(this);
}
displayThis();
const person = {
name: 'John',
greet: function() {
console.log('Hello, ' + this.name);
}
};
person.greet();
In a method, this refers to the object that owns the method (person in
the case).
document.getElementById('myButton').addEventListener('click', function() {
console.log(this);
});
In an event handler, this refers to the element that triggered the event
(the button in this case).
Source: https://github.com/sudheerj/javascript-interview-questions