28
MarJavaScript Interview Questions and Answer(Fresher + Experience)
JavaScript interview preparation might be challenging, right? But don't worry; you've got this! JavaScript is a unique and strong language. I'm here to help you with callbacks, closures, async/await, and even the hard keyword issues. Let's look at some of the most popular JavaScript interview questions and answers to ensure you're prepared to ace your interview with confidence!
In this JavaScript Tutorial, we'll unlock the secrets to acing your JavaScript interview with a curated selection of the best JavaScript interview questions and answers for 2025.
To further enhance your skills and prepare for your interview, be sure to enroll in our Free Javascript Course for a comprehensive learning experience.
Why JavaScript?
- JavaScript is an unbeatable language when it comes to web development.
- It powers interactive elements, dynamic websites, and even mobile apps.
- Mastering JavaScript opens doors to exciting front-end, back-end, and full-stack development careers.
- Today, JavaScript is a programming language that can replace C#, Java, PHP, or any other object-oriented language.
- JavaScript can run in a browser, server-side, or on any device using a program known as JavaScript Engine.
- Now, let'slook at the most commonly askedJavaScript interview questions and answersin a JavaScript or front-end technologies interview.
Javascript Interview Questions For Freshers
Q. 1. What is JavaScript?
JavaScript is an object-based programming language, primarily used as a client-side programming language with the HTML page to add some behavior to it.
JavaScript was initially created as a browser-only language, but now it can be executed on the server or any client that has a JavaScript Engine. A product like Node.js, MongoDB, jaggery.js, ASP, etc, uses server-side JavaScript.
In the browser, JavaScript can do many things, as given below:
- Manipulating the HTML element.
- React to a user action, like running an event while the user clicks on the mouse or uses the keyboard.
- Send a request to the remote server.
- Downloading and uploading the files.
- Get and set cookies and handle the client-side storage (local and session storage).
Major Advantages of using the JavaScript
- Full integration with HTML/CSS.
- Supported by all major browsers, which are enabled by default.
Q 2. What is ECMAScript?
ECMAScript is a scripting language standardized by ECMA International in ECMA-262. Languages like ActionScript, JavaScript, and many more scripting languages are used in ECMAScript. Among these, JavaScript is a well-known client-side scripting language and an implementation of ECMAScript since the standard was published. The latest version is ECMAScript6.
ECMAScript is generally a standardized version of JavaScript and a general-purpose programming language that was implemented in Javascript and some other languages as well. It is a scripting language that formed the basis of browser-based Javascript and Node.js eventually.
|
Q 3. What are the data types used in Javascript?
In JavaScript, data types define the kind of value that a JavaScriptvariable can hold. JavaScript has two main categories of data types:
- Primitive Data Types (Simple and cannot be changed)
- Non-Primitive (Reference) Data Types (More complex and can be modified)
Let’s look at each type in detail with examples.
1. Primitive Data Types (Simple and cannot be changed)
Primitive data types hold simple values, and they are immutable (cannot be changed once created). There are seven primitive data types in JavaScript:
1. Number- This type is used for numbers, including both integers and decimals.
let age = 25; // Integer number
let price = 99.99; // Decimal number
2. String- A string represents text and is written inside single (') or double (") quotes.
let name = "Aman Mishra";
let message = 'Hello, how are you?';
3. Boolean- A boolean has only two values: true or false. It is used for logical decisions.
let isStudent = true;
let isRaining = false;
4. Undefined- A variable is undefined when it has been declared but not assigned any value.
let city;
console.log(city); // Output: undefined
5. Null- null represents an empty or unknown value. It is intentionally assigned to show that a variable has no value.
let person = null;
6. Symbol (Introduced in ES6)- A Symbol is a unique and immutable value, mostly used for object properties to avoid naming conflicts.
let id = Symbol("uniqueID");
7. BigInt (Introduced in ES11 - 2020)- BigInt is used to store very large numbers that are bigger than what Number can store.
let bigNumber = 123456789012345678901234567890n;
2. Non-Primitive (Reference) Data Types (More complex and can be modified)
These types hold complex structures and can be modified.
1. Object- Objects are used to store multiple values in a single variable using key-value pairs.
let student = {
name: "Aman",
age: 23,
course: "MCA"
};
2. Array- An array is a special type of object that stores a list of values.
let fruits = ["Apple", "Mango", "Banana"];
3. Function- A function is a block of code that performs a specific task.
function greet() {
return "Hello, welcome!";
}
|
Q 4. What is the difference between undefined and not defined?
In JavaScript, undefined and "not defined" may sound similar, but they have different meanings.
Factors | undefined | not defined |
Definition | A variable is declared but not assigned a value. | A variable is not declared at all. |
Error | No error; JavaScript assigns undefined automatically. | Causes a ReferenceError. |
Example | let x; console.log(x); // Output: undefined | console.log(y); // ReferenceError: y is not defined |
Solution | Assign a value before using the variable. | Declare the variable before using it. |
Let's understand both of them thoroughly.
1. undefined (Declared but Not Assigned a Value)
If you declare a variable but do not assign a value, JavaScript automatically gives it the value undefined.
let a; // Declared but not assigned a value
console.log(a); // Output: undefined
Another case of undefined: Accessing an object property that does not exist.
let person = { name: "Aman" };
console.log(person.age); // Output: undefined (because "age" is not in the object)
Now, let's move forward to Not Defined:
2. "Not Defined" (Variable Does Not Exist at All - Causes Error)
If you try to use a variable that was never declared, JavaScript will throw a ReferenceError.
console.log(b); // ReferenceError: b is not defined
- This happens because b was never declared anywhere in the code.
Q 5. What is the use of the typeof operator?
The typeof operator in JavaScriptis a unary operator which means it takes a single operand in a statement or expression. It is used to check the data type of its operand in the form of a string, for example, if we check the undefined variable then the typeof operator will return the value as "undefined".
var x=10;
console.log(typeof (x))
Output
number
It will print the number in the console
var x = 10;
console.log(typeof (x) == 'number')
Output
number
From the above code, if the type of x is a number, from the expression, it will printtruein the console.
Q 6. What is the instanceof operator?
instanceof operator in JavaScript checks whether the object is an instance of a class or not.
function Country(name){this.name=name};
var country = new Country("India");
console.log(country instanceof Country) // return true
Output
true
- It will also consider inheritance
let arr = ['apple', 'orange', 'grapes'];
console.log(arr instanceof Array); //prints true in console
console.log(arr instanceof Object); //prints true in console
Output
true
true
Here, arr is an array, but it also belongs to the object because the array prototype inherits from the object.
Q 7. What is the strict mode?
Strict mode in JavaScript helps prevent mistakes and makes code safer. It stops bad coding practices and shows errors that JavaScript would normally ignore.
- To turn on strict mode, you write "use strict"; at the start of a script or inside a function.
Example
"use strict";
x = 10; // this will give error
The above statement will give an error because, in strict mode, the variable should be declared before it is used.The “use strict” expression can be in global scope as well as local scope
1. Global scope
const employee = { name: "Ram", age: 25 }
employee.name = "Raju" // it is possible
use strict";
x = 10; // this will give error
2. Local scope
x = 10; // This will not give error.
myFunction();
function myFunction() {
"use strict";
y = 15; // This will give error
}
Q 8. Explain string in JavaScript.
In JavaScript, a string is a sequence of characters used to represent textual data. Strings are enclosed in single quotes ('), double quotes ("), or template literals (`backticks`).
But with JavaScript, the methods and properties are also available to primitive values, because JavaScript treats primitive values as an object when executing the methods and properties.
var str = 'hello';
console.log(str);//print hello
Read More: Strings in JavaScript
Q 9. What are the differences between search() and indexOf()?
Ans: The differences between search() and indexOf() methods are given below:
- search(): It is used to find a specified value and returns the position of the match, the value can be a string or a regular expression.
- indexOf(): It is used to find a specified value and returns the position of the match, the value should be a string, it won’t accept a regular expression
var m = /e/;
var m = /e/;
var str = "apple";
str.search(m)//return 4
var str = "apple";
str.indexOf(m)//return -1
Q 10. What are the differences between indexOf() and lastIndexOf() ?
The differences between indexOf() and lastIndexOf() methods are given below:
- indexOf(): It will return the index of the first occurrence of specific text in a string
- lastIndexOf(): It will return the index of the last occurrence of specific text in a string
var str = 'Hello find me test me';
str.indexOf('me') // return 11
var str = 'Hello find me test me';
str.lastIndexOf('me') // return 19
Q 11. What are the differences between substr() and substring()?
The differences between substr() and substring() methods are given below:
- substr(): It is used to return the characters in a string beginning at the specified index and returns the number of characters based on the length provided
- substring(): It is used to return the characters in a string beginning at the specified index and returns the number of characters based on the length provided minus 1.
var x = "hello";
console.log((x.substr(1, 4) == "ello"))//It will print true in the log
var x = "hello";
console.log((x.substring(1, 4) == "ello"))//It will print false in the log
var x = "hello";
console.log((x.substring(1, 5) == "ello"))//print true in console
Q 12. What are the differences between an array and an object?
The differences between array and object are given below:
Array | Object |
The array uses the numbered indexes to access the element in it | The object uses the named indexes to access the members in it. |
You should use an array when you want the element name to be a number | You should use an object when you want the element name to be a string |
It is an ordered collection. | It is a collection of unordered properties |
Q 13. What is the self-executing function?
The self-executing function will execute right after it has been defined. The advantage of using it is, that it will execute the code without declaring any global. Mostly it will be used to attach event listeners to DOM elements and other initialization work.
This type of self-executing function does not have its name and hence it is called an anonymous function. The function has a trailing set of parentheses without any arguments. The parameters for this function could be passed in the parenthesis.
Below is a simple example showing the usage of the anonymous function.
(function ()
{
//function body
})();
Q 14. What is the arrow function?
The arrow function in Javascript will support in JavaScript only after ES6 or above, it is a short way to write function expressions.
- The arrow function is a shorter syntax for using a function that does not have its own "this", below is a simple example of the same.
function add(a, b) {
return a + b;
}
console.log(add(1, 2));//3
Output
3
Using arrow function
add = (a, b) => {
return a + b }
console.log(add(1, 2));
Output
3
Q 15. How do you find the browser that is running the web page?
The window object navigator is used to find the browser that is currently running the web application.
var browsername = navigator.appName;
console.log(browsername);
Q 16. How do you redirect the user to a new page?
We can use the window object location to redirect the user to the new page by providing the HREF URL link to be redirected.
window.location.href="https://www.dotnettricks.com/"
Q 17. What is the output of the below code?
var num = "10";
(function () {
console.log("Original Number " + num);
var num = "50"; // This is the inner variable
console.log("New Number " + num);
})();
Output
Original Number undefined
New Number 50
Reason: You would expect the original number to take the value from the outer scope, but the salary value was undefined because of hoisting.
Q 18. What is DOM?
DOM is a W3C (World Wide Web Consortium) standard. When the HTML page loads in the browser, the browser creates the DOM (Document object model). It defines the HTML element as an object and allows scripts to manipulate the content and the structure of the document dynamically.
When any HTML document is loaded in the browser, it becomes a document object, which is the root element that represents the HTML document. Each DOM element has various properties and methods. With the help of document objects, we may add dynamic content to our web page according to the required behavior.
HTML:
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Document Object Model</h1>
</body>
</html>
In DOM, every HTML is an object, Nested tags are “children”, and the text inside a <h1> is an object as well
The DOM Tree of objects
The DOM represents HTML as a tree structure of tags. Here’s how it looks in the browser inspect the element
Q 19. What is BOM?
BOM (Browser Object Model)provides interaction with the browser, the default object of the browser is a window. The various properties provided by Windows are a document, history, screen, location, and navigator.
All modern browsers have implemented the same methods and properties for JavaScript operational interactions often referred to as BOM's methods and properties. A window object is automatically created by the browser itself.
Read More: Understanding DOM and BOM |
Q 20. What is the NaN property in JavaScript?
NaN property depicts the “Not-a-Number” value. It shows a value that is not a legal number. One type of NaN would return a Number. If you want to check if a value is NaN, the isNaN() function is used. It is important to note that the isNaN() function transforms the given value to a Number type; later on, it equates to NaN.
Q 21. What is the difference between the 'var' and 'let' keywords?
The difference between the 'var' and 'let' keywords are:
Factor | 'var' Keyword | 'let' keyword |
Scope | Function-scoped (Available throughout the function) | Block-scoped (Available only inside {} where it is defined) |
Hoisting | Hoisted to the top but initialized as undefined | Hoisted to the top but not initialized (Accessing before declaration gives an error) |
Redeclaration | Can be redeclared in the same scope | Cannot be redeclared in the same scope (throws an error) |
Reassignment | Can be reassigned | Can be reassigned |
Global Object Property (window.var) | Becomes a property of the window object in browsers | Does not become a property of window object |
Example: var (Function-Scoped)
function testVar() {
var x = 10;
if (true) {
var x = 20; // Same variable (overwrites)
console.log(x); // Output: 20
}
console.log(x); // Output: 20 (Still changed)
}
testVar();
Output
20
20
Example: let (Block-Scoped)
function testLet() {
let y = 10;
if (true) {
let y = 20; // Different variable (inside block)
console.log(y); // Output: 20
}
console.log(y); // Output: 10 (Original value)
}
testLet();
Output
20
10
Javascript Interview Questions for Intermediate Developers
Q 22. What is Implicit Type Coercion in JavaScript?
Implicit Type Coercion in JavaScript is the automatic conversion of one data type into another when different types are used in an operation. JavaScript performs this conversion internally to avoid errors and ensure smooth execution.
Exmple
console.log("10" * 2); // Output: 20 (String "10" is converted to a Number)
Output
20
Q 23. Does JavaScript use static typing or dynamic typing?
JavaScript is a dynamically typed language. This means that variable types are determined at runtime, and you do not need to declare a specific data type when defining a variable. The type of a variable can change as the program runs.
Q 24. What is a Higher Order Function in JavaScript?
A Higher-Order Function (HOF) is a function that takes another function as an argument or returns a function as its result. These functions help make code more reusable, modular, and readable.
Example
function greet(name) {
return `Hello, ${name}!`;
}
function processUser(userName, callback) {
return callback(userName); // Calls the passed function
}
console.log(processUser("Aman", greet));
Output
Hello, Aman!
Q 25. Explain Self-Invoking Functions in JavaScript.
A Self-Invoking Function, also called an Immediately Invoked Function Expression (IIFE), executes automatically as soon as it is defined without needing to be called separately.
Example
(function() {
console.log("This function runs automatically!");
})();
Output
This function runs automatically!
Q 26. What is the usefulness of the window object?
A browser’s history object could be used to switch to history pages like back and forward from the existing page or another page. 3 methods of studying history objects are as follows:
- history.back() – This method loads the previous page.
- history.forward() – This method loads the next page.
- history.go(number) - Its number may be positive (for forwarding) or negative (for backward). It will load the provided page number.
Q 27. What is the functioning of timers in JavaScript?
Timers are useful for operating a piece of code at a specific time or iterating the code in a specific interval. Functions like setInterval, setTimeout, and clearInterval perform this function. Timers are executed in a single thread, so they may queue up and take a while to execute.
The setTimeout(function, delay) function is useful for starting a timer that calls a specific function after the stated delay. The setInterval(function, delay) function frequently operates the provided function within the stated delay and only stops when it is canceled. The timer learns when to stop with the clearInterval(id) function.
Q 28. What are the various types of errors in JavaScript?
There are three types of errors in JavaScript:
- Runtime errors: These are the errors that occur due to misuse of the command within the HTML language.
- Load time errors: These errors occur while loading a web page. An example includes improper syntax errors that produce the errors dynamically.
- Logical Errors: These errors occur because of bad logic carried out on a function with a varied operation.
Q 29. Explain the “this” keyword.
The “this” keyword refers to the object of which the function is a property. The value of the “this” keyword will always depend on the object that is invoking the function.
Example
var obj = {
name: "ScholarHat",
getName: function(){
console.log(this.name);
}
}
obj.getName();
Output
ScholarHat
In the above code, at the time of invocation, the getName function is a property of the object obj, therefore, this keyword will refer to the object obj, and hence the output will be “ScholarHat”.
Q 30. Explain the difference between .call() and .apply().
The functions .apply() and .call() are very identical in their usage but come with a minor difference. The .call() is employed whenever the programmer knows the number of the function arguments. This is because they have to be stated as arguments within the call statement. Conversely, .apply() is employed whenever the number is unknown. Also, this function .apply() needs an array argument. The key difference between these two functions is how the arguments are passed to the function.
Q 31. How is DOM used in JavaScript?
DOM (Document Object Model) is accountable for how different objects in a document interrelate with each other. It is useful for developing web pages that contain objects like links, paragraphs, etc. Such objects can be executed by including actions like add or delete. Furthermore, DOM is also useful to equip a web page with extra capabilities. The use of API provides a benefit compared to other prevailing models.
Q 32. What is the role of deferred scripts in JavaScript?
The parsing of HTML code during page loading is, by default, paused until the script has not halted executing. The webpage is delayed if the server is slow or the script is chiefly heavy.
When using Deferred, scripts delay execution until the HTML parser is operating. This decreases web pages’ loading time and showcases them faster.
Q 33. What are the different functional components of JavaScript?
Functional components of JavaScript are important topics covered in a javascript Course. Two types of functional components in JavaScript are –First-class functions and nested functions.
(I). First-class functions
These functions in JavaScript are used as first-class objects. Usually, this means that such functions can be passed in the form of arguments to other functions. Moreover, they are returned as values from other functions or assigned to variables, or they can be saved in data structures.
(II). Nested functions
Those functions that are defined within other functions are termed Nested functions. Whenever the main function is invoked, nested functions are called.
Q 34. What are the different ways to access the HTML elements in JavaScript?
The following DOM Methods are used to capture the HTML element and manipulate it.
getElementById('idname') - > This function is used to select the HTML element based on the ID property of the HTML element.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <label id="myelement"></label> <script> document.getElementById('myelement').innerHTML = '<h3> Welcome </h3>' </script> </body </html>
getElementsByClassName('className') - > This function is used to select the HTML elements based on the class name in DOM, it will return all matched HTML elements concerning the class name.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <style> .lblMsg { color: #000; } </style> <body> <label id="myelement" class="lblMsg"></label> <script> document.getElementsByClassName('lblMsg')[0].innerHTML = '<h3> Welcome </h3>' </script> </body> </html>
getElementsByTagName(‘HTMLtagname’) - > This function is used to select the HTML elements based on the Tag name in DOM, it will return all matched HTML elements concerning the Tag name.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <style> .lblMsg { color: #000; } </style> <body> <label id="myelement" class="lblMsg"></label> <script> document.getElementsByTagName('label')[0].innerHTML = '<h3> Welcome </h3>' </script> </body> </html>
Q 35. What is the difference between function declarations and function expressions?
Ans. Function declarations are defined using the function keyword, while function expressions are defined by assigning a function to a variable. Function declarations are hoisted, while function expressions are not.
Q 36. What are the types of errors in JavaScript?
There are two types of errors in JavaScript.
- Syntax errors: These errors are mistakes or spelling problems in the code that cause the program to not execute at all or to stop running halfway through. Error messages are usually supplied as well.
- Logical error: Reasoning mistakes occur when the syntax is proper but the logic or program is incorrect. The application executes without problems in this case. However, the output findings are inaccurate. These are sometimes more difficult to correct than syntax issues since these applications do not display error signals for logic faults.
Q 37. What is the use of a TypedArray object in JavaScript?
The JavaScript TypedArray object illustrates an array-like view of an underlying binary data buffer. There are several different global properties, whose values are TypedArray constructors for specific element types.
function display()
{
var arr1= [11,12,3,4,5,6,17,8,9,10];
arr1.copyWithin(2) ;
document.write(arr1);
}
display();
Q 38. Explain WeakSet in JavaScript.
In JavaScript, a Set is a collection of unique and ordered elements. Similarly, WeakSet is also a collection of unique and ordered elements with some key differences:
- Weakset contains only objects and no other type.
- An object inside the weakest is referenced weakly. This means that if the object inside the weakest does not have a reference, it will be garbage collected.
- Unlike Set, WeakSet only has three methods: add(), delete(), and has().
const newSet = new Set([4, 5, 16, 7]);
console.log(newSet);// Outputs Set {4,5,16,7}
const newSet2 = new WeakSet([3, 4, 5]); //Throws an error
let obj1 = {message:"Hello ScholarHat"};
const newSet3 = new WeakSet([obj1]);
console.log(newSet3.has(obj1)); // true
Q 39. What is the use of the debugger keyword in JavaScript?
The debugger keyword sets the breakpoint through the code itself. The debugger stops the execution of the program at the position it is applied. Now, we can start the flow of execution manually. If an exception occurs, the execution will stop again on that particular line.
function display()
{
x = 20;
y = 15;
z = x + y;
debugger;
document.write(z);
document.write(a);
}
display();
Q 40. What is a prototype design pattern?
The Prototype Pattern produces different objects, but instead of returning uninitialized objects, it produces objects that have values replicated from a template – or sample – object. It is also known as the Properties pattern, the Prototype pattern is used to create prototypes.
The Prototype pattern is hardly used in traditional languages. However, it is used in the development of new objects and templates in JavaScript, which is a prototypal language.
Javascript Interview Questions for Experienced Developers
Q 41. What are the advantages of JavaScript?
The following are some of the advantages of JavaScript:
- JavaScript is executed on the client side as well as the server side.
- There are a variety of front-end frameworks that you may study and utilize.
- However, if you want to use JavaScript on the backend, you'll need to learn NodeJS.
- It is currently the only JavaScript framework that may be used on the backend.
- JavaScript is a simple language to learn.
- Web pages now have more functionality because of Javascript.
- To the end-user, Javascript is relatively quick.
Q 42. What are the different events in JavaScript?
There are many different events in JavaScript. The following are some of them:
- Click: This occurs when a user clicks on an HTML element.
- Mouseover: It occurs when a user's mouse pointer moves over an HTML element.
- Keydown: It occurs when a user presses a key on the keyboard.
- Keyup: It occurs when a user releases a key on the keyboard.
- Change: It occurs when a user changes the value of an HTML input element.
Q 43. What is the difference between exec() and test() methods in JavaScript?
The difference between exec() and test() methods in JavaScript are:
- test() and exec() are RegExp expression methods used in JavaScript.
- We'll use exec() to search a string for a specific pattern, and if it finds it, it'll return the pattern directly; otherwise, it'll return an 'empty' result.
- We will use a test() to find a string for a specific pattern. It will return the Boolean value 'true' on finding the given text otherwise, it will return 'false'.
Q 44. Explain WeakMap in JavaScript.
We know thataMap in JavaScript is used to store key-value pairs. The key-value pairs can be of both primitive and non-primitive types. WeakMap is similar to Map with key differences:- The keys and values in weakmap should always be an object.
- If there are no references to the object, the object will be garbage collected.
const map1 = new Map();
map1.set('Value', 1);
const map2 = new WeakMap();
map2.set('Value', 2.3); // Throws an error
let obj = {name:"ScholarHat"};
const map3 = new WeakMap();
map3.set(obj, {age:2});
Q 45. Is JavaScript a pass-by-reference or pass-by-value language?
The variable's data is always a reference for objects, hence it's always a pass-by value. As a result, if you supply an object and alter its members inside the method, the changes continue outside of it.
It appears to be a pass-by reference here. However, if you modify the values of the object variable, there's no permanent change, demonstrating that it is indeed passed by value.
Q 46. What is the requirement for debugging in JavaScript?
JavaScript never shows any error message in the browser. However, these mistakes can affect the output. The best way to find out the error is to debug the code. The code can be debugged easily by using web browsers like Google Chrome, and Mozilla Firebox.
To perform debugging, we can use any of the following approaches:
- Using console.log() method
- Using debugger keyword
Q 47. What is a Temporal Dead Zone?
Temporal Dead Zone is a behavior that occurs with variables declared using let and const keywords. Here, we try to access a variable before it is initialized.
Example
x = 30; // Gives reference error
let x;
function anotherRandomFunc(){
message = "Hello ScholarHat"; // Throws a reference error
let message;
}
anotherRandomFunc();
Q 48. What are the different ways to access an HTML element in JavaScript?
There are mainly three ways to access an HTML element in JavaScript:
- Using the getElementById() method: The getElementById() method takes a string as an argument and returns the HTML element with the specified ID.
- Using the getElementsByTagName() method: The getElementsByTagName() method takes a string as an argument and returns an array of all the HTML elements with the specified tag name.
- Using the querySelector() method: The querySelector() method takes a CSS selector as an argument and returns the first HTML element that matches the selector.
Q 49. Is JavaScript a case-sensitive language?
Yes, JavaScript is a case-sensitive language.Example
Var msg = "ScholarHat by DotNetTriks"; //Here, var should be used to declare a variable
function display()
{
document.writeln(msg); // It will not display the result.
}
display();
Q 50. What is the difference between localStorage and sessionStorage in JavaScript?
Both localStorage and sessionStorage are web storage objects in JavaScript, but they have different scopes and lifetimes.
- The localStorage persists data even after the browser window is closed and is accessible across different browser tabs/windows of the same origin.
- The sessionStorage stores data for a single browser session and is accessible only within the same tab or window.
Q 51. What is the difference between JavaScript and JScript?
Netscape provided the JavaScript language. Microsoft changed the name and called it JScript to avoid trademark issues. In other words, you can say JScript is the same as JavaScript, but Microsoft provides it.
Q 52. What is the difference between splice() and slice()?
The difference between splice() and slice() is:
- splice() is used to modify an array by adding, removing, or replacing elements at a specific position.
splice(start, optional delete count, optional items to add)
- slice() is used to create a new array that contains a portion of an existing array, specified by the starting and ending indices.
slice(optional start parameter, optional end parameter)
Q 53. What are the four states of promise objects in JavaScript?
Promise object has four states -
- Pending - Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is pending.
- Fulfilled - This state represents that the promise has been fulfilled, meaning the async operation is completed.
- Rejected - This state represents that the promise has been rejected for some reason, meaning the async operation has failed.
- Settled - This state represents that the promise has been either rejected or fulfilled.
Q 54. What is event delegation in JavaScript?
Event delegation is a technique of attaching a single event listener to a parent element. This event listener handles events occurring on its child elements. It helps optimize performance and reduce memory consumption.
Item 1
Item 2
Item 3
document.getElementById("list").addEventListener
("click", function(event) {
if (event.target.nodeName === "LI" ) {
console.log(event.target.textContent);
}
});
Q 55. Explain the for-in loop in JavaScript.
The for-in loop in javascript is used to loop through the properties or keys of an object. Syntax
for (key in object) {
// body
};
Q 56. What are Screen objects?
Screen objects implement the Screen interface. They store information about the screen on which the current window is being rendered. The properties of screen objects are:
- AvailHeight: Gives the height of the visitor's screen
- AvailWidth: Gives the width of the visitor's screen
- ColorDepth: Gives the bit depth of images on the visitor's screen
- Height: Gives the total height of the visitor's screen, including the taskbar
- Width: Gives the total width of the visitor's screen, including the taskbar
Q 57. Why should you not use innerHTML in JavaScript?
The two major drawbacks are:
- Cybersecurity concerns: Since innerHTML can add content that includes actual bits of HTML code rather than simple strings, it may pose a security risk.
- Inefficiency: innerHTML content is refreshed every time. This makes the page slower and inefficient.
Q 58. Differentiate innerText from innerHTML.
The difference between innerTextand innerHTML are:
innerText | innerHTML |
Retrieves and sets the content in plain text | Retrieves and sets the content in HTML format |
We can not insert the HTML tags | We can insert the HTML tags |
It ignores the spaces. | It considers the spaces. |
It returns text without an inner element tag. | It returns a tag with an inner element tag. |
Q 59. What is the unshift method in JavaScript?
The unshift() method adds new elements to the beginning of an array. It overwrites the original array.
Syntax
array.unshift(item1, item2, ..., itemX)
Q 60. What is an event bubbling in JavaScript?
Event bubbling is one of the event propagation methods in the DOM (Document Object Model). They dictate the order in which events are processed in the DOM tree.
In event bubbling, events are processed from the innermost element and then propagated up to the parent elements. With this, we can handle multiple events with a single event listener. The event first triggers on the target element and then propagates up the DOM tree.
In this example, there are three nested div elements within the body.When an event occurs on the Div element, the event starts at the Div element and then bubbles up the DOM tree, starting with Div2, then Div1, and finally, the Body element.
Q 61. What is hoisting in JS?
Hoisting inJSrefers to the process whereby the interpreter appears to move the declaration of functions, variables, classes, or imports to the top of their scope before the code is executed. Hence, we can use a functionor a variable before declaration.
Example
// use demo variable before declaring
console.log(demo);
// declare and initialize demo variable
var demo = 5;
Here, we can use the demo variable before declaration because of variable hoisting. But, we get undefined as output because the variable hasn't been initialized at the time it's printed.
Output
undefined
Q 62. What is a debounce function?
Debounce optimizes event handling by delaying the execution of a function until after a specified period of dormancy. When an event is triggered, the debounce function starts a timer. If the function is called again within the delay period, the timer is reset. This delay helps prevent unnecessary or premature function calls, resulting in more efficient event handling.
Q 63. What is Negative Infinity?
Negative infinity is a constant value that represents the lowest available value. This means that no number is less than this value. Negative Infinity is calculated by dividing a negative number by zero.
Q 64. What is Memoization in JavaScript?
Memoization is a performance optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again. This helps reduce redundant calculations and improves execution speed.
Example:
function memoizedFactorial() {
let cache = {}; // Store previous results
return function factorial(n) {
if (n in cache) {
console.log("Fetching from cache:", n);
return cache[n]; // Return cached result
}
console.log("Calculating result for:", n);
if (n <= 1) return 1;
cache[n] = n * factorial(n - 1); // Store result in cache
return cache[n];
};
}
const factorial = memoizedFactorial();
console.log(factorial(5)); // Calculates and stores
console.log(factorial(5)); // Fetches from cache
Output:
Calculating result for: 5
Calculating result for: 4
Calculating result for: 3
Calculating result for: 2
Calculating result for: 1
120
Fetching from cache: 5
120
Q 65. What is Recursion in a Coding Language?
Recursion is a programming technique where a function calls itself to solve a problem. It breaks down complex problems into smaller subproblems, making them easier to solve.
Example:
function factorial(n) {
if (n === 1) return 1; // Base case (stops recursion)
return n * factorial(n - 1); // Recursive call
}
console.log(factorial(5)); // Output: 120
Output:
120
Q 66. What is the Rest Parameter and Spread Operator?
The rest parameter (`...`) allows a function to accept an indefinite number of arguments as an array. The spread operator (`...`) expands an array or object into individual elements.
Example of Rest Parameter:
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(10, 20, 30)); // Output: 60
Output:
60
Example of Spread Operator:
let numbers = [1, 2, 3];
let newNumbers = [...numbers, 4, 5]; // Spreads elements
console.log(newNumbers); // Output: [1, 2, 3, 4, 5]
Output:
[1, 2, 3, 4, 5]
Summary
I hope these questions and answers will help you crack your JavaScript Interview. They have been taken from our newly released eBook, JavaScript Interview Questions & Answers, which contains more than 110 JavaScript interview questions.
This eBook has been written to make you confident in JavaScript with a solid foundation. Also, this will help you to turn your programming into your profession. It would be equally helpful in your real projects or to crack your JavaScript Interview.

Download this PDF Now - JavaScript Interview Questions and Answers PDF By ScholarHat |
Test your skills by following MCQs
🚀 Test your JavaScript knowledge with this fun and interactive quiz! Can you get a perfect score?
Q 1: What is JavaScript primarily used for?
FAQs
- Fundamentals: Cover basic syntax, data types, variables, operators, and control flow.
- Advanced Concepts: Dive into closures, prototypes, hoisting, asynchronous programming, and the Document Object Model (DOM).
- Problem Solving: Assess your ability to analyze problems, write efficient code, and debug issues.
- Frameworks and Libraries: If relevant, expect questions about specific frameworks like React, Angular, or Vue.js.
- Behavioral: Explore your teamwork, communication, and problem-solving skills on past projects.
- Not understanding the difference between var, let, and const.
- Struggling with closures and scope chain concepts.
- Being unfamiliar with common browser APIs and event handling.
- Neglecting best practices for clean, readable code.
- Getting nervous or flustered under pressure.
Take our Javascript skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.