Javascript
Javascript
Star Notifications
💡 Nail JavaScript interviews with questions and solutions from ex-interviewers! Try GreatFrontEnd → 💡
🚀 Ace Javascript interview questions with solutions from FAANG+ companies! Try FrontendLead → 🚀
[Link] 1/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Table of Contents
No. Questions
24 What is memoization
25 What is Hoisting
37 What is a Cookie
[Link] 2/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
No. Questions
41 What are the differences between cookie, local storage and session storage
51 What is a promise
64 What is [Link]
75 What is eval
[Link] 3/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
No. Questions
79 What is isNaN
92 What are the tools or techniques used for debugging JavaScript code
[Link] 4/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
No. Questions
141 What is the way to find the number of parameters expected by a function
150 Can you write a random integers function to print integers within a range
[Link] 5/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
No. Questions
155 What are the string methods that accept Regular expression
168 How do you get the image width and height using JS
175 What are the ways to execute javascript after page load
177 Can you give an example of when you really need a semicolon
186 What happens if you do not use rest parameter as a last argument
[Link] 6/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
No. Questions
190 How do you determine two values same or not using object
197 What are the differences between freeze and seal methods
200 What is the main difference between [Link] and [Link] method
201 How can you get the list of keys of any object
215 What is the precedence order between local and global variables
222 What are the conventions to be followed for the usage of switch case
[Link] 7/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
No. Questions
228 What are the different error names from error object
233 How do you perform language specific date and time formatting
246 How do you find min and max values without Math functions
256 What happens if you write constructor more than once in a class
[Link] 8/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
No. Questions
274 What are the DOM methods available for constraint validation
285 How do you check whether an array includes a particular value or not
292 How do you invoke javascript code in an iframe from parent page
295 What are the different methods to find HTML elements in DOM
[Link] 9/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
No. Questions
326 What are the problems with postmessage target origin as wildcard
340 What are the list of cases error thrown from non-strict mode to strict mode
[Link] 10/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
No. Questions
347 How do you return all matching strings against a regular expression
349 What is the output of below console statement with unary operator
363 How do you map the array values without using map method
372 How do you display data in a tabular format using console object
[Link] 11/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
No. Questions
382 What are the different ways to deal with Asynchronous Code
402 What is the difference between Function constructor and function declaration
414 What are the differences between arguments object and rest parameter
415 What are the differences between spread operator and rest parameter
[Link] 12/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
No. Questions
418 What are the differences between for...of and for...in statements
441 How do you create your own bind method using either call or apply method?
442 What are the differences between pure and impure functions?
[Link] 13/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
No. Questions
456 How do you create polyfills for map, filter and reduce methods?
The object literal syntax (or object initializer), is a comma-separated set of name-value pairs wrapped in curly braces.
var object = {
name: "Sudheer",
age: 34
};
Object literal property values can be of any data type, including array, function, and nested object.
The simplest way to create an empty object is using the Object constructor. Currently this approach is not recommended.
The Object() is a built-in constructor function so "new" keyword is not required. The above code snippet can be re-written as:
The create method of Object is used to create a new object by passing the specified prototype object and properties as arguments,
i.e., this pattern is helpful to create new objects based on existing objects. The second argument is optional and it is used to create
properties on a newly created object.
The following code creates a new empty object whose prototype is null.
[Link] 14/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
The following example creates an object along with additional new properties.
let vehicle = {
wheels: '4',
fuelType: 'Gasoline',
color: 'Green'
}
let carProps = {
type: {
value: 'Volkswagen'
},
model: {
value: 'Golf'
}
}
In this approach, create any function and apply the new operator to create object instances.
function Person(name) {
[Link] = name;
[Link] = 21;
}
var object = new Person("Sudheer");
This is similar to function constructor but it uses prototype for their properties and methods,
function Person() {}
[Link] = "Sudheer";
var object = new Person();
This is equivalent to creating an instance with [Link] method with a function prototype and then calling that function with an
instance and parameters as arguments.
function func() {}
(OR)
// If the result is a non-null object then use it otherwise just use the new instance.
[Link](result && typeof result === 'object' ? result : newInstance);
The [Link] method is used to copy all the properties from one or more source objects and stores them into a target object.
The following code creates a new staff object by copying properties of his working company and the car he owns.
[Link] 15/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
class Person {
constructor(name) {
[Link] = name;
}
}
A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance. This way
one can ensure that they don't accidentally create multiple instances.
⬆ Back to Top
The prototype on object instance is available through [Link](object) or __proto__ property whereas prototype on
constructor function is available through [Link].
⬆ Back to Top
Call: The call() method invokes a function with a given this value and arguments provided one by one
[Link](employee1, "Hello", "How are you?"); // Hello John Rodson, How are you?
[Link](employee2, "Hello", "How are you?"); // Hello Jimmy Baily, How are you?
Apply: Invokes the function with a given this value and allows you to pass in arguments as an array
[Link] 16/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
function invite(greeting1, greeting2) {
[Link](
greeting1 + " " + [Link] + " " + [Link] + ", " + greeting2
);
}
[Link](employee1, ["Hello", "How are you?"]); // Hello John Rodson, How are you?
[Link](employee2, ["Hello", "How are you?"]); // Hello Jimmy Baily, How are you?
Bind: returns a new function, allowing you to pass any number of arguments
Call and Apply are pretty much interchangeable. Both execute the current function immediately. You need to decide whether it’s easier to
send in an array or a comma separated list of arguments. You can remember by treating Call is for comma (separated list) and Apply is for
Array.
Bind creates a new function that will have this set to the first parameter passed to bind().
⬆ Back to Top
[Link](text);
Stringification: Converting a native object to a string so that it can be transmitted across the network
[Link](object);
⬆ Back to Top
Note: Slice method doesn't mutate the original array but it returns the subset as a new array.
[Link] 17/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
let arrayIntegers1 = [Link](0, 2); // returns [1, 2]; original array: [3, 4, 5]
let arrayIntegers2 = [Link](3); // returns [4, 5]; original array: [1, 2, 3]
let arrayIntegers3 = [Link](3, 1, "a", "b", "c"); //returns [4]; original array: [1, 2, 3, "a", "b",
Note: Splice method modifies the original array and returns the deleted array.
⬆ Back to Top
Slice Splice
Returns the subset of original array Returns the deleted elements as array
Used to pick the elements from array Used to insert/delete elements to/from array
⬆ Back to Top
i. The keys of an Object can be Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any
primitive type.
ii. The keys in a Map are ordered while keys added to Object are not. Thus, when iterating over it, a Map object returns keys in the order
of insertion.
iii. You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.
iv. A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and
iterating over them.
v. An Object has a prototype, so there are default keys in an object that could collide with your keys if you're not careful. As of ES5 this
can be bypassed by creating an object(which can be called a map) using [Link](null) , but this practice is seldom done.
vi. A Map may perform better in scenarios involving frequent addition and removal of key pairs.
⬆ Back to Top
i. Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding
positions.
[Link] 18/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
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
NaN == NaN or NaN === NaN // false
[]==[] or []===[] //false, refer different objects in memory
{}=={} or {}==={} //false, refer different objects in memory
⬆ Back to Top
⬆ Back to Top
For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can
be assigned as a value to a variable. For example, in the below example, handler functions assigned to a listener
⬆ Back to Top
⬆ Back to Top
[Link] 19/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
A higher-order function is a function that accepts another function as an argument or returns a function as a return value or both. The
syntactic structure of higher order function will be as follows,
You can also call the function which you are passing to higher order function as callback function.
The higher order function is helpful to write the modular and reusable code.
⬆ Back to Top
const unaryFunction = (a) => [Link](a + 10); // Add 10 to the given argument and display the value
⬆ Back to Top
Let's take an example of n-ary function and how it turns into a currying function,
Curried functions are great to improve code reusability and functional composition.
⬆ Back to Top
Let's take an example to see the difference between pure and impure functions,
//Impure
let numberArray = [];
const impureAddNumber = (number) => [Link](number);
//Pure
const pureAddNumber = (number) => (argNumberArray) =>
[Link]([number]);
[Link] 20/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
As per the above code snippets, the Push function is impure itself by altering the array and returning a push number index independent of
the parameter value, whereas Concat on the other hand takes the array and concatenates it with the other array producing a whole new
array without side effects. Also, the return value is a concatenation of the previous array.
Remember that Pure functions are important as they simplify unit testing without any side effects and no need for dependency injection.
They also avoid tight coupling and make it harder to break your application by not having any side effects. These principles are coming
together with the Immutability concept of ES6: giving preference to const over let usage.
⬆ Back to Top
⬆ Back to Top
var let
It has been available from the beginning of JavaScript Introduced as part of ES6
Variable declaration will be hoisted, initialized as undefined Hoisted but not initialized
It is possible to re-declare the variable in the same scope It is not possible to re-declare the variable
function userDetails(username) {
if (username) {
[Link](salary); // undefined due to hoisting
[Link](age); // ReferenceError: Cannot access 'age' before initialization
let age = 30;
var salary = 10000;
}
[Link](salary); //10000 (accessible due to function scope)
[Link](age); //error: age is not defined(due to block scope)
}
userDetails("John");
⬆ Back to Top
⬆ Back to Top
[Link] 21/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
If you try to redeclare variables in a switch block then it will cause errors because there is only one block. For example, the below code
block throws a syntax error as below,
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() {
[Link](counter1); // undefined
[Link](counter2); // ReferenceError
var counter1 = 1;
let counter2 = 2;
}
⬆ Back to Top
(function () {
// logic here
})();
The primary reason to use an IIFE is to obtain data privacy because any variables declared within the IIFE cannot be accessed by the
outside world. i.e, If you try to access variables from the IIFE then it throws an error as below,
(function () {
var message = "IIFE";
[Link](message);
[Link] 22/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
})();
[Link](message); //Error: message is not defined
⬆ Back to Top
Note: If you want to encode characters such as / ? : @ & = + $ # then you need to use encodeURIComponent() .
⬆ Back to Top
⬆ Back to Top
var message;
[Link](message);
message = "The variable Has been hoisted";
[Link] 23/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
function message(name) {
[Link](name);
}
This hoisting makes functions to be safely used in code before they are declared.
⬆ Back to Top
[Link] = function () {
return [Link] + " bike has" + [Link] + " color";
};
class Bike {
constructor(color, model) {
[Link] = color;
[Link] = model;
}
getDetails() {
return [Link] + " bike has" + [Link] + " color";
}
}
⬆ Back to Top
function Welcome(name) {
var greetingInfo = function (message) {
[Link](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.
[Link] 24/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ 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
⬆ Back to Top
i. Local storage: It stores data for current origin with no expiration date.
ii. Session storage: It stores data for one session and the data is lost when the browser tab is closed.
[Link] 25/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
⬆ Back to Top
[Link] = "username=John";
⬆ 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 is deleted when the browser is closed but you can change this behavior by setting expiry date (in UTC time).
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
[Link] =
"username=; expires=Fri, 07 Jun 2019 00:00:00 UTC; path=/;";
Note: You should define the cookie path option to ensure that you delete the right cookie. Some browsers doesn't allow to delete a cookie
unless you specify a path parameter.
⬆ Back to Top
[Link] 26/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
41. What are the differences between cookie, local storage and session storage
Below are some of the differences between cookie, local storage and session storage,
Session
Feature Cookie Local storage
storage
Accessed on client or Both server-side & client-side. The set-cookie HTTP response client-side
client-side only
server side header is used by server inorder to send it to user. only
Not
SSL support Supported Not supported
supported
⬆ Back to Top
⬆ Back to Top
[Link]("logo", [Link]("logo").value);
[Link]("logo");
⬆ Back to Top
⬆ Back to Top
[Link] 27/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link] = functionRef;
Let's take the example usage of onstorage event handler which logs the storage key and it's values
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
i. Create a Web Worker File: You need to write a script to increment the count value. Let's name it as [Link]
let i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()", 500);
}
timedCount();
[Link] 28/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Here postMessage() method is used to post a message back to the HTML page
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("[Link]");
}
i. 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.
[Link]();
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
[Link] 29/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
function callbackFunction(name) {
[Link]("Hello " + name);
}
function outerFunction(callback) {
let name = prompt("Please enter your name.");
callback(name);
}
outerFunction(callbackFunction);
⬆ Back to Top
[Link] 30/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
function firstFunction() {
// Simulate a code delay
setTimeout(function () {
[Link]("First function called");
}, 1000);
}
function secondFunction() {
[Link]("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
[Link] 31/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
} else {
// No server-sent events supported
}
⬆ 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
⬆ Back to Top
[Link] 32/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
})
.then(function (result) {
[Link](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
Note: Remember that the order of the promises(output the result) is maintained as per input order.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
[Link] 33/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
The strict mode is declared by adding "use strict"; to the beginning of a script or a function. If declared at the beginning of a script, it has
global scope.
"use strict";
x = 3.14; // This will cause an error because x is not declared
function myFunction() {
"use strict";
y = 3.14; // This will cause an error
}
⬆ Back to Top
If you don't use this expression then it returns the original value.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
[Link] 34/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
user = undefined;
⬆ Back to Top
⬆ Back to Top
Null Undefined
It is an assignment value which indicates that variable points It is not an assignment value where a variable has been declared but
to no object. has not yet been assigned a value.
The null value is a primitive value that represents the null, The undefined value is a primitive value used when a variable has not
empty, or non-existent reference. been assigned a value.
Indicates the absence of a value for a variable Indicates absence of variable itself
Converted to zero (0) while performing primitive operations Converted to NaN while performing primitive operations
⬆ Back to Top
[Link](eval("1 + 2")); // 3
⬆ Back to Top
Window Document
It is the direct child of the window object. This is also known as Document
It is the root level element in any web page
Object Model (DOM)
It has methods like alert(), confirm() and properties like It provides methods like getElementById, getElementsByTagName,
document, location createElement etc
[Link] 35/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
function goBack() {
[Link]();
}
function goForward() {
[Link]();
}
⬆ Back to Top
Let's take an input element to detect the CapsLock on/off behavior with an example:
<p id="feedback"></p>
<script>
function enterInput(e) {
var flag = [Link]("CapsLock");
if (flag) {
[Link]("feedback").innerHTML = "CapsLock activated";
} else {
[Link]("feedback").innerHTML =
"CapsLock not activated";
}
}
</script>
⬆ Back to Top
isNaN("Hello"); //true
isNaN("100"); //false
⬆ Back to Top
80. What are the differences between undeclared and undefined variables
Below are the major differences between undeclared(not defined) and undefined variables,
undeclared undefined
If you try to read the value of an undeclared variable, then a If you try to read the value of an undefined variable, an
runtime error is encountered undefined value is returned.
[Link] 36/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
```javascript
This can be confusing, because it says „not defined“ instead of „not declared“ (Chrome)
⬆ Back to Top
⬆ Back to Top
[Link](-1);
parseInt("Hello");
⬆ Back to Top
isFinite(Infinity); // false
isFinite(NaN); // false
isFinite(-Infinity); // false
isFinite(100); // true
⬆ Back to Top
[Link] 37/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
<div>
<button class="child">Hello</button>
</div>
<script>
const parent = [Link]("div");
const child = [Link](".child");
[Link]("click",
function () {
[Link]("Parent");
}
);
[Link]("click", function () {
[Link]("Child");
});
</script>
// Child
// Parent
⬆ Back to Top
You need to pass true value for addEventListener method to trigger event handlers in event capturing phase.
<div>
<button class="child">Hello</button>
</div>
<script>
const parent = [Link]("div");
const child = [Link](".child");
[Link]("click",
function () {
[Link]("Parent");
},
true
);
[Link]("click", function () {
[Link]("Child");
});
</script>
// Parent
// Child
⬆ Back to Top
[Link] 38/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
function submit() {
[Link][0].submit();
}
⬆ Back to Top
[Link]([Link]);
⬆ Back to Top
90. What is the difference between document load and DOMContentLoaded events
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for
assets(stylesheets, images, and subframes) to finish loading. Whereas The load event is fired when the whole page has loaded, including all
dependent resources(stylesheets, images).
⬆ Back to Top
91. What is the difference between native, host and user objects
Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification. For example, String, Math,
RegExp, Object, Function etc core objects defined in the ECMAScript spec. Host objects are objects provided by the browser or runtime
environment (Node).
For example, window, XmlHttpRequest, DOM nodes etc are considered as host objects. User objects are objects defined in the javascript
code. For example, User objects created for profile information.
⬆ Back to Top
92. What are the tools or techniques used for debugging JavaScript code
You can use below tools or techniques for debugging javascript
i. Chrome Devtools
ii. debugger statement
iii. Good old [Link] 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
You can retrieve the attribute value as below, for example after typing "Good morning" into the input field:
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
[Link] 40/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
<!doctype html>
<html>
<head>
<script>
function greeting() {
alert('Hello! Good morning');
}
</script>
</head>
<body>
<button type="button" onclick="greeting()">Click me</button>
</body>
</html>
⬆ Back to Top
⬆ Back to Top
document
.getElementById("link")
.addEventListener("click", function (event) {
[Link]();
});
⬆ Back to Top
<script>
function firstFunc(event) {
alert("DIV 1");
[Link]();
}
[Link] 41/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
function secondFunc() {
alert("DIV 2");
}
</script>
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
setTimeout(function () {
[Link]("Good morning");
}, 2000);
⬆ Back to Top
setInterval(function () {
[Link]("Good morning");
}, 2000);
⬆ Back to Top
⬆ Back to Top
[Link] 42/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
For example, if you wanted to detect field changes inside a specific form, you can use event delegation technique,
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
[Link] 43/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link](userJSON); // {name: "John", age: 31}
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
For example, the below setTimeout method is used to display the message after 3 seconds. This timeout can be cleared by the
clearTimeout() method.
<script>
var msg;
function greeting() {
alert('Good morning');
}
function start() {
msg =setTimeout(greeting, 3000);
function stop() {
clearTimeout(msg);
}
</script>
⬆ Back to Top
For example, the below setInterval method is used to display the message for every 3 seconds. This interval can be cleared by the
clearInterval() method.
<script>
var msg;
function greeting() {
alert('Good morning');
}
function start() {
msg = setInterval(greeting, 3000);
function stop() {
clearInterval(msg);
}
</script>
[Link] 44/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
function redirect() {
[Link] = "[Link]";
}
⬆ Back to Top
i. Using includes: ES6 provided [Link] method to test a string contains a substring
ii. Using indexOf: In an ES5 or older environment, you can use [Link] which returns the index of a substring. If the
index value is not equal to -1 then it means the substring exists in the main string.
iii. Using RegEx: The advanced solution is using Regular expression's test method( [Link] ), which allows for testing for against
regular expressions
⬆ Back to Top
function validateEmail(email) {
var re =
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|((
return [Link](String(email).toLowerCase());
}
⬆ Back to Top
The above regular expression accepts unicode characters.
⬆ Back to Top
[Link] 45/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
⬆ Back to Top
i. Using in operator: You can use the in operator whether a key exists in an object or not
"key" in obj;
and If you want to check if a key doesn't exist, remember to use parenthesis,
!("key" in obj);
ii. Using hasOwnProperty method: You can use hasOwnProperty to particularly test for properties of the object instance (and not
inherited properties)
[Link]("key"); // true
iii. Using undefined comparison: If you access a non-existing property from an object, the result is undefined. Let’s compare the
properties against undefined to determine the existence of the property.
const user = {
name: "John",
};
⬆ Back to Top
[Link] 46/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
var object = {
k1: "value1",
k2: "value2",
k3: "value3",
};
⬆ Back to Top
i. Using Object entries(ECMA 7+): You can use object entries length along with constructor type.
[Link](obj).length === 0 && [Link] === Object; // Since date object length is 0, you need to check constru
ii. Using Object keys(ECMA 5+): You can use object keys length along with constructor type.
[Link](obj).length === 0 && [Link] === Object; // Since date object length is 0, you need to check constructo
iii. Using for-in with hasOwnProperty(Pre-ECMA 5): You can use a for-in loop along with hasOwnProperty.
function isEmpty(obj) {
for (var prop in obj) {
if ([Link](prop)) {
return false;
}
}
⬆ Back to Top
function sum() {
var total = 0;
for (var i = 0, len = [Link]; i < len; ++i) {
total += arguments[i];
}
return total;
}
Note: You can't apply array methods on arguments object. But you can convert into a regular array as below.
⬆ Back to Top
[Link] 47/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
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 [Link](0).toUpperCase() + [Link](1);
}
⬆ Back to Top
Pros
Cons
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
[Link] 48/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
If your browser(<IE9) doesn't support this method then you can use below polyfill.
if (![Link]) {
(function () {
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
[Link] = function () {
return [Link](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";
ii. Using square bracket notation: This solution is useful when the name of the property is dynamically determined or the key's name is
non-JS like "user-name"
obj["key3"] = "value3";
⬆ Back to Top
At first, the value decremented by one and then tested to see if it is equal to zero or not for determining the truthy/falsy value.
⬆ Back to Top
var a = b || c;
As per the above expression, variable 'a 'will get the value of 'c' only if 'b' is falsy (if is null, false, undefined, 0, empty string, or NaN),
otherwise 'a' will get the value of 'b'.
⬆ Back to Top
[Link] 49/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
var str =
"This is a \n\ very lengthy \n\ sentence!";
[Link](str);
But if you have a space after the '\n' character, there will be indentation inconsistencies.
⬆ Back to Top
⬆ Back to Top
fn = function (x) {
//Function code goes here
};
[Link] = "John";
⬆ Back to Top
141. What is the way to find the number of parameters expected by a function
You can use [Link] 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
[Link] 50/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
The continue statement is used to "jump over" one iteration in the loop. i.e, It breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
⬆ Back to Top
var i, 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 within a range
Yes, you can create a proper random function to return a random number between min and max (both included)
⬆ Back to Top
[Link] 52/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Tree shaking is a form of dead code elimination. It means that unused modules will not be included in the bundle during the build process
and for that it relies on the static structure of ES2015 module syntax,( i.e. import and export). Initially this has been popularized by the
ES2015 module bundler rollup .
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
/pattern/modifiers;
For example, the regular expression or search pattern with case-insensitive username would be,
/John/i;
⬆ Back to Top
155. What are the string methods that accept Regular expression
There are six string methods: search(), replace(), replaceAll(), match(), matchAll(), and split().
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() and replaceAll() methods are used to return a modified string where the pattern is replaced.
The match() and matchAll() methods are used to return the matches when matching a string against a regular expression.
The split() method is used to split a string into an array of substrings, and returns the new array.
[Link] 53/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
Modifier Description
⬆ Back to Top
i. Brackets: These are used to find a range of characters. For example, below are some use cases,
a. [abc]: Used to find any of the characters between the brackets(a,b,c)
b. [0-9]: Used to find any of the digits between the brackets
c. (a|b): Used to find any of the alternatives separated with |
ii. Metacharacters: These are characters with a special meaning. For example, below are some use cases,
a. \d: Used to find a digit
b. \s: Used to find a whitespace character
c. \b: Used to find a match at the beginning or ending of a word
iii. Quantifiers: These are useful to define quantities. For example, below are some use cases,
a. n+: Used to find matches for any string that contains at least one n
b. n*: Used to find matches for any string that contains zero or more occurrences of n
c. n?: Used to find matches for any string that contains zero or one occurrences of n
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
[Link] 54/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
i. Using style property: You can modify inline style using style property
[Link]("title").[Link] = "30px";
ii. Using ClassName property: It is easy to modify element class using className property
[Link]("title").className = "custom-title";
⬆ Back to Top
⬆ Back to Top
function getProfile() {
// code goes here
debugger;
// code goes here
}
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
[Link] 55/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link] = 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
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
[Link](0, 4)
)
)
mobileCheck = true;
})([Link] || [Link] || [Link]);
return mobileCheck;
};
⬆ Back to Top
function detectmob() {
if (
[Link](/Android/i) ||
[Link](/webOS/i) ||
[Link](/iPhone/i) ||
[Link](/iPad/i) ||
[Link](/iPod/i) ||
[Link](/BlackBerry/i) ||
[Link](/Windows Phone/i)
) {
return true;
} else {
return false;
}
}
⬆ Back to Top
168. How do you get the image width and height using JS
You can programmatically get the image and check the dimensions(width and height) using Javascript.
⬆ Back to Top
function httpGet(theUrl) {
var xmlHttpReq = new XMLHttpRequest();
[Link]("GET", theUrl, false); // false for synchronous request
[Link](null);
[Link] 56/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
return [Link];
}
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
var width =
[Link] ||
[Link] ||
[Link];
var height =
[Link] ||
[Link] ||
[Link];
⬆ Back to Top
⬆ Back to Top
[Link] 57/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
function traceValue(someParam) {
return condition1
? value1
: condition2
? value2
: condition3
? value3
: value4;
}
function traceValue(someParam) {
if (condition1) {
return value1;
} else if (condition2) {
return value2;
} else if (condition3) {
return value3;
} else {
return value4;
}
}
⬆ Back to Top
175. What are the ways to execute javascript after page load
You can execute javascript after page load in many different ways,
i. [Link]:
ii. [Link]:
<body onload="script();">
⬆ Back to Top
Access All the function constructors have prototype properties. All the objects have __proto__ property
Used to reduce memory wastage with a single copy of Used in lookup chain to resolve methods, constructors
Purpose
function etc.
⬆ Back to Top
[Link] 58/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
177. Can you give an example of when you really need a semicolon
It is recommended to use semicolons after every statement in JavaScript. For example, in the below case it throws an error ".. is not a
function" at runtime due to missing semicolon.
// define a function
var fn = (function () {
//...
})(
// semicolon missing at this line
var fn = (function () {
//...
})(function () {
//...
})();
In this case, we are passing the second function as an argument to the first function and then trying to call the result of the first function
call as a function. Hence, the second function will fail with a "... is not a function" error at runtime.
⬆ Back to Top
const obj = {
prop: 100,
};
[Link](obj);
[Link] = 200; // Throws an error in strict mode
[Link]([Link]); //100
Remember freezing is only applied to the top-level properties in objects but not for nested objects. For example, let's try to freeze user
object which has employment details as nested object and observe that details have been changed.
const user = {
name: "John",
employment: {
department: "IT",
},
};
[Link](user);
[Link] = "HR";
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
var language =
([Link] && [Link][0]) || // Chrome / Firefox
[Link] || // All browsers
[Link]; // IE <= 10
[Link](language);
⬆ Back to Top
function toTitleCase(str) {
return [Link](/\w\S*/g, function (txt) {
return [Link](0).toUpperCase() + [Link](1).toLowerCase();
});
}
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 the page. Please click Next Page</a>
</noscript>
⬆ Back to Top
i. Arithmetic Operators: Includes + (Addition), – (Subtraction), * (Multiplication), / (Division), % (Modulus), ++ (Increment) and – –
(Decrement)
ii. Comparison Operators: Includes == (Equal), != (Not Equal), === (Equal with type), > (Greater than), >= (Greater than or Equal to), <
(Less than), <= (Less than or Equal to)
iii. Logical Operators: Includes && (Logical AND), || (Logical OR), ! (Logical NOT)
[Link] 60/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
iv. Assignment Operators: Includes = (Assignment Operator), += (Add and Assignment Operator), –= (Subtract and Assignment
Operator), *= (Multiply and Assignment), /= (Divide and Assignment), %= (Modules and Assignment)
v. Ternary Operators: It includes conditional(: ?) Operator
vi. typeof Operator: It uses to find type of variable. The syntax looks like typeof variable
⬆ Back to Top
For example, let's take a sum example to calculate on dynamic number of parameters,
function sum(...args) {
let total = 0;
for (const i of args) {
total += i;
}
return total;
}
⬆ Back to Top
186. What happens if you do not use rest parameter as a last argument
The rest parameter should be the last argument, as its job is to collect all the remaining arguments into an array. For example, if you define
a function like below it doesn’t make any sense and will throw an error.
function someFunc(a,…b,c){
//You code goes here
return;
}
⬆ Back to Top
⬆ Back to Top
[Link] 61/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. Let's take an example to see
this behavior,
function calculateSum(x, y, z) {
return x + y + z;
}
[Link](calculateSum(...numbers)); // 6
⬆ Back to Top
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",
};
[Link](object);
[Link]([Link](object));
⬆ Back to Top
190. How do you determine two values same or not using object
The [Link]() method determines whether two values are the same value. For example, the usage with different types of values would be,
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
⬆ Back to Top
[Link] 62/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
You can use the [Link]() method which is used to copy the values and properties from one or more source objects to a target
object. It returns the target object which has properties and values copied from the source objects. The syntax would be as below,
[Link](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 };
[Link](target); // { a: 1, b: 3, c: 4 }
[Link](returnedTarget); // { a: 1, b: 3, c: 4 }
As observed in the above code, there is a common property( b ) from source to target so it's value has been overwritten.
⬆ Back to Top
⬆ Back to Top
A proxy is created with two parameters: a target object which you want to proxy and a handler object which contains methods to intercept
fundamental operations. The syntax would be as follows,
Let's take a look at below examples of proxy object and how the get method which customize the lookup behavior,
//Example1:
const person = {
name: 'Sudheer Jonna',
age: 35
};
const handler = {
get(target, prop) {
if (prop === 'name') {
return 'Mr. ' + target[prop];
}
return target[prop];
}
};
//Example2:
var handler1 = {
get: function (obj, prop) {
return prop in obj ? obj[prop] : 100;
},
[Link] 63/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
};
In the above code, it uses get handler which define the behavior of the proxy when an operation is performed on it. These proxies are
mainly used for some of the below cross-cutting concerns.
i. Logging
ii. Authentication or Authorization
iii. Data binding and observables
iv. Function parameter validation
⬆ Back to Top
const object = {
property: "Welcome JS world",
};
[Link](object);
[Link] = "Welcome to object world";
[Link]([Link](object)); // true
delete [Link]; // You cannot delete when sealed
[Link]([Link]); //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 [Link]() method then its properties become immutable and no changes can be made in them
whereas if an object is sealed using the [Link]() 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",
};
[Link] 64/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
const object = {
a: "Good morning",
b: 100,
};
⬆ Back to Top
200. What is the main difference between [Link] and [Link] method
The [Link]() method's behavior is similar to [Link]() 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 [Link]() 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 () {
[Link] 65/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link](`My name is ${[Link]}.`);
},
};
[Link] = "Nick"; // Remember that "name" is a property set on "admin" but not on "user" object
⬆ Back to Top
new WeakSet([iterable]);
⬆ Back to Top
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
i. add(value): A new object is appended with the given value to the weakset
ii. delete(value): Deletes the value from the WeakSet collection.
iii. has(value): It returns true if the value is present in the WeakSet Collection, otherwise it returns false.
⬆ Back to Top
[Link] 66/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. In this case, keys must be objects and the
values can be arbitrary values. The syntax looks like the following:
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
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(){})"
The uneval() function has been deprecated. It is recommended to use toString() for functions and [Link]() for other cases.
[Link] 67/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
function user() {}
[Link]([Link]()); // 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
[Link] 68/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
}
⬆ Back to Top
215. What is the precedence order between local and global variables
A local variable takes precedence over a global variable with the same name. Let's see this behavior in an example.
⬆ Back to Top
var user = {
firstName: "John",
lastName: "Abraham",
language: "en",
get lang() {
return [Link];
},
set lang(lang) {
[Link] = lang;
},
};
[Link]([Link]); // getter access lang as en
[Link] = "fr";
[Link]([Link]); // setter used to set lang as fr
⬆ Back to Top
[Link](newObject, "newProperty", {
value: 100,
writable: false,
[Link] 69/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
});
[Link]([Link]); // 100
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
// Define getters
[Link](obj, "increment", {
get: function () {
[Link]++;
return [Link];
},
});
[Link](obj, "decrement", {
get: function () {
[Link]--;
return [Link];
},
});
// Define setters
[Link](obj, "add", {
set: function (value) {
[Link] += value;
},
});
[Link](obj, "subtract", {
set: function (value) {
[Link] -= value;
},
});
[Link] = 10;
[Link] = 5;
[Link]([Link]); //6
[Link]([Link]); //5
⬆ Back to Top
[Link] 70/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
The above multi-way branch statement provides an easy way to dispatch execution to different parts of code based on the value of the
expression.
⬆ Back to Top
222. What are the conventions to be followed for the usage of switch case
Below are the list of conventions should be taken care,
⬆ Back to Top
i. string
ii. number
iii. boolean
iv. null
v. undefined
vi. bigint
vii. symbol
⬆ Back to Top
[Link];
ii. Square brackets notation: It uses square brackets for property access
[Link] 71/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
objectName["property"];
objectName[expression];
⬆ Back to Top
⬆ Back to Top
try {
greeting("Welcome");
} catch (err) {
[Link]([Link] + "<br>" + [Link]);
}
⬆ Back to Top
try {
eval("greeting('welcome)"); // Missing ' will produce an error
} catch (err) {
[Link]([Link]);
}
⬆ Back to Top
228. What are the different error names from error object
There are 7 different types of error names returned from error object,
[Link] 72/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
233. How do you perform language specific date and time formatting
You can use the [Link] 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
[Link] 73/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Iterable: It is an object which can be iterated over via a method whose key is [Link].
Iterator: It is an object returned by invoking [[Link]]() on an iterable. This iterator object wraps each iterated element in an
object and returns it via next() method one by one.
IteratorResult: It is an object returned by next() method. The object contains two properties; the value property contains an iterated
element and the done property determines whether the element is the last element or not.
⬆ Back to Top
Note: The event loop allows [Link] to perform non-blocking I/O operations, even though JavaScript is single-threaded, by offloading
operations to the system kernel whenever possible. Since most modern kernels are multi-threaded, they can handle multiple operations
executing in the background.
⬆ Back to Top
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.
[Link] 74/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
Whenever the call stack receives an async function, it is moved into the Web API. Based on the function, Web API executes it and awaits the
result. Once it is finished, it moves the callback into the event queue (the callback of the promise is moved into the microtask queue).
The event loop constantly checks whether or not the call stack is empty. Once the call stack is empty and there is a callback in the event
queue, the event loop moves the callback into the call stack. But if there is a callback in the microtask queue as well, it is moved first. The
microtask queue has a higher priority than the event queue.
⬆ Back to Top
function admin(isAdmin) {
return function(target) {
[Link] = isAdmin;
}
}
@admin(true)
class User() {
}
[Link]([Link]); //true
@admin(false)
class User() {
}
[Link]([Link]); //false
⬆ Back to Top
i. Collator: These are the objects that enable language-sensitive string comparison.
ii. DateTimeFormat: These are the objects that enable language-sensitive date and time formatting.
iii. ListFormat: These are the objects that enable language-sensitive list formatting.
iv. NumberFormat: Objects that enable language-sensitive number formatting.
v. PluralRules: Objects that enable plural-sensitive formatting and language-specific rules for plurals.
vi. RelativeTimeFormat: Objects that enable language-sensitive relative time formatting.
⬆ Back to Top
[Link] 75/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
var x = "100";
var y = +x;
[Link](typeof x, typeof y); // string, number
var a = "Hello";
var b = +a;
[Link](typeof a, typeof b, b); // string, number, NaN
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
[Link] 76/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link](findMin(marks));
[Link](findMax(marks));
⬆ Back to Top
246. How do you find min and max values without Math functions
You can write functions which loop through an array comparing each value with the lowest value or highest value to find the min and max
values. Let's create those functions to find min and max values,
function findMax(arr) {
var length = [Link];
var max = -Infinity;
while (length--) {
if (arr[length] > max) {
max = arr[length];
}
}
return max;
}
[Link](findMin(marks));
[Link](findMax(marks));
⬆ Back to Top
// Initialize an array a
for (let i = 0; i < [Link]; a[i++] = 0);
⬆ Back to Top
⬆ Back to Top
[Link] 77/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
The comma operator is used to evaluate each of its operands from left to right and returns the value of the last operand. This is totally
different from comma usage within arrays, objects, and function arguments and parameters. For example, the usage for numeric
expressions would be as below,
var x = 1;
x = (x++, x);
[Link](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
[Link](greeting(user));
⬆ Back to Top
[Link] 78/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Optional parameters Functions support optional parameters No support of optional parameters for functions
⬆ Back to Top
i. TypeScript is able to find compile time errors at the development time only and it makes sures less runtime errors. Whereas javascript
is an interpreted language.
ii. TypeScript is strongly-typed or supports static typing which allows for checking type correctness at compile time. This is not available
in javascript.
iii. TypeScript compiler can compile the .ts files into ES3,ES4 and ES5 unlike ES6 features of javascript which may not be supported in
some browsers.
⬆ Back to Top
[Link](initObject.a); // John
⬆ Back to Top
class Employee {
constructor() {
[Link] = "John";
}
}
[Link]([Link]); // John
⬆ Back to Top
256. What happens if you write constructor more than once in a class
The "constructor" in a class is a special method and it should be defined only once in a class. i.e, If you write a constructor method more
than once in a class it will throw a SyntaxError error.
class Employee {
constructor() {
[Link] = "John";
}
constructor() { // Uncaught SyntaxError: A class may only have one constructor
[Link] = 30;
}
}
[Link] 79/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link]([Link]);
⬆ Back to Top
get area() {
return [Link] * [Link];
}
set area(value) {
[Link] = value;
}
}
⬆ Back to Top
⬆ Back to Top
// ES5
[Link]("James"); // TypeError: "James" is not an object
// ES2015
[Link]("James"); // [Link]
⬆ Back to Top
[Link]([Link], [Link]);
[Link]({}, null);
⬆ Back to Top
[Link] 80/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
The [Link]() method is used to determine if an object is extendable or not. i.e, Whether it can have new properties added
to it or not.
Note: By default, all the objects are extendable. i.e, The new properties can be added or modified.
⬆ Back to Top
try {
[Link](newObject, "newProperty", {
// Adding new property
value: 100,
});
} catch (e) {
[Link](e); // TypeError: Cannot define property newProperty, object is not extensible
}
⬆ Back to Top
i. [Link]
ii. [Link]
iii. [Link]
⬆ Back to Top
[Link](newObject, {
newProperty1: {
value: "John",
writable: true,
},
newProperty2: {},
});
[Link] 81/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
⬆ Back to Top
function greeting() {
[Link]("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 = [Link](new RegExp("\\b" + e(c) + "\\b", "g"), k[c]);
}
}
return p;
})(
"2 1(){0.3('4, 7 6 5 8')}",
9,
9,
"console|greeting|function|log|Hello|JS|to|welcome|world".split("|"),
0,
{}
)
);
⬆ Back to Top
i. The Code size will be reduced. So data transfers between server and client will be fast.
ii. It hides the business logic from outside world and protects the code from others
iii. Reverse engineering is highly difficult
iv. The download time will be reduced
[Link] 82/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
Changing the form of any data in any other Changing the form of information to an unreadable format by
Definition
form using a key
Target data
It will be converted to a complex form Converted into an unreadable format
format
⬆ Back to Top
⬆ Back to Top
function validateForm() {
var x = [Link]["myForm"]["uname"].value;
if (x == "") {
alert("The username shouldn't be empty");
return false;
[Link] 83/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
}
}
⬆ Back to Top
<form method="post">
<input type="text" name="uname" required />
<input type="submit" value="Submit" />
</form>
Note: Automatic form validation does not work in Internet Explorer 9 or earlier.
⬆ Back to Top
274. What are the DOM methods available for constraint validation
The below DOM methods are available for constraint validation on an invalid input,
function myFunction() {
var userName = [Link]("uname");
if (![Link]()) {
[Link]("message").innerHTML =
[Link];
} else {
[Link]("message").innerHTML =
"Entered a valid username";
}
}
⬆ Back to Top
i. validity: It provides a list of boolean properties related to the validity of an input element.
ii. validationMessage: It displays the message when the validity is false.
iii. willValidate: It indicates if an input element will be validated or not.
⬆ Back to Top
[Link] 84/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
function myOverflowFunction() {
if ([Link]("age").[Link]) {
alert("The mentioned age is not allowed");
}
}
⬆ Back to Top
⬆ Back to Top
enum Color {
RED, GREEN, BLUE
}
⬆ Back to Top
const newObject = {
a: 1,
b: 2,
c: 3,
};
[Link]([Link](newObject));
["a", "b", "c"];
⬆ Back to Top
const newObject = {
a: 1,
[Link] 85/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
b: 2,
c: 3,
};
const descriptorsObject = [Link](newObject);
[Link]([Link]); //true
[Link]([Link]); //true
[Link]([Link]); //true
[Link]([Link]); // 1
⬆ Back to Top
⬆ Back to Top
get area() {
return [Link] * [Link];
}
set area(value) {
[Link] = value;
}
}
⬆ Back to Top
⬆ Back to Top
285. How do you check whether an array includes a particular value or not
[Link] 86/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
The Array#includes() method is used to determine whether an array includes a particular value among its entries by returning either true
or false. Let's see an example to find an element(numeric and string) within an array.
⬆ Back to Top
If you would like to compare arrays irrespective of order then you should sort them before,
⬆ Back to Top
⬆ Back to Top
function convertToThousandFormat(x) {
return [Link](); // 12,345.679
}
[Link](convertToThousandFormat(12345.6789));
⬆ Back to Top
[Link] 87/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Both are totally unrelated programming languages and no relation between them. Java is statically typed, compiled, runs on its own VM.
Whereas Javascript is dynamically typed, interpreted, and runs in a browser and nodejs environments. Let's see the major differences in a
tabular format,
Memory Uses more memory Uses less memory. Hence it will be used for web pages
⬆ Back to Top
function func1() {
[Link]("This is a first definition");
}
function func1() {
[Link]("This is a second definition");
}
func1(); // This is a second definition
It always calls the second function definition. In this case, namespace will solve the name collision problem.
⬆ Back to Top
i. Using Object Literal Notation: Let's wrap variables and functions inside an Object literal which acts as a namespace. After that you can
access them using object notation
var namespaceOne = {
function func1() {
[Link]("This is a first definition");
}
}
var namespaceTwo = {
function func1() {
[Link]("This is a second definition");
}
}
namespaceOne.func1(); // This is a first definition
namespaceTwo.func1(); // This is a second definition
ii. Using IIFE (Immediately invoked function expression): The outer pair of parentheses of IIFE creates a local scope for all the code
inside of it and makes the anonymous function a function expression. Due to that, you can create the same function in two different
function expressions to act as a namespace.
(function () {
function fun1() {
[Link]("This is a first definition");
}
fun1();
})();
(function () {
[Link] 88/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
function fun1() {
[Link]("This is a second definition");
}
fun1();
})();
iii. Using a block and a let/const declaration: In ECMAScript 6, you can simply use a block and a let declaration to restrict the scope of a
variable to a block.
{
let myFunction = function fun1() {
[Link]("This is a first definition");
};
myFunction();
}
//myFunction(): ReferenceError: myFunction is not defined.
{
let myFunction = function fun1() {
[Link]("This is a second definition");
};
myFunction();
}
//myFunction(): ReferenceError: myFunction is not defined.
⬆ Back to Top
292. How do you invoke javascript code in an iframe from parent page
Initially iFrame needs to be accessed using either [Link] or [Link] . After that contentWindow property of iFrame
gives the access for targetFunction
[Link]("targetFrame").[Link]();
[Link][0].[Link](); // Accessing iframe this way may not work in latest versions
⬆ Back to Top
⬆ Back to Top
[Link] 89/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
}
if (typeof fileReference != "undefined")
[Link]("head")[0].appendChild(fileReference);
}
⬆ Back to Top
295. What are the different methods to find HTML elements in DOM
If you want to access any element in an HTML page, you need to start with accessing the document object. Later you can use any of the
below methods to find the HTML element,
⬆ Back to Top
$(document).ready(function () {
// It selects the document and apply the function on page load
alert("Welcome to jQuery world");
});
Note: You can download it from jquery's official site or install it from CDNs, like google.
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
void expression;
void expression;
[Link] 90/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Note: This operator is often used to obtain the undefined primitive value, using "void(0)".
⬆ Back to Top
function myFunction() {
[Link] = "wait";
}
<body onload="myFunction()"></body>
⬆ Back to Top
for (;;) {}
while (true) {}
⬆ Back to Top
[Link] = "welcome";
[Link] = 32;
with (a.b.c) {
greeting = "welcome";
age = 32;
}
But this with statement creates performance problems since one cannot predict whether an argument will refer to a real variable or to a
property inside the with argument.
⬆ Back to Top
[Link] 91/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Explanation: Due to the event queue/loop of javascript, the setTimeout callback function is called after the loop has been executed. Since
the variable i is declared with the var keyword it became a global variable and the value was equal to 4 using iteration when the time
setTimeout function is invoked. Hence, the output of the second loop is 4 4 4 4 .
Whereas in the second loop, the variable i is declared as the let keyword it becomes a block scoped variable and it holds a new value(0, 1
,2 3) for each iteration. Hence, the output of the first loop is 0 1 2 3 .
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
Explanation: The variable declaration with var keyword refers to a function scope and the variable is treated as if it were declared at the
top of the enclosing scope due to hoisting feature. So all the multiple declarations contributing to the same hoisted variable without any
error. Let's take an example of re-declaring variables in the same scope for both var and let/const variables.
[Link] 92/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
myFunc();
alert(name); // John
myFunc();
alert(name);
⬆ Back to Top
No, the const variable doesn't make the value immutable. But it disallows subsequent assignments(i.e, You can declare with assignment
but can't assign another value later)
⬆ 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;
};
[Link](calculateArea()); //300
⬆ Back to Top
[Link] 93/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
var greeting = 'Welcome to JS World, Mr. ' + firstName + ' ' + lastName.`
Note: You can use multi-line strings and string interpolation features with template literals.
⬆ Back to Top
Whereas in ES6, You don't need to mention any newline sequence character,
⬆ Back to Top
You can write the above use case without nesting template features as well. However, the nesting template feature is more compact and
readable.
⬆ Back to Top
[Link] 94/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
var str2 = strings[2]; // "in"
var expertiseStr;
if (experienceExp > 10) {
expertiseStr = "expert developer";
} else if (skillExp > 5 && skillExp <= 10) {
expertiseStr = "senior developer";
} else {
expertiseStr = "junior developer";
}
return `${str0}${userExp}${str1}${expertiseStr}${str2}${skillExp}`;
}
⬆ Back to Top
If you don't use raw strings, the newline character sequence will be processed by displaying the output in multiple lines
Also, the raw property is available on the first argument to the tag function
function tag(strings) {
[Link]([Link][0]);
}
⬆ Back to Top
[Link](one); // "JAN"
[Link](two); // "FEB"
[Link](three); // "MARCH"
and you can get user properties of an object using destructuring assignment,
[Link] 95/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link](name); // John
[Link](age); // 32
⬆ Back to Top
Arrays destructuring:
var x, y, z;
[x = 2, y = 4, z = 6] = [10];
[Link](x); // 10
[Link](y); // 4
[Link](z); // 6
Objects destructuring:
var { x = 2, y = 4, z = 6 } = { x: 10 };
[Link](x); // 10
[Link](y); // 4
[Link](z); // 6
⬆ Back to Top
var x = 10,
y = 20;
⬆ Back to Top
//ES6
var x = 10,
y = 20;
obj = { x, y };
[Link](obj); // {x: 10, y:20}
//ES5
var x = 10,
y = 20;
obj = { x: x, y: y };
[Link](obj); // {x: 10, y:20}
⬆ Back to Top
[Link] 96/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
The dynamic imports using import() function syntax allows us to load modules on demand by using promises or the async/await syntax.
Currently this feature is in stage4 proposal. The main advantage of dynamic imports is reduction of our bundle's sizes, the size/payload
response of our requests and overall improvements in the user experience. The syntax of dynamic imports would be as below,
⬆ Back to Top
i. Import a module on-demand or conditionally. For example, if you want to load a polyfill on legacy browser
if (isLegacyBrowser()) {
import(···)
.then(···);
}
ii. Compute the module specifier at runtime. For example, you can use it for internationalization.
import(`messages_${getLocale()}.js`).then(···);
⬆ Back to Top
For example, you can create an array of 8-bit signed integers as below
⬆ Back to Top
i. Dynamic loading
ii. State isolation
[Link] 97/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
iii. Global namespace isolation
iv. Compilation hooks
v. Nested virtualization
⬆ Back to Top
i. Comparison:
var list = ["ä", "a", "z"]; // In German, "ä" sorts with "a" Whereas in Swedish, "ä" sorts after "z"
var l10nDE = new [Link]("de");
var l10nSV = new [Link]("sv");
[Link]([Link]("ä", "z") === -1); // true
[Link]([Link]("ä", "z") === +1); // true
ii. Sorting:
var list = ["ä", "a", "z"]; // In German, "ä" sorts with "a" Whereas in Swedish, "ä" sorts after "z"
var l10nDE = new [Link]("de");
var l10nSV = new [Link]("sv");
[Link]([Link]([Link])); // [ "a", "ä", "z" ]
[Link]([Link]([Link])); // [ "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
326. What are the problems with postmessage target origin as wildcard
[Link] 98/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
The second argument of postMessage method specifies which origin is allowed to receive the message. If you use the wildcard “*” as an
argument then any origin is allowed to receive the message. In this case, there is no way for the sender window to know if the target
window is at the target origin when sending the message. If the target window has been navigated to another origin, the other origin
would receive the data. Hence, this may lead to XSS vulnerabilities.
[Link](message, "*");
⬆ Back to Top
For example, let's check the sender's origin [Link] on receiver side [Link],
//Listener on [Link]
[Link]("message", function(message){
if(/^[Link]
[Link]('You received the data from valid sender', [Link]);
}
});
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
[Link] 99/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
You can apply the checked property on the selected checkbox in the DOM. If the value is true it means the checkbox is checked,
otherwise it is unchecked. For example, the below HTML checkbox element can be access using javascript as below:
⬆ Back to Top
⬆ Back to Top
"ABC".charCodeAt(0); // returns 65
⬆ Back to Top
⬆ Back to Top
[Link]("Welcome to JS world"[0]);
The output of the above expression is "W". Explanation: The bracket notation with specific index on a string returns the character at a
specific location. Hence, it returns the character "W" of the string. Since this is not supported in IE7 and below versions, you may need to
use the .charAt() method to get the desired result.
⬆ Back to Top
[Link] 100/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
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) {
[Link]([Link] + ": " + [Link]);
}
⬆ Back to Top
try {
throw new EvalError('Eval function error', '[Link]', 100);
} catch (e) {
[Link]([Link], [Link], [Link]); // "Eval function error", "EvalError", "[Link]"
⬆ Back to Top
340. What are the list of cases error thrown from non-strict mode to strict mode
When you apply 'use strict'; syntax, some of the below cases will throw a SyntaxError before executing the script
var n = 022;
if (someCondition) {
function f() {}
}
f(); // ReferenceError: f is not defined
Hence, the errors from above cases are helpful to avoid errors in development/production environments.
⬆ Back to Top
⬆ Back to Top
[Link] 101/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Parameter is the variable name of a function definition whereas an argument represents the value given to a function when it is invoked.
Let's explain this with a simple function
⬆ Back to Top
⬆ Back to Top
Let's take an example of array's concatenation with veggies and fruits arrays,
⬆ Back to Top
Shallow Copy: Shallow copy is a bitwise copy of an object. A new object is created that has an exact copy of the values in the original
object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory
address is copied.
Example
var empDetails = {
name: "John",
age: 25,
expertise: "Software Developer",
};
to create a duplicate
[Link] 102/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
if we change some property value in the duplicate one like this:
[Link] = "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: [Link],
age: [Link],
expertise: [Link],
};
Now if you change [Link] , it will only affect empDetailsDeepCopy & not empDetails
⬆ Back to Top
"Hello".repeat(4); // 'HelloHelloHelloHello'
347. How do you return all matching strings against a regular expression
The matchAll() method can be used to return an iterator of all results matching a string against a regular expression. For example, the
below example returns an array of matching string results against a regular expression,
[Link](greetingList[0][0]); //Hello1
[Link](greetingList[1][0]); //Hello2
[Link](greetingList[2][0]); //Hello3
⬆ Back to Top
[Link] 103/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link](greeting); // " Hello, Goodmorning! "
[Link]([Link]()); // "Hello, Goodmorning! "
[Link]([Link]()); // "Hello, Goodmorning! "
⬆ 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,
[Link](+"Hello"); // NaN
The output of the above console log statement returns NaN. Because the element is prefixed by the unary operator and the JavaScript
interpreter will try to convert that element into a number type. Since the conversion fails, the value of the statement results in NaN value.
⬆ Back to Top
But sometimes we require to extend more than one, to overcome this we can use Mixin which helps to copy methods to the prototype of
another class.
Say for instance, we've two classes User and CleanRoom . Suppose we need to add CleanRoom functionality to User , so that user can
clean the room at demand. Here's where concept called mixins comes into picture.
// mixin
let cleanRoomMixin = {
cleanRoom() {
alert(`Hello ${[Link]}, your room is clean now`);
},
sayBye() {
alert(`Bye ${[Link]}`);
},
};
// usage:
class User {
constructor(name) {
[Link] = name;
}
}
⬆ Back to Top
[Link] 104/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
thunk(); // 5
⬆ Back to Top
function fetchData(fn) {
fetch("[Link]
.then((response) => [Link]())
.then((json) => fn(json));
}
asyncThunk();
The getData function won't be called immediately but it will be invoked only when the data is available from API endpoint. The
setTimeout function is also used to make our code asynchronous. The best real time example is redux state management library which
uses the asynchronous thunks to delay the actions to dispatch.
⬆ Back to Top
const circle = {
radius: 20,
diameter() {
return [Link] * 2;
},
perimeter: () => 2 * [Link] * [Link],
};
[Link]([Link]());
[Link]([Link]());
Output:
The output is 40 and NaN. Remember that diameter is a regular function, whereas the value of perimeter is an arrow function. The this
keyword of a regular function(i.e, diameter) refers to the surrounding scope which is a class(i.e, Shape object). Whereas this keyword of
perimeter function refers to the surrounding scope which is a window object. Since there is no radius property on window objects it returns
an undefined value and the multiple of number value returns NaN value.
⬆ Back to Top
In the above expression, g and m are for global and multiline flags.
[Link] 105/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
⬆ Back to Top
[Link](![]); // false
⬆ Back to Top
⬆ Back to Top
[Link](+null); // 0
[Link](+undefined); // NaN
[Link](+false); // 0
[Link](+NaN); // NaN
[Link](+""); // 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
[Link] 106/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
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
[Link] 107/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ 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 [Link] as below
⬆ Back to Top
[Link](
"%c The text has blue color, with large font and red background",
[Link] 108/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
"color: blue; font-size: x-large; background: red"
);
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
372. How do you display data in a tabular format using console object
The [Link]() is used to display data in the console in a tabular format to visualize complex arrays or objects.
[Link] 109/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
const users = [
{ name: "John", id: 1, city: "Delhi" },
{ name: "Max", id: 2, city: "London" },
{ name: "Rod", id: 3, city: "Paris" },
];
[Link](users);
⬆ Back to Top
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
⬆ Back to Top
[Link]("#copy-button").onclick = function () {
// Select the content
[Link]("#copy-input").select();
// Copy to the clipboard
[Link]("copy");
};
⬆ Back to Top
[Link](+new Date());
[Link]([Link]());
⬆ Back to Top
[Link] 110/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
const biDimensionalArr = [11, [22, 33], [44, 55], [66, 77], 88, 99];
const flattenArr = [].concat(...biDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
But you can make it work with multi-dimensional arrays by recursive calls,
function flattenMultiArray(arr) {
const flattened = [].concat(...arr);
return [Link]((item) => [Link](item))
? flattenMultiArray(flattened)
: flattened;
}
const multiDimensionalArr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];
const flatArr = flattenMultiArray(multiDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
⬆ Back to Top
// Verbose approach
if (
input === "first" ||
input === 1 ||
input === "second" ||
input === 2
) {
someFunction();
}
// Shortcut
if (["first", 1, "second", 2].indexOf(input) !== -1) {
someFunction();
}
⬆ Back to Top
[Link]('beforeunload', () => {
[Link]('Clicked browser back button');
});
You can also use popstate event to detect the browser back button. Note: The history entry has been activated using [Link]
method.
[Link]('popstate', () => {
[Link]('Clicked browser back button');
[Link] = 'white';
});
[Link] 111/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link]('click', () => {
[Link] = 'blue';
[Link]({}, 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.
⬆ 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
382. What are the different ways to deal with Asynchronous Code
Below are the list of different ways to deal with Asynchronous code.
i. Callbacks
ii. Promises
iii. Async/await
iv. Third-party libraries such as [Link],bluebird etc
⬆ Back to Top
[Link] 112/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
iii. Call the AbortController's abort property to cancel all fetches that use that signal For example, passing the same signal to multiple
fetch calls will cancel all requests with that signal,
fetch("[Link] { signal })
.then((response) => {
[Link](`Request 1 is complete!`);
})
.catch((e) => {
if ([Link] === "AbortError") {
// We know it's been canceled!
}
});
fetch("[Link] { signal })
.then((response) => {
[Link](`Request 2 is complete!`);
})
.catch((e) => {
if ([Link] === "AbortError") {
// We know it's been canceled!
}
});
⬆ Back to Top
i. SpeechRecognition (Asynchronous Speech Recognition or Speech-to-Text): It provides the ability to recognize voice context from an
audio input and respond accordingly. This is accessed by the SpeechRecognition interface. The example below shows how to use this
API to get text from speech,
[Link] =
[Link] || [Link]; // webkitSpeechRecognition for Chrome and SpeechRecognition f
const recognition = new [Link]();
[Link] = (event) => {
// SpeechRecognitionEvent type
const speechToText = [Link][0][0].transcript;
[Link](speechToText);
};
[Link]();
In this API, browser is going to ask you for permission to use your microphone
ii. SpeechSynthesis (Text-to-Speech): It provides the ability to recognize voice context from an audio input and respond. This is accessed
by the SpeechSynthesis interface. For example, the below code is used to get voice/speech from text,
if ("speechSynthesis" in window) {
var speech = new SpeechSynthesisUtterance("Hello World!");
[Link] = "en-US";
[Link](speech);
}
The above examples can be tested on chrome(33+) browser's developer console. Note: This API is still a working draft and only available in
Chrome and Firefox browsers(ofcourse Chrome only implemented the specification)
⬆ Back to Top
[Link] 113/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Both browser and NodeJS javascript environments throttles with a minimum delay that is greater than 0ms. That means even though
setting a delay of 0ms will not happen instantaneously. Browsers: They have a minimum delay of 4ms. This throttle occurs when successive
calls are triggered due to callback nesting(certain depth) or after a certain number of successive intervals. Note: The older browsers have a
minimum delay of 10ms. Nodejs: They have a minimum delay of 1ms. This throttle happens when the delay is larger than 2147483647 or
less than 1. The best example to explain this timeout throttling behavior is the order of below code snippet.
function runMeFirst() {
[Link]("My script is initialized");
}
setTimeout(runMeFirst, 0);
[Link]("Script loaded");
Script loaded
My script is initialized
function runMeFirst() {
[Link]("My script is initialized");
}
runMeFirst();
[Link]("Script loaded");
My script is initialized
Script loaded
⬆ Back to Top
⬆ Back to Top
i. When a new javascript program is executed directly from console or running by the <script> element, the task will be added to the
task queue.
ii. When an event fires, the event callback added to task queue
iii. When a setTimeout or setInterval is reached, the corresponding callback added to task queue
⬆ Back to Top
Note: All of these microtasks are processed in the same turn of the event loop.
⬆ Back to Top
[Link] 114/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Browser Event Loop: The Browser Event Loop is used in client-side JavaScript applications and is responsible for handling events that occur
within the browser environment, such as user interactions (clicks, keypresses, etc.), HTTP requests, and other asynchronous actions.
The [Link] Event Loop is used in server-side JavaScript applications and is responsible for handling events that occur within the [Link]
runtime environment, such as file I/O, network I/O, and other asynchronous actions.
⬆ Back to Top
Example:
[Link]("Start"); //1
queueMicrotask(() => {
[Link]("Inside microtask"); // 3
});
[Link]("End"); //2
By using queueMicrotask, you can ensure that certain tasks or callbacks are executed at the earliest opportunity during the JavaScript
event loop, making it useful for performing work that needs to be done asynchronously but with higher priority than regular setTimeout
or setInterval callbacks.
⬆ Back to Top
In the runtime, typescript will provide the type to the customLibrary variable as any type. The another alternative without using declare
keyword is below
⬆ Back to Top
Promises Observables
[Link] 115/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Promises Observables
Eager in nature; they are going to be called immediately Lazy in nature; they require subscription to be invoked
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
[Link] 116/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Microtask Queue is the new queue where all the tasks initiated by promise objects get processed before the callback queue. The
microtasks queue are processed before the next rendering and painting jobs. But if these microtasks are running for a long time then it
leads to visual degradation.
⬆ Back to Top
⬆ Back to Top
isPrimitive(myPrimitive);
isPrimitive(myNonPrimitive);
If the value is a primitive data type, the Object constructor creates a new wrapper object for the value. But If the value is a non-primitive
data type (an object), the Object constructor will give the same object.
⬆ Back to Top
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
[Link] 117/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
402. What is the difference between Function constructor and function declaration
The functions which are created with Function constructor do not create closures to their creation contexts but they are always created in
the global scope. i.e, the function can access its own local variables and global scope variables only. Whereas function declarations can
access outer function variables(closures) too.
Function Constructor:
var a = 100;
function createFunction() {
var a = 200;
return new Function("return a;");
}
[Link](createFunction()()); // 100
Function declaration:
var a = 100;
function createFunction() {
var a = 200;
return function func() {
return a;
};
}
[Link](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
[Link] = 2;
[Link]([Link]); // 2
[Link](array); // [1,2]
[Link] 118/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link]([Link]); // 0
[Link](array); // []
⬆ Back to Top
Note: Observables are not part of the JavaScript language yet but they are being proposed to be added to the language
⬆ Back to Top
Classes:
class User {}
Constructor Function:
function User() {}
⬆ Back to Top
[Link] 119/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
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.
⬆ Back to Top
Let's say you expect to print an error to the console for all the below cases,
[Link]("promised value").then(function () {
throw new Error("error");
});
[Link]("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
[Link]("promised value")
.then(function () {
throw new Error("error");
})
.catch(function (error) {
[Link]([Link]);
});
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
[Link]("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);
});
[Link] 120/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
In future, if the processing library API changed to synchronous then you can remove done block as below,
getDataFromHttp().then(function (result) {
return displayData(processDataAsync(result));
});
and then you forgot to add done block to then block leads to silent errors.
iii. Extend ES6 Promises by Bluebird: Bluebird extends the ES6 Promises API to avoid the issue in the second solution. This library has a
“default” onRejection handler which will print all errors from rejected Promises to stderr. After installation, you can process unhandled
rejections
[Link](function (error) {
throw error;
});
⬆ Back to Top
⬆ Back to Top
const collection = {
one: 1,
two: 2,
three: 3,
[[Link]]() {
const values = [Link](this);
let i = 0;
return {
next: () => {
return {
value: this[values[i++]],
done: i > [Link],
};
},
};
},
};
[Link] 121/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link]([Link]()); // → {value: 3, done: false}
[Link]([Link]()); // → {value: undefined, done: true}
const collection = {
one: 1,
two: 2,
three: 3,
[[Link]]: function* () {
for (let key in this) {
yield this[key];
}
},
};
const iterator = collection[[Link]]();
[Link]([Link]()); // {value: 1, done: false}
[Link]([Link]()); // {value: 2, done: false}
[Link]([Link]()); // {value: 3, done: false}
[Link]([Link]()); // {value: undefined, done: true}
⬆ Back to Top
For example, the below classic or head recursion of factorial function relies on stack for each step. Each step need to be processed upto n
* factorial(n - 1)
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
[Link](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 && [Link]) {
return [Link](object) == object;
} else {
throw "Promise not supported in your environment";
}
[Link] 122/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
}
var i = 1;
var promise = new Promise(function (resolve, reject) {
resolve();
});
[Link](isPromise(i)); // false
[Link](isPromise(promise)); // true
function isPromise(value) {
return Boolean(value && typeof [Link] === "function");
}
var i = 1;
var promise = new Promise(function (resolve, reject) {
resolve();
});
[Link](isPromise(i)); // false
[Link](isPromise(promise)); // true
⬆ Back to Top
i. If a constructor or function invoked using the new operator, [Link] returns a reference to the constructor or function.
ii. For function calls, [Link] is undefined.
function Myfunc() {
if ([Link]) {
[Link]("called with new");
} else {
[Link]("not called with new");
}
}
⬆ Back to Top
414. What are the differences between arguments object and rest parameter
There are three main differences between arguments object and rest parameters
i. The arguments object is an array-like but not an array. Whereas the rest parameters are array instances.
ii. The arguments object does not support methods such as sort, map, forEach, or pop. Whereas these methods can be used in rest
parameters.
iii. The rest parameters are only the ones that haven’t been given a separate name, while the arguments object contains all arguments
passed to the function
⬆ Back to Top
415. What are the differences between spread operator and rest parameter
Rest parameter collects all remaining elements into an array. Whereas Spread operator allows iterables( arrays / objects / strings ) to be
expanded into single arguments/elements. i.e, Rest parameter is opposite to the spread operator.
⬆ Back to Top
[Link] 123/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
function* myGenFunc() {
yield 1;
yield 2;
yield 3;
}
const genObj = myGenFunc();
const myObj = {
*myGeneratorMethod() {
yield 1;
yield 2;
yield 3;
},
};
const genObj = [Link]();
class MyClass {
*myGeneratorMethod() {
yield 1;
yield 2;
yield 3;
}
}
const myObject = new MyClass();
const genObj = [Link]();
const SomeObj = {
*[[Link]]() {
yield 1;
yield 2;
yield 3;
},
};
[Link]([Link](SomeObj)); // [ 1, 2, 3 ]
⬆ Back to Top
[Link] 124/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
ii. Strings: Iterate over each character or Unicode code-points
iii. Maps: iterate over its key-value pairs
iv. Sets: iterates over their elements
v. arguments: An array-like special variable in functions
vi. DOM collection such as NodeList
⬆ Back to Top
418. What are the differences between for...of and for...in statements
Both for...in and for...of statements iterate over js data structures. The only difference is over what they iterate:
[Link] = "newVlue";
Since for..in loop iterates over the keys of the object, the first loop logs 0, 1, 2 and newProp while iterating over the array object. The for..of
loop iterates over the values of a arr data structure and logs a, b, c in the console.
⬆ Back to Top
class Person {
constructor(name, age) {
[Link] = name;
[Link] = age;
}
}
But Static(class) and prototype data properties must be defined outside of the ClassBody declaration. Let's assign the age value for Person
class as below,
[Link] = 30;
[Link] = 40;
⬆ Back to Top
[Link] 125/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
isNaN(‘hello’); // true
[Link]('hello'); // false
⬆ Back to Top
(function (dt) {
[Link]([Link]());
})(new Date());
Since both IIFE and void operator discard the result of an expression, you can avoid the extra brackets using void operator for IIFE as
below,
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
It is also possible to add more styles for the content. For example, the font-size can be modified for the above text
[Link](
"%cThis is a red text with bigger font",
[Link] 126/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
"color:red; font-size:20px"
);
⬆ Back to Top
⬆ Back to Top
[Link]("User Details");
[Link]("name: Sudheer Jonna");
[Link]("job: Software Developer");
// Nested Group
[Link]("Address");
[Link]("Street: Commonwealth");
[Link]("City: Los Angeles");
[Link]("State: California");
You can also use [Link]() instead of [Link]() if you want the groups to be collapsed by default.
⬆ Back to Top
⬆ Back to Top
[Link] 127/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
⬆ Back to Top
[Link](newArray); // [ 5, 4, 3, 2, 1]
[Link](originalArray); // [ 5, 4, 3, 2, 1]
There are few solutions that won't mutate the original array. Let's take a look.
i. Using slice and reverse methods: In this case, just invoke the slice() method on the array to create a shallow copy followed by
reverse() method call on the copy.
[Link](originalArray); // [1, 2, 3, 4, 5]
[Link](newArray); // [ 5, 4, 3, 2, 1]
ii. 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.
[Link] 128/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link](originalArray); // [1, 2, 3, 4, 5]
[Link](newArray); // [ 5, 4, 3, 2, 1]
iii. Using reduce and spread methods: Here execute a reducer function on an array elements and append the accumulated array on right
side using spread syntax
[Link](originalArray); // [1, 2, 3, 4, 5]
[Link](newArray); // [ 5, 4, 3, 2, 1]
iv. Using reduceRight and spread methods: Here execute a right reducer function(i.e. opposite direction of reduce method) on an array
elements and append the accumulated array on left side using spread syntax
[Link](originalArray); // [1, 2, 3, 4, 5]
[Link](newArray); // [ 5, 4, 3, 2, 1]
v. Using reduceRight and push methods: Here execute a right reducer function(i.e. opposite direction of reduce method) on an array
elements and push the iterated value to the accumulator
[Link](originalArray); // [1, 2, 3, 4, 5]
[Link](newArray); // [ 5, 4, 3, 2, 1]
⬆ Back to Top
i. Define your custom HTML element: First you need to define some custom class by extending HTMLElement class. After that define
your component properties (styles,text etc) using connectedCallback method. Note: The browser exposes a function called
[Link] inorder to reuse the element.
ii. Use custom element just like other HTML element: Declare your custom element as a HTML tag.
<body>
<custom-element>
</body>
⬆ Back to Top
[Link] 129/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
The global execution context is the default or first execution context that is created by the JavaScript engine before any code is
executed(i.e, when the file first loads in the browser). All the global code that is not inside a function or object will be executed inside this
global execution context. Since JS engine is single threaded there will be only one global environment and there will be only one global
execution context.
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() {
[Link]("Start function A");
function B() {
[Link]("In function B");
}
B();
}
A();
[Link]("GlobalContext");
⬆ Back to Top
⬆ Back to Top
Let's say you want to show suggestions for a search query, but only after a visitor has finished typing it. So here you write a debounce
function where the user keeps writing the characters with in 500ms then previous timer cleared out using clearTimeout and reschedule
API call/DB query for a new time—300 ms in the future.
The debounce() function can be used on input, button and window events.
Input:
Button:
[Link] 130/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Windows event:
[Link]("scroll", processChange);
⬆ Back to Top
The below example creates a throttle function to reduce the number of events for each pixel change and trigger scroll event for each
100ms except for the first event.
⬆ Back to Top
The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the
expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does
not exist.
const adventurer = {
name: "Alice",
cat: {
name: "Dinah",
},
};
[Link]([Link]?.());
// expected output: undefined
⬆ Back to Top
Environment Record is a specification type used to define the association of Identifiers to specific variables and functions, based upon
the lexical nesting structure of ECMAScript code.
[Link] 131/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Usually an Environment Record is associated with some specific syntactic structure of ECMAScript code such as a FunctionDeclaration, a
BlockStatement, or a Catch clause of a TryStatement.
Each time such code is evaluated, a new Environment Record is created to record the identifier bindings that are created by that code.
⬆ Back to Top
i. [Link]() method:
The [Link](value) utility function is used to determine whether value is an array or not. This function returns a true boolean
value if the variable is an array and a false value if it is not.
The instanceof operator is used to check the type of an array at run time. It returns true if the type of a variable is an Array other false
for other type.
The constructor property of the variable is used to determine whether the variable Array type or not.
⬆ Back to Top
let a = 5;
let b = a;
b++;
[Link](a, b); //5, 6
In the above code snippet, the value of a is assigned to b and the variable b has been incremented. Since there is a new space created
for variable b , any update on this variable doesn't impact the variable a .
Pass by reference doesn't create a new space in memory but the new variable adopts a memory address of an initial variable. Non-
primitives such as objects, arrays and functions gets the reference of the initiable variable. i.e, updating one value will impact the other
variable.
let user1 = {
name: "John",
age: 27,
};
[Link] 132/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
let user2 = user1;
[Link] = 30;
In the above code snippet, updating the age property of one object will impact the other property due to the same reference.
⬆ Back to Top
Primitives Non-primitives
⬆ Back to Top
441. How do you create your own bind method using either call or apply method?
The custom bind function needs to be created on Function prototype inorder to use it as other builtin functions. This custom function
should return a function similar to original bind method and the implementation of inner function needs to use apply method call.
The function which is going to bind using custom myOwnBind method act as the attached function( boundTargetFunction ) and argument as
the object for apply method call.
⬆ Back to Top
442. What are the differences between pure and impure functions?
Some of the major differences between pure and impure function are as below,
It is always return the same result It returns different result on each call
Easy to read and debug Difficult to read and debug because they are affected by external code
⬆ Back to Top
[Link] 133/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
multiplyBy2(add(2, 3));
⬆ Back to Top
Making an HTTP request. Asynchronous functions such as fetch and promise are impure.
DOM manipulations
Mutating the input data
Printing to a screen or console: For example, [Link]() and alert()
Fetching the current time
[Link]() calls: Modifies the internal state of Math object
⬆ Back to Top
⬆ Back to Top
(function () {
// Private variables or functions goes here.
return {
// Return public variables or functions here.
};
})();
Let's see an example of a module pattern for an employee with private and public access,
// Public
return {
name,
department,
getName: () => getEmployeeName(),
getDepartment: () => getDepartmentName(),
};
})();
[Link] 134/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link]([Link]);
[Link]([Link]);
[Link]([Link]());
[Link]([Link]());
Note: It mimic the concepts of classes with private variables and methods.
⬆ Back to Top
//example
const double = (x) => x * 2;
const square = (x) => x * x;
⬆ Back to Top
But you can fix this issue with an alternative IIFE (Immediately Invoked Function Expression) to get access to the feature.
(async function () {
await [Link]([Link]("Hello await")); // Hello await
})();
In ES2022, you can write top-level await without writing any hacks.
⬆ Back to Top
The this keyword in JavaScript is a reference to the object that owns or invokes the current function. Its value is determined by the calling
context.
[Link](this);
In a global context, this refers to the global object (e.g., window in a browser).
[Link] 135/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
function displayThis() {
[Link](this);
}
displayThis();
const person = {
name: 'John',
greet: function() {
[Link]('Hello, ' + [Link]);
}
};
[Link]();
In a method, this refers to the object that owns the method (person in the case).
[Link]('myButton').addEventListener('click', function() {
[Link](this);
});
In an event handler, this refers to the element that triggered the event (the button in this case).
⬆ Back to Top
Data Privacy: Closures can be used to create private variables and methods. By defining variables within a function's scope and returning
inner functions that have access to those variables, you can create a form of encapsulation, limiting access to certain data or functionality.
Function Factories: Closures are often used to create functions with pre-set parameters. This is useful when you need to create multiple
functions with similar behavior but different configurations.
Callback Functions: Closures are frequently used in asynchronous programming, such as handling event listeners or AJAX requests. The
inner function captures variables from the outer scope and can access them when the callback is invoked.
Memoization: Closures can be used for memoization, a technique to optimize performance by caching the results of expensive function
calls. The inner function can remember the results of previous calls and return the cached result if the same input is provided again.
iterators and Generators: Closures can be used to create iterators and generators, which are essential for working with collections of data
in modern JavaScript.
⬆ Back to Top
Creation phase: In this phase, the JavaScript engine creates the execution context and sets up the script's environment. This includes
creating the variable object and the scope chain.
[Link] 136/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Execution phase: In this phase, the JavaScript engine executes the code in the execution context. This includes evaluating expressions,
assigning values to variables, and calling functions.
The execution context is created when a function is called. The function's code is then executed in the execution context. When the function
returns, the execution context is destroyed.
⬆ Back to Top
i. The execessive usage of global variables or omitting the var keyword in local scope.
ii. Forgetting to clear the timers set up by setTimeout or setInterval .
iii. Closures retain references to variables from their parent scope, which leads to variables might not garbage collected even they are no
longer used.
i. Inline expansion: It is a compiler optimization by replacing the function calls with the corresponding function blocks.
ii. Copy elision: This is a compiler optimization method to prevent expensive extra objects from being duplicated or copied.
iii. Inline caching: It is a runtime optimization technique where it caches the execution of older tasks those can be lookup while executing
the same task in the future.
⬆ Back to Top
⬆ Back to Top
i. Abstraction
ii. Reusability
iii. Immutability
iv. Modularity
⬆ Back to Top
456. How do you create polyfills for map, filter and reduce methods?
The polyfills for array methods such as map, filter and reduce methods can be created using array prototype.
1. map:
The built-in [Link] method syntax will be helpful to write polyfill. The map method takes the callback function as an argument and
that callback function can have below three arguments passed into it.
[Link] 137/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link] = function(cb) {
let newArr = [];
for(let i=0; i< [Link]; i++) {
[Link](cb(this[i], i, this));
}
return newArr;
};
In the above code, custom method name 'myMap' has been used to avoid conflicts with built-in method.
2. filter: Similar to map method, [Link] method takes callback function as an argument and the callback function can have three
agurguments passed into it.
i. Current value
ii. Index of current value(optional)
iii. array(optional)
[Link] = function(cb) {
let newArr = [];
for(let i=0; i< [Link]; i++) {
if(cb(this[i], i, this)) {
[Link](this[i]);
}
}
return newArr;
}
3. reduce:
The built-in [Link] method syntax will be helpful to write our own polyfill. The reduce method takes the callback function as first
argument and the initial value as second argument.
The callback function can have four arguments passed into it. i. Accumulator ii. Current value iii. Index of current value(optional) iv.
array(optional)
[Link] 138/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
i. Returning values: The map method returns a new array with transformed elements whereas forEach method returns undefined
eventhough both of them are doing the same job.
The `forEach()` method in JavaScript always returns undefined. This is because forEach() is used to iterate over arrays a
ii. Chaining methods: The map method is chainable. i.e, It can be attached with reduce , filter , sort and other methods as well.
Whereas forEach cannot be attached with any other methods because it returns undefined value.
iii. Mutation: The map method doesn't mutate the original array by returning new array. Whereas forEach method also doesn't mutate
the original array but it's callback is allowed to mutate the original array.
⬆ Back to Top
i. An empty statement
ii. var statement
iii. An expression statement
iv. do-while statement
v. continue statement
vi. break statement
vii. return statement
viii. throw statement
⬆ Back to Top
[Link] 139/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
i. Capturing phase: This phase goes down gradually from the top of the DOM tree to the target element when a nested element clicked.
Before the click event reaching the final destination element, the click event of each parent's element must be triggered.
ii. Target phase: This is the phase where the event originally occurred reached the target element .
iii. Bubbling phase: This is reverse of the capturing phase. In this pase, the event bubbles up from the target element through it's parent
element, an ancestor and goes all the way to the global window object.
The pictorial representation of these 3 event phases in DOM looks like below,
⬆ Back to Top
⬆ Back to Top
Let's consider the following example to see how the additional properties age and gender added at runtime.
function Person(name) {
[Link] = name;
}
[Link] 140/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link] = 40;
[Link] = "Male";
[Link] = "Female";
[Link] = 50;
As a result, this behavior leads to lower JavaScript performance compared to the contiguous buffer method used in non-dynamic
languages. The V8 engine provided a solution named hidden classes to optimize the access time when retrieving a property on an object.
This optimization is achieved by sharing hidden classes among objects created in a similar fashion. These hidden classes are attached to
each and every object to track its shape.
When V8 engine sees the constructor function(e.g, Person) is declared, it creates a hidden class (let's say Class01) without any offsets. Once
the first property assignment statement ( [Link] = name ) is executed, V8 engine will create a new hidden class (let's say Class02),
inheriting all properties from the previous hidden class (Class01), and assign the property to offset 0. This process enables compiler to skip
dictionary lookup when you try to retrieve the same property(i.e, name). Instead, V8 will directly point to Class02. The same procedure
happens when you add new properties to the object.
For example, adding age and gender properties to Person constructor leads to transition of hidden classes(Class02 -> Class03 ->
Class04). If you create a second object(Person2) based on the same Person object, both Class01 and Class02 hidden classes are going to be
shared. However, the hidden classes Class03 and Class04 cannot be shared because second object has been modified with a different
order of properties assignment.
Since both the objects(person1 and person2) do not share the hidden classes, now V8 engine cannot use Inline Caching technique for the
faster access of properties.
⬆ Back to Top
Let's consider an example where the compiler stores the shape type in cache for repeated calls in the loop.
let shape = {width : 30, height: 20}; // Compiler store the type in cache as { width: <int>, height: <int>} after repeated ca
function area(obj) {
//Calculate area
}
for(let i=0; i<100; i++) {
area(shape);
}
After few successful calls of the same area method to its same hidden class, V8 engine omits the hidden class lookup and simply adds the offset
of the property to the object pointer itself. As a result, it increases the execution speed.
1. Monomorphic: This is a optimized caching technique in which there can be always same type of objects passed.
2. Polymorphic: This ia slightly optimized caching technique in which limited number of different types of objects can be passed.
3. Megamorphic: It is an unoptimized caching in which any number of different objects can be passed.
⬆ Back to Top
i. async: The script is downloaded in parallel to parsing the page, and executed as soon as it is available even before parsing completes.
The parsing of the page is going to be interuppted once the script is downloaded completely and then the script is executed.
Thereafter, the parsing of the remaining page will continue.
[Link] 141/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
The syntax for async usage is as shown below,
ii. defer: The script is downloaded in parallel to parsing the page, and executed after the page has finished parsing.
iii. Neither async or defer: The script is downloaded and executed immediately by blocking parsing of the page until the script execution
is completed.
Note: You should only use either async or defer attribute if the src attribute is present.
⬆ Back to Top
<script>
function x(){
var a=10;
function y(){
[Link](a); // will print a , because of lexical scope, it will first look 'a' in
//its local memory space and then in its parent functions memory space
}
y();
}
x();
</script>
⬆ Back to Top
You can also watch changes to system color scheme using addEventListener ,
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", (event) => {
const theme = [Link] ? "dark" : "light";
});
Note: The matchMedia method returns MediaQueryList object stores information from a media query.
⬆ Back to Top
[Link] 142/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
The requestAnimationFrame() method in JavaScript is used to schedule a function to be called before the next repaint of the browser window,
allowing you to create smooth, efficient animations. It's primarily used for animations and visual updates, making it an essential tool for
improving performance when you're animating elements on the web.
⬆ Back to Top
The two parameters of substr() are start and length, while for substring(), they are start and end.
substr()'s start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0.
Negative lengths in substr() are treated as zero, while substring() will swap the two indexes if end is less than start.
Furthermore, substr() is considered a legacy feature in ECMAScript, so it is best to avoid using it if possible.
⬆ Back to Top
function multiply(x, y) {
return x * y;
}
function sum(a, b, c) {
return a + b +c;
}
[Link]([Link]); //2
[Link]([Link]); //3
But there are few important rules which needs to be noted while using length property.
1. Default values: Only the parameters which exists before a default value are considered.
2. Rest params: The rest parameters are excluded with in length property.
[Link] 143/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link]([Link]); // 2
Note: The Function constructor is itself a function object and it has a length property of 1.
⬆ Back to Top
i. In web browser, the global object is accessible via window , self , or frames .
ii. In Node environment, you have to use global .
iii. In Web workers, the global object is available through self .
The globalThis property provides a standard way of accessing the global object without writing various code snippet to support multiple
environments. For example, the global object retuned from multiple environments as shown below,
⬆ Back to Top
1. Mutating methods: These are the methods that directly modify the original array.
2. Non-mutating methods: These methods return a new array without altering the original one.
1. push: Adds one or more elements to the end of the array and returns the new length.
2. pop: Removes the last element from the array and returns that element.
3. unshift: Adds one or more elements to the beginning of the array and returns the new length..
4. shift: Removes the first element from the array and returns that element.
5. splice: Adds or removes elements from the array at a specific index position.
6. sort: Sorts the elements of the array in-place based on a given sorting criteria.
7. reverse: Reverses the order of elements in the given array.
8. fill: Fills all elements of the array with a specific value.
9. copyWithIn: Copies a sequence of elements within the array to a specified target index in the same array.
⬆ Back to Top
[Link] 144/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
// [Link]
// This variable is PRIVATE to moduleA. It's like a tool inside a closed box.
const privateVariable = "I am private";
// This variable is PUBLIC because it's exported. Others can use it when they import moduleA.
export const publicVariable = "I am public";
// PUBLIC function because it's exported. But it can still access privateVariable inside moduleA.
export function publicFunction() {
[Link](privateVariable); // ✅ This works because we're inside the same module.
return "Hello from publicFunction!";
}
// [Link]
// ❌ This will cause an ERROR because privateVariable was NOT exported from moduleA.
// [Link](privateVariable); // ❌ ReferenceError: privateVariable is not defined
⬆ Back to Top
Coding Exercise
1: Undefined
2: ReferenceError
[Link] 145/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
3: null
4: {model: "Honda", color: "white", year: "2010", country: "UK"}
Answer
⬆ Back to Top
function foo() {
let x = (y = 0);
x++;
y++;
return x;
}
Answer
⬆ Back to Top
function main() {
[Link]("A");
setTimeout(function print() {
[Link]("B");
}, 0);
[Link]("C");
}
main();
1: A, B and C
2: B, A and C
3: A and C
4: A, C and B
Answer
⬆ Back to Top
1: false
2: true
Answer
⬆ Back to Top
[Link] 146/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
5. What is the output of below code
var y = 1;
if (function f() {}) {
y += typeof f;
}
[Link](y);
1: 1function
2: 1object
3: ReferenceError
4: 1undefined
Answer
⬆ Back to Top
function foo() {
return;
{
message: "Hello World";
}
}
[Link](foo());
1: Hello World
2: Object {message: "Hello World"}
3: Undefined
4: SyntaxError
Answer
⬆ Back to Top
Answer
⬆ Back to Top
[Link] 147/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
var array2 = [];
array2[2] = 100;
[Link](array2);
Answer
⬆ Back to Top
const obj = {
prop1: function () {
return 0;
},
prop2() {
return 1;
},
["prop" + 3]() {
return 2;
},
};
[Link](obj.prop1());
[Link](obj.prop2());
[Link](obj.prop3());
1: 0, 1, 2
2: 0, { return 1 }, 2
3: 0, { return 1 }, { return 2 }
4: 0, 1, undefined
Answer
⬆ Back to Top
1: true, true
2: true, false
3: SyntaxError, SyntaxError,
4: false, false
Answer
⬆ Back to Top
[Link] 148/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
1: 1, 2, 3
2: 3, 2, 3
3: SyntaxError: Duplicate parameter name not allowed in this context
4: 1, 2, 1
Answer
⬆ Back to Top
1: 1, 2, 3
2: 3, 2, 3
3: SyntaxError: Duplicate parameter name not allowed in this context
4: 1, 2, 1
Answer
⬆ Back to Top
Answer
⬆ Back to Top
1: True, False
2: False, True
Answer
[Link] 149/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
[Link]([Link]());
1: undefined
2: Infinity
3: 0
4: -Infinity
Answer
⬆ Back to Top
[Link](10 == [10]);
[Link](10 == [[[[[[[10]]]]]]]);
1: True, True
2: True, False
3: False, False
4: False, True
Answer
⬆ Back to Top
[Link](10 + "10");
[Link](10 - "10");
1: 20, 0
2: 1010, 0
3: 1010, 10-10
4: NaN, NaN
Answer
⬆ Back to Top
[Link]([0] == false);
if ([0]) {
[Link]("I'm True");
} else {
[Link]("I'm False");
}
[Link] 150/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
4: False, I'm False
Answer
1: [1,2,3,4]
2: [1,2][3,4]
3: SyntaxError
4: 1,23,4
Answer
⬆ Back to Top
Answer
⬆ Back to Top
1: True
2: False
Answer
⬆ Back to Top
1: 4
2: NaN
3: SyntaxError
4: -1
Answer
[Link] 151/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
1: 1, [2, 3, 4, 5]
2: 1, {2, 3, 4, 5}
3: SyntaxError
4: 1, [2, 3, 4]
Answer
⬆ Back to Top
Answer
⬆ Back to Top
Answer
⬆ Back to Top
function delay() {
return new Promise(resolve => setTimeout(resolve, 2000));
}
[Link] 152/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
[Link](item);
}
processArray([1, 2, 3, 4]);
1: SyntaxError
2: 1, 2, 3, 4
3: 4, 4, 4, 4
4: 4, 3, 2, 1
Answer
⬆ Back to Top
function delay() {
return new Promise((resolve) => setTimeout(resolve, 2000));
}
Answer
⬆ Back to Top
Answer
[Link] 153/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
1: true, true
2: true, false
3: false, true
4: false, false
Answer
⬆ Back to Top
1: SyntaxError
2: one
3: Symbol('one')
4: Symbol
Answer
⬆ Back to Top
1: SyntaxError
2: It is not a string!, It is not a number!
3: It is not a string!, It is a number!
4: It is a string!, It is a number!
Answer
[Link] 154/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
[Link](
[Link]({ myArray: ["one", undefined, function () {}, Symbol("")] })
);
[Link](
[Link]({ [[Link]("one")]: "one" }, [[Link]("one")])
);
Answer
⬆ Back to Top
class A {
constructor() {
[Link]([Link]);
}
}
class B extends A {
constructor() {
super();
}
}
new A();
new B();
1: A, A
2: A, B
Answer
⬆ Back to Top
1: 1, [2, 3], 4
2: 1, [2, 3, 4], undefined
3: 1, [2], 3
4: SyntaxError
Answer
⬆ Back to Top
[Link] 155/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
const { a: x = 10, b: y = 20 } = { a: 30 };
[Link](x);
[Link](y);
1: 30, 20
2: 10, 20
3: 10, undefined
4: 30, undefined
Answer
⬆ Back to Top
area();
1: 200
2: Error
3: undefined
4: 0
Answer
⬆ Back to Top
const props = [
{ id: 1, name: "John" },
{ id: 2, name: "Jack" },
{ id: 3, name: "Tom" },
];
1: Tom
2: Error
3: undefined
4: John
Answer
⬆ Back to Top
function checkType(num = 1) {
[Link](typeof num);
}
checkType();
[Link] 156/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
checkType(undefined);
checkType("");
checkType(null);
Answer
⬆ Back to Top
[Link](add("Orange"));
[Link](add("Apple"));
Answer
⬆ Back to Top
greet("Hello", "John");
greet("Hello", "John", "Good morning!");
1: SyntaxError
2: ['Hello', 'John', 'Hello John'], ['Hello', 'John', 'Good morning!']
Answer
⬆ Back to Top
1: ReferenceError
2: Inner
Answer
[Link] 157/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
myFun(1, 2, 3, 4, 5);
myFun(1, 2);
Answer
⬆ Back to Top
1: ['key', 'value']
2: TypeError
3: []
4: ['key']
Answer
⬆ Back to Top
function* myGenFunc() {
yield 1;
yield 2;
yield 3;
}
var myGenObj = new myGenFunc();
[Link]([Link]().value);
1: 1
2: undefined
3: SyntaxError
4: TypeError
Answer
⬆ Back to Top
[Link] 158/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
function* yieldAndReturn() {
yield 1;
return 2;
yield 3;
}
1: { value: 1, done: false }, { value: 2, done: true }, { value: undefined, done: true }
2: { value: 1, done: false }, { value: 2, done: false }, { value: undefined, done: true }
3: { value: 1, done: false }, { value: 2, done: true }, { value: 3, done: true }
4: { value: 1, done: false }, { value: 2, done: false }, { value: 3, done: true }
Answer
⬆ Back to Top
Answer
⬆ Back to Top
1: SyntaxError
2: 38
Answer
⬆ Back to Top
[Link] 159/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
class Square {
constructor(length) {
[Link] = length;
}
get area() {
return [Link] * [Link];
}
set area(value) {
[Link] = value;
}
}
1: 100
2: ReferenceError
Answer
⬆ Back to Top
function Person() {}
[Link] = function () {
return this;
};
[Link] = function () {
return this;
};
1: undefined, undefined
2: Person, Person
3: SyntaxError
4: Window, Window
Answer
⬆ Back to Top
class Vehicle {
constructor(name) {
[Link] = name;
}
start() {
[Link](`${[Link]} vehicle started`);
}
}
[Link] 160/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
1: SyntaxError
2: BMW vehicle started, BMW car started
3: BMW car started, BMW vehicle started
4: BMW car started, BMW car started
Answer
⬆ Back to Top
1: 30
2: 25
3: Uncaught TypeError
4: SyntaxError
Answer
⬆ Back to Top
1: false
2: true
Answer
⬆ Back to Top
1: string
2: boolean
3: NaN
4: number
Answer
[Link] 161/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
if (zero) {
[Link]("If");
} else {
[Link]("Else");
}
1: If
2: Else
3: NaN
4: SyntaxError
Answer
⬆ Back to Top
[Link] = "John";
[Link]([Link]);
1: ""
2: Error
3: John
4: Undefined
Answer
⬆ Back to Top
(function innerFunc() {
if (count === 10) {
let count = 11;
[Link](count);
}
[Link](count);
})();
1: 11, 10
2: 11, 11
3: 10, 11
4: 10, 10
Answer
⬆ Back to Top
[Link] 162/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
57. What is the output of below code ?
Answer
⬆ Back to Top
[Link](arr == str);
1: false
2: Error
3: true
Answer
⬆ Back to Top
getMessage();
1: Good morning
2: getMessage is not a function
3: getMessage is not defined
4: Undefined
Answer
⬆ Back to Top
[Link]("program finished");
1: program finished
2: Cannot predict the order
3: program finished, promise finished
4: promise finished, program finished
Answer
[Link] 163/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
console
.log("First line")
[("a", "b", "c")].forEach((element) => [Link](element));
[Link]("Third line");
1: First line , then print a, b, c in a new line, and finally print Third line as next line
2: First line , then print a, b, c in a first line, and print Third line as next line
3: Missing semi-colon error
4: Cannot read properties of undefined
Answer
⬆ Back to Top
Solution 2 (One-liner)
⬆ Back to Top
var of = ["of"];
for (var of of of) {
[Link](of);
}
1: of
2: SyntaxError: Unexpected token of
3: SyntaxError: Identifier 'of' has already been declared
4: ReferenceError: of is not defined
Answer
⬆ Back to Top
Answer
⬆ Back to Top
[Link] 164/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
65. What is the output order of below code?
setTimeout(() => {
[Link]("1");
}, 0);
[Link]("hello").then(() => [Link]("2"));
[Link]("3");
1: 1, 2, 3
2: 1, 3, 2
3: 3, 1, 2
4: 3, 2, 1
Answer
⬆ Back to Top
[Link](name);
[Link](message());
var name = "John";
(function message() {
[Link]("Hello John: Welcome");
});
Answer
⬆ Back to Top
message();
function message() {
[Link]("Hello");
}
function message() {
[Link]("Bye");
}
Answer
⬆ Back to Top
[Link] 165/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
changeCurrentCity();
1: NewYork, Singapore
2: NewYork, NewYork
3: undefined, Singapore
4: Singapore, Singapore
Answer
⬆ Back to Top
function second() {
var message;
[Link](message);
}
function first() {
var message = "first";
second();
[Link](message);
}
Answer
⬆ Back to Top
Answer
[Link] 166/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
⬆ Back to Top
const user = {
name: "John",
eat() {
[Link](this);
var eatFruit = function () {
[Link](this);
};
eatFruit();
},
};
[Link]();
Answer
⬆ Back to Top
Answer
⬆ Back to Top
let user1 = {
name: "Jacob",
age: 28,
};
let user2 = {
name: "Jacob",
age: 28,
};
1: True
2: False
3: Compile time error
[Link] 167/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Answer
⬆ Back to Top
function greeting() {
setTimeout(function () {
[Link](message);
}, 5000);
const message = "Hello, Good morning";
}
greeting();
1: Undefined
2: Reference error:
3: Hello, Good morning
4: null
Answer
⬆ Back to Top
1: False
2: True
Answer
⬆ Back to Top
function add(a, b) {
[Link]("The input arguments are: ", a, b);
return a + b;
}
1: Pure function
2: Impure function
Answer
⬆ Back to Top
[Link] 168/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
1: [{status: "fulfilled", value: undefined}, {status: "rejected", reason: undefined}]
2: [{status: "fulfilled", value: undefined}, Uncaught(in promise)]
3: Uncaught (in promise)
4: [Uncaught(in promise), Uncaught(in promise)]
Answer
⬆ Back to Top
try {
setTimeout(() => {
[Link]("try block");
throw new Error(`An exception is thrown`);
}, 1000);
} catch (err) {
[Link]("Error: ", err);
}
Answer
⬆ Back to Top
let a = 10;
if (true) {
let a = 20;
[Link](a, "inside");
}
[Link](a, "outside");
Answer
⬆ Back to Top
1: 0
2: Undefined
3: null
4: [ ]
[Link] 169/170
4/10/25, 3:42 PM GitHub - sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview Questions
Answer
---
⬆ Back to Top
An anagram is a word or phrase formed by rearranging all the letters of a different word or phrase exactly once. For example, the anagrams of
"eat" word are "tea" and "ate".
You can split each word into characters, followed by sort action and later join them back. After that you can compare those two words to verify
whether those two words are anagrams or not.
f i if ( d d ) {
Releases
No releases published
[Link]
Packages
No packages published
Contributors 117
+ 103 contributors
Languages
JavaScript 100.0%
[Link] 170/170