SlideShare a Scribd company logo
JavaScript Interview Questions and Answer(Fresher
+ Experience)
Are you gearing up for a JavaScript interview? Whether you're a seasoned developer or a passionate fresher,
mastering the right questions can make all the difference. In this comprehensive guide, we'll unlock the
secrets to acing your JavaScript interview with a curated selection of the best JavaScript interview
questions and answers for 2024.
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. This article contains the most commonly asked JavaScript interview questions and answers in a
JavaScript or front-end technologies Interview.
Why JavaScript?
Javascript Interview Questions For Freshers
1. What is JavaScript?
Ans. JavaScript is an object-based programming language, mostly used as a client-side programming
language with the HTML page to add some behavior for it.
2. What is ECMAScript?
Ans. 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.
3. Which data types are supported by JavaScript?
Watch the Video - Introduction to ECMA Script
Major Advantages of using the JavaScript
Full integration with HTML/CSS.
Supported by all major browsers which are enabled by default.
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.
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 some event while the user clicks on the mouse or by using 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).
Ans. Consider the below example
Watch the Video - Data Type in JavaScript | Primitive and Non Primitive Data Type
Now in the console, we will get a message that x is ‘undefined’ which means the variable is declared and
memory is created but the value is not assigned to it.
In this case, you will get a message like ‘not defined’ because the variable y is not created, and memory is not
allocated for it and we try to reference the variable.
Ans. JavaScript variables are dynamically typed, which means there is a data type but it will not be bound to a
particular type, For example, while initializing the variable it can be string type but later It can also be
assigned to a numeric value.
Two types of data types are being supported which are primitive data types and non-primitive data types.
Below are some of the data types supported by JavaScript.
The data types supported by JavaScript are:
Undefined
Null
Boolean
Object
String
Symbol
Number
4. What is the difference between undefined and not defined?
console.log(y)
var x;
console.log(x);
7. What is the strict mode?
Ans. “use strict” is not a statement but a literal expression which is supported by ECMAScript version 5. This
statement instructs the browser to use the strict mode, which is a safer future in JavaScript. It will eliminate
6. What is the instanceof operator?
Ans. instanceof operator checks whether the object is an instance of a class or not.
5. What is the use of typeof operator?
Ans. The typeof is 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".
It will also consider inheritance
It will print the number in the console
Here, arr is an array, but it also belongs to the object, because array prototypal inherits from the object.
From the above code if the type of x is a number, so from the expression it will print true in the console.
var x=10;
console.log(typeof (x))
var x = 10;
console.log(typeof (x) == 'number')
function Country(name){this.name=name};
var country = new Country("India");
console.log(country instanceof Country) // return true
let arr = ['apple', 'orange', 'grapes'];
console.log(arr instanceof Array); //prints true in console
console.log(arr instanceof Object); //prints true in console
local scope
The “use strict” expression can be in global scope as well as local scope
Global scope
The above statement will give an error because in strict mode the variable should be declared before it is
used.
some JavaScript silent errors.
The strict mode applies to the entire script or the individual functions and it doesn't apply to the block
statements or code which is enclosed by the curly braces {}. Attempting to apply it to such contexts does not
have any meaning. At multiple places such as eval code, functional code, event handler attributes, strings
passed along with the setTimeout() and related functions are completely scripts, and invoking the strict mode
in them works as expected to check the syntax vulnerabilities.
Example
"use strict";
x = 10; // this will give error
x = 10; // This will not give error.
myFunction();
const employee = { name: "Ram", age: 25 }
employee.name = "Raju" // it is possible
use strict";
x = 10; // this will give error
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
8. Explain string in JavaScript.
Ans. The group of characters or textual data is called a string in JavaScript. There is no separate type for the
character, even a single character will be stored as a string. In JavaScript, the string can be enclosed with
single quotes or double quotes.
9. What are the differences between search() and indexOf()?
Ans: The differences between search() and indexOf() methods are given below:
Read More: Strings in JavaScript
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
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 m = /e/;
var m = /e/;
var str = "apple";
var str = "apple";
str.search(m)//return 4
var str = 'hello';
console.log(str);//print hello
function myFunction() {
"use strict";
y = 15; // This will give error
}
11. What are the differences between substr() and substring()?
Ans: The differences between substr() and substring() methods are given below:
10. What are the differences between indexOf() and lastIndexOf() ?
Ans: 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
It will print true in the log
It will print false in the log
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.
str.indexOf(m)//return -1
var str = 'Hello find me test me';
str.indexOf('me') // return 11
var str = 'Hello find me test me';
str.lastIndexOf('me') // return 19
var x = "hello";
console.log((x.substr(1, 4) == "ello"))
var x = "hello";
console.log((x.substring(1, 4) == "ello"))
var x = "hello";
console.log((x.substring(1, 5) == "ello"))//print true in console
HTML to PDF
14. What is the arrow function?
Ans. The arrow function will support in JavaScript only after ES6 or above, it is a short way to write function
expressions.
13. What is the self-executing function?
Ans. 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.
12. What are the differences between an array and an object?
Ans: The differences between array and object are given below:
Array
The array uses the numbered indexes to access the
element in it
Object
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
It is an ordered collection.
You should use an object when you want the
element name to be a string
It is a collection of unordered properties
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.
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
})();
function add(a, b) {
return a + b;
Run Code >>
Using arrow function
Ans. The window object navigator is used to find the browser which is currently running the web application.
Ans. We can use the window object location to redirect the user to the new page by providing the HREF URL
link to be redirected.
17. What is the output of the below code?
16. How to redirect the user to a new page?
15. How to find the browser that is running the web page?
var num = "10";
}
console.log(add(1, 2));//3
add = (a, b) => {
return a + b
}
console.log(add(1, 2));//3
var browsername = navigator.appName;
console.log(browsername);
(function () {
console.log("Original Number " + num);
var num = "50"; // This is the inner variable
console.log("New Number " + num);
})();
window.location.href="https://www.dotnettricks.com/"
Output
Original Number undefined
New Number 50
<!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
Reason: You will expect the original number will take the value from the outer scope, but the salary value was
undefined, because of hoisting.
Ans. 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 dynamically manipulate the content and the structure of the document.
When any of the HTML documents are loaded in the browser, it will become a document object which is the
root element that represents the HTML document. Each DOM element has various properties and methods.
and with the help of document objects, we may add dynamic content to our web page according to the
required behavior.
HTML:
Ans. 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
19. What is BOM?
18. What is DOM?
the browser itself.
Read More: Understanding DOM and BOM
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 history object are as follows:
1. history.back() – This method loads the previous page.
2. history.forward() – This method loads the next page.
3. history.go(number) - Its number may be positive (for forwarding) or negative (for backward). It will load
the provided page number.
Ans.Here are the three types of errors in JavaScript:
1. Runtime errors: These are the errors that occur due to misuse of the command within the HTML
language.
2. Load time errors: These errors occur while loading a web page. An example includes improper syntax
errors that produce the errors dynamically.
3. Logical Errors: These errors come up because of the bad logic carried out on a function with a varied
operation.
Ans. 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.
Ans. Timers are useful to operate a piece of code at a specific time or iterate the code in a specific interval.
The same is performed by using functions like setInterval, setTimeout, and clearInterval. Timers are
executed in a single thread. Therefore, they may queue up and there may be a waiting time for execution.
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 in the stated
delay and only stops when canceled. The timer gets to know when to stop with the clearInterval(id) function.
24. Explain the “this” keyword.
20. What is the NaN property in JavaScript?
21. What is the usefulness of the window object?
22. What is the functioning of timers in JavaScript?
23. What are the various types of errors in JavaScript?
Javascript Interview Questions for Intermediate Developers
Ans. 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.
Ans. 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 to contain 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.
Ans. 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 the Deferred, scripts would delay execution of the script until the HTML parser is operating. It
decreases the web pages’ loading time and they get showcased faster.
The “this” keyword refers to the object that the function is a property of. The value of the “this” keyword will
always depend on the object that is invoking the function.
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”.
Example
26. How is DOM used in JavaScript?
27. What is the role of deferred scripts in JavaScript?
25. Explain the difference between .call() and .apply().
28. What are the different functional components in JavaScript?
var obj = {
} }
obj.getName();
name: "ScholarHat",
getName: function(){
console.log(this.name);
HTML to PDF
2. 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.
Ans. The following DOM Methods are used to capture the HTML element and manipulate it.
1. getElementById('idname') - > This function is used to select the HTML element based on the ID property
of the HTML element.
Ans. Functional components 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.
29. What are the different ways to access the HTML elements in JavaScript?
<!DOCTYPE html> <html>
<head> <meta
charset="utf-8" /> <title>
</title> </head>
<!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>
3. 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.
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.
30. What is the difference between function declarations and function
expressions?
<!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>
<style> .lblMsg { color: #000; }
</style>
<body>
<label id="myelement" class="lblMsg"></label>
<script> document.getElementsByClassName('lblMsg')[0].innerHTML = '<h3> Welcome
</h3>' </script> </body> </html>
33. 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().
31. What are the types of errors in javascript?
There are two types of errors in javascript.
32. What is the use of a TypedArray object in JavaScript?
The JavaScript TypedArray object illustrates an array like a view of an underlying binary data buffer. There are
several different global properties, whose values are TypedArray constructors for specific element types.
1. 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.
2. 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.
let obj1 = {message:"Hello ScholarHat"};
function display()
{
var arr1= [11,12,3,4,5,6,17,8,9,10];
arr1.copyWithin(2) ;
document.write(arr1);
}
display();
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
35. 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.
36. What are the advantages of JavaScript?
Following are some of the advantages of JavaScript:
34. 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.
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 is executed on the client side as well as server-side also. There are a variety of Frontend
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 quite quick.
Javascript Interview Questions for Experienced Developers
function display() { x
= 20; y = 15; z = x + y;
debugger;
document.write(z);
document.write(a);
}
display();
const newSet3 = new WeakSet([obj1]);
console.log(newSet3.has(obj1)); // true
40. Explain WeakMap in JavaScript.
We know that Map 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:
37. What are the different events in JavaScript?
There are many different events in JavaScript. The following are some of them:
38. Explain higher-order functions in JavaScript.
Functions that operate on other functions, either by taking them as arguments or by returning them, are called
higher-order functions.
39. What is the difference between exec() and test() methods in JavaScript?
Click: It 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.
Higher-order functions are a result of functions being first-class citizens in JavaScript.
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.
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'.
const map1 = new Map();
map1.set('Value', 1);
function higherOrder() {
return function() {
}
}
var x = higherOrder();
x()
return "Hello ScholarHat";
43. 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.
42. What is the requirement of 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.
41. 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.
To perform debugging, we can use any of the following approaches:
Using console.log() method
Using debugger keyword
Example
let x;
let message;
let obj = {name:"ScholarHat"};
const map3 = new WeakMap();
map3.set(obj, {age:2});
x = 30; // Gives reference error
const map2 = new WeakMap();
map2.set('Value', 2.3); // Throws an error
function anotherRandomFunc(){
message = "Hello ScholarHat"; // Throws a reference error
46. What is the use of history objects?
The history object of a browser can be used to switch to history pages such as back and forward from the
current page or another page. There are three methods of history object.
45. Is JavaScript case-sensitive language?
Yes, JavaScript is a case-sensitive language.
47. 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.
44. What are the different ways to access an HTML element in JavaScript?
There are mainly three ways to access an HTML element in JavaScript:
1. Using the getElementById() method: The getElementById() method takes a string as an argument and
returns the HTML element with the specified ID.
2. 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.
3. Using the querySelector() method: The querySelector() method takes a CSS selector as an argument and
returns the first HTML element that matches the selector.
1. history.back() - It loads the previous page.
2. history.forward() - It loads the next page.
3. history.go(number) - The number may be positive for forward, and negative for backward. It loads the
given page number.
Example
}
anotherRandomFunc();
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();
splice() is used to modify an array by adding, removing, or replacing elements at a specific position.
slice() is used to create a new array that contains a portion of an existing array, specified by the starting
and ending indices.
Netscape provided the JavaScript language. Microsoft changed the name and called it JScript to avoid the
trademark issue. In other words, you can say JScript is the same as JavaScript, but Microsoft provides it.
Promise object has four states -
1. Pending - Initial state of promise. This state represents that the promise has neither been fulfilled nor
been rejected, it is pending.
2. Fulfilled - This state represents that the promise has been fulfilled, meaning the async operation is
completed.
3. Rejected - This state represents that the promise has been rejected for some reason, meaning the async
operation has failed.
4. Settled - This state represents that the promise has been either rejected or fulfilled.
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.
localStorage persists data even after the browser window is closed and is accessible across different
browser tabs/windows of the same origin.
sessionStorage stores data for a single browser session and is accessible only within the same tab or
window.
51. What is event delegation in JavaScript?
49. What is the difference between splice() and slice()?
48. What is the difference between JavaScript and JScript?
50. What are the four states of promise object in javascript?
Item 1
Item 2
slice(optional start parameter, optional end parameter)
splice(start, optional delete count, optional items to add)
53. 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:
52. Explain the for-in loop in JavaScript.
The for-in loop is used to loop through the properties or keys of an object. Syntax
The iteration here continues until there are no more keys left to iterate.
Output
Example
10
2
0
3
0
4
0
55
Item 3
for (key in object) {
};
// body
for (const element of arr) {
console.log(element);
}
const arr = [10, 20, 30, 40, 55];
document.getElementById("list").addEventListener
("click", function(event) {
if (event.target.nodeName === "LI" ) {
} });
console.log(event.target.textContent);
innerText
Retrieves and sets the content in plain text
We can not insert the HTML tags
It ignores the spaces.
It returns text without an inner element tag.
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
innerHTML
Retrieves and sets the content in HTML format
We can insert the HTML tags
It considers the spaces.
It returns a tag with an inner element tag.
The unshift() method adds new elements to the beginning of an array. It overwrites the original array.
The two major drawbacks are:
Cyber security 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.
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.
55. Differentiate innerText from innerHTML.
57. What is an event bubbling in JavaScript?
56. What is the unshift method in JavaScript?
54. Why should you not use innerHTML in JavaScript?
Syntax
array.unshift(item1, item2, ..., itemX)
Run Code >>
The 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.
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.
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.
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.
Hoisting refers to the process whereby the interpreter appears to move the declaration of functions,
variables, classes, or imports to the top of their scope, before execution of the code. Hence, we can use the
function or a variable before declaration.
58. What is hoisting in JS?
60. What is Negative Infinity?
59. What is a debounce function?
Output
Example
undefined
// use demo variable before declaring
console.log(demo);
// declare and initialize demo variable
var demo = 5;
HTML to PDF
Read More:
JavaScript Developer Salary
How to Become a Full Stack JavaScript Developer?
I hope these questions and answers will help you to crack your
JavaScript Interview. These interview questions have been taken from
our newly released eBook JavaScript Interview Questions & Answers.
This book 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.
In a JavaScript interview, you can expect a mix of theoretical questions to assess your understanding of
language fundamentals and practical coding problems to evaluate your problem-solving skills. Questions
may cover topics such as closures, event handling, object manipulation, asynchronous programming, and
JavaScript frameworks.
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.
To prepare for a JavaScript programming interview, it's crucial to have a solid understanding of fundamental
concepts such as variables, data types, functions, and control flow. Additionally, practice coding exercises,
familiarize yourself with common JavaScript libraries and frameworks, and review advanced topics such as
closures, prototypes, and asynchronous programming.
Summary
Buy this eBook at a Discounted Price!
FAQs
Q1. How should I prepare for a JavaScript programming interview?
Q3. What are the different types of JavaScript interview questions?
Q2. What types of questions can I expect in a JavaScript interview?
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.
You can learn more about JavaScript through online platforms
comprehensive guides and tutorials, various certification programs, etc.
Behavioral: Explore your teamwork, communication, and problem-solving skills on past projects.
In less than 5 minutes, with our skill challenge, you can identify your
knowledge gaps and strengths in a given skill.
To ace your JavaScript interview, thoroughly understand core concepts like closures, async/await, and the
event loop and practice solving coding problems.
like ScholarHat, which provides
In JavaScript, objects and their properties are managed using dot notation or bracket notation to access,
add, modify, or delete properties. For example, object.property or object['property'] can be used to interact
with object properties.
Key features of JavaScript functions include first-class functions, meaning they can be assigned to variables,
passed as arguments, and returned from other functions, and closures, which allow functions to access
variables from their defining scope even after that scope has closed.
Q6. What are the key features of functions in JavaScript?
Q7. What are some tips for acing your JavaScript interview?
Q5. How do you handle objects and their properties in JavaScript?
Q8. Where can I find resources for learning more about Javascript?
Q4. What are some common pitfalls to avoid during JavaScript interviews?
Take our Javascript skill challenge to evaluate yourself!
GET FREE CHALLENGE

More Related Content

Similar to JavaScript Interview Questions PDF By ScholarHat (20)

PPTX
Introduction to JavaScript - Web Programming
tyfeng7
 
PPTX
Learning space presentation1 learn Java script
engmk83
 
PDF
13 javascript techniques to improve your code
Surendra kumar
 
PPTX
Full Stack Online Course in Marathahalli| AchieversIT
AchieversIT
 
PPTX
JAVASCRIPT PPT [Autosaved].pptx
AchieversIT
 
PPTX
Cordova training : Day 3 - Introduction to Javascript
Binu Paul
 
PPTX
JavaScript.pptx
Govardhan Bhavani
 
PPTX
Javascript
Sheldon Abraham
 
PPTX
Introduction to JavaScript Programming
Raveendra R
 
PDF
JavaScript: Core Part
維佋 唐
 
PDF
internet Chapter 4-JavascripPrepare a ppt of video compression techniques bas...
wabii3179com
 
PDF
1669958779195.pdf
venud11
 
PDF
Comprehensive JavaScript Cheat Sheet for Quick Reference and Mastery
pavanbackup22
 
PDF
JavaScript Cheatsheets with easy way .pdf
ranjanadeore1
 
PDF
JavaScript Programming
Sehwan Noh
 
PPTX
Web programming
Leo Mark Villar
 
PPT
Introduction to Javascript
Amit Tyagi
 
PPTX
Pawangvvhgvhg hbhvhhhhvhjjkvhvghvhgh.pptx
ramtiwari7081
 
PPT
Java script final presentation
Adhoura Academy
 
PDF
Advanced JavaScript - Internship Presentation - Week6
Devang Garach
 
Introduction to JavaScript - Web Programming
tyfeng7
 
Learning space presentation1 learn Java script
engmk83
 
13 javascript techniques to improve your code
Surendra kumar
 
Full Stack Online Course in Marathahalli| AchieversIT
AchieversIT
 
JAVASCRIPT PPT [Autosaved].pptx
AchieversIT
 
Cordova training : Day 3 - Introduction to Javascript
Binu Paul
 
JavaScript.pptx
Govardhan Bhavani
 
Javascript
Sheldon Abraham
 
Introduction to JavaScript Programming
Raveendra R
 
JavaScript: Core Part
維佋 唐
 
internet Chapter 4-JavascripPrepare a ppt of video compression techniques bas...
wabii3179com
 
1669958779195.pdf
venud11
 
Comprehensive JavaScript Cheat Sheet for Quick Reference and Mastery
pavanbackup22
 
JavaScript Cheatsheets with easy way .pdf
ranjanadeore1
 
JavaScript Programming
Sehwan Noh
 
Web programming
Leo Mark Villar
 
Introduction to Javascript
Amit Tyagi
 
Pawangvvhgvhg hbhvhhhhvhjjkvhvghvhgh.pptx
ramtiwari7081
 
Java script final presentation
Adhoura Academy
 
Advanced JavaScript - Internship Presentation - Week6
Devang Garach
 

More from Scholarhat (20)

PDF
React Redux Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
React Redux Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
React Router Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Java Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Java Interview Questions for 10+ Year Experienced PDF By ScholarHat
Scholarhat
 
PDF
Infosys Angular Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
DBMS Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
API Testing Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
System Design Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Python Viva Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Linux Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Kubernetes Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Collections in Java Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
CI CD Pipeline Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Azure DevOps Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
TypeScript Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
UIUX Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Python Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
OOPS JavaScript Interview Questions PDF By ScholarHat
Scholarhat
 
React Redux Interview Questions PDF By ScholarHat
Scholarhat
 
React Redux Interview Questions PDF By ScholarHat
Scholarhat
 
React Router Interview Questions PDF By ScholarHat
Scholarhat
 
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
Java Interview Questions PDF By ScholarHat
Scholarhat
 
Java Interview Questions for 10+ Year Experienced PDF By ScholarHat
Scholarhat
 
Infosys Angular Interview Questions PDF By ScholarHat
Scholarhat
 
DBMS Interview Questions PDF By ScholarHat
Scholarhat
 
API Testing Interview Questions PDF By ScholarHat
Scholarhat
 
System Design Interview Questions PDF By ScholarHat
Scholarhat
 
Python Viva Interview Questions PDF By ScholarHat
Scholarhat
 
Linux Interview Questions PDF By ScholarHat
Scholarhat
 
Kubernetes Interview Questions PDF By ScholarHat
Scholarhat
 
Collections in Java Interview Questions PDF By ScholarHat
Scholarhat
 
CI CD Pipeline Interview Questions PDF By ScholarHat
Scholarhat
 
Azure DevOps Interview Questions PDF By ScholarHat
Scholarhat
 
TypeScript Interview Questions PDF By ScholarHat
Scholarhat
 
UIUX Interview Questions PDF By ScholarHat
Scholarhat
 
Python Interview Questions PDF By ScholarHat
Scholarhat
 
OOPS JavaScript Interview Questions PDF By ScholarHat
Scholarhat
 
Ad

Recently uploaded (20)

PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
Ad

JavaScript Interview Questions PDF By ScholarHat

  • 1. JavaScript Interview Questions and Answer(Fresher + Experience) Are you gearing up for a JavaScript interview? Whether you're a seasoned developer or a passionate fresher, mastering the right questions can make all the difference. In this comprehensive guide, we'll unlock the secrets to acing your JavaScript interview with a curated selection of the best JavaScript interview questions and answers for 2024. 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. This article contains the most commonly asked JavaScript interview questions and answers in a JavaScript or front-end technologies Interview. Why JavaScript? Javascript Interview Questions For Freshers
  • 2. 1. What is JavaScript? Ans. JavaScript is an object-based programming language, mostly used as a client-side programming language with the HTML page to add some behavior for it. 2. What is ECMAScript? Ans. 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. 3. Which data types are supported by JavaScript? Watch the Video - Introduction to ECMA Script Major Advantages of using the JavaScript Full integration with HTML/CSS. Supported by all major browsers which are enabled by default. 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. 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 some event while the user clicks on the mouse or by using 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).
  • 3. Ans. Consider the below example Watch the Video - Data Type in JavaScript | Primitive and Non Primitive Data Type Now in the console, we will get a message that x is ‘undefined’ which means the variable is declared and memory is created but the value is not assigned to it. In this case, you will get a message like ‘not defined’ because the variable y is not created, and memory is not allocated for it and we try to reference the variable. Ans. JavaScript variables are dynamically typed, which means there is a data type but it will not be bound to a particular type, For example, while initializing the variable it can be string type but later It can also be assigned to a numeric value. Two types of data types are being supported which are primitive data types and non-primitive data types. Below are some of the data types supported by JavaScript. The data types supported by JavaScript are: Undefined Null Boolean Object String Symbol Number 4. What is the difference between undefined and not defined? console.log(y) var x; console.log(x);
  • 4. 7. What is the strict mode? Ans. “use strict” is not a statement but a literal expression which is supported by ECMAScript version 5. This statement instructs the browser to use the strict mode, which is a safer future in JavaScript. It will eliminate 6. What is the instanceof operator? Ans. instanceof operator checks whether the object is an instance of a class or not. 5. What is the use of typeof operator? Ans. The typeof is 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". It will also consider inheritance It will print the number in the console Here, arr is an array, but it also belongs to the object, because array prototypal inherits from the object. From the above code if the type of x is a number, so from the expression it will print true in the console. var x=10; console.log(typeof (x)) var x = 10; console.log(typeof (x) == 'number') function Country(name){this.name=name}; var country = new Country("India"); console.log(country instanceof Country) // return true let arr = ['apple', 'orange', 'grapes']; console.log(arr instanceof Array); //prints true in console console.log(arr instanceof Object); //prints true in console
  • 5. local scope The “use strict” expression can be in global scope as well as local scope Global scope The above statement will give an error because in strict mode the variable should be declared before it is used. some JavaScript silent errors. The strict mode applies to the entire script or the individual functions and it doesn't apply to the block statements or code which is enclosed by the curly braces {}. Attempting to apply it to such contexts does not have any meaning. At multiple places such as eval code, functional code, event handler attributes, strings passed along with the setTimeout() and related functions are completely scripts, and invoking the strict mode in them works as expected to check the syntax vulnerabilities. Example "use strict"; x = 10; // this will give error x = 10; // This will not give error. myFunction(); const employee = { name: "Ram", age: 25 } employee.name = "Raju" // it is possible use strict"; x = 10; // this will give error Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
  • 6. 8. Explain string in JavaScript. Ans. The group of characters or textual data is called a string in JavaScript. There is no separate type for the character, even a single character will be stored as a string. In JavaScript, the string can be enclosed with single quotes or double quotes. 9. What are the differences between search() and indexOf()? Ans: The differences between search() and indexOf() methods are given below: Read More: Strings in JavaScript 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 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 m = /e/; var m = /e/; var str = "apple"; var str = "apple"; str.search(m)//return 4 var str = 'hello'; console.log(str);//print hello function myFunction() { "use strict"; y = 15; // This will give error }
  • 7. 11. What are the differences between substr() and substring()? Ans: The differences between substr() and substring() methods are given below: 10. What are the differences between indexOf() and lastIndexOf() ? Ans: 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 It will print true in the log It will print false in the log 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. str.indexOf(m)//return -1 var str = 'Hello find me test me'; str.indexOf('me') // return 11 var str = 'Hello find me test me'; str.lastIndexOf('me') // return 19 var x = "hello"; console.log((x.substr(1, 4) == "ello")) var x = "hello"; console.log((x.substring(1, 4) == "ello")) var x = "hello"; console.log((x.substring(1, 5) == "ello"))//print true in console HTML to PDF
  • 8. 14. What is the arrow function? Ans. The arrow function will support in JavaScript only after ES6 or above, it is a short way to write function expressions. 13. What is the self-executing function? Ans. 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. 12. What are the differences between an array and an object? Ans: The differences between array and object are given below: Array The array uses the numbered indexes to access the element in it Object 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 It is an ordered collection. You should use an object when you want the element name to be a string It is a collection of unordered properties 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. 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 })(); function add(a, b) { return a + b;
  • 9. Run Code >> Using arrow function Ans. The window object navigator is used to find the browser which is currently running the web application. Ans. We can use the window object location to redirect the user to the new page by providing the HREF URL link to be redirected. 17. What is the output of the below code? 16. How to redirect the user to a new page? 15. How to find the browser that is running the web page? var num = "10"; } console.log(add(1, 2));//3 add = (a, b) => { return a + b } console.log(add(1, 2));//3 var browsername = navigator.appName; console.log(browsername); (function () { console.log("Original Number " + num); var num = "50"; // This is the inner variable console.log("New Number " + num); })(); window.location.href="https://www.dotnettricks.com/"
  • 10. Output Original Number undefined New Number 50 <!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 Reason: You will expect the original number will take the value from the outer scope, but the salary value was undefined, because of hoisting. Ans. 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 dynamically manipulate the content and the structure of the document. When any of the HTML documents are loaded in the browser, it will become a document object which is the root element that represents the HTML document. Each DOM element has various properties and methods. and with the help of document objects, we may add dynamic content to our web page according to the required behavior. HTML: Ans. 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 19. What is BOM? 18. What is DOM?
  • 11. the browser itself. Read More: Understanding DOM and BOM 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 history object are as follows: 1. history.back() – This method loads the previous page. 2. history.forward() – This method loads the next page. 3. history.go(number) - Its number may be positive (for forwarding) or negative (for backward). It will load the provided page number. Ans.Here are the three types of errors in JavaScript: 1. Runtime errors: These are the errors that occur due to misuse of the command within the HTML language. 2. Load time errors: These errors occur while loading a web page. An example includes improper syntax errors that produce the errors dynamically. 3. Logical Errors: These errors come up because of the bad logic carried out on a function with a varied operation. Ans. 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. Ans. Timers are useful to operate a piece of code at a specific time or iterate the code in a specific interval. The same is performed by using functions like setInterval, setTimeout, and clearInterval. Timers are executed in a single thread. Therefore, they may queue up and there may be a waiting time for execution. 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 in the stated delay and only stops when canceled. The timer gets to know when to stop with the clearInterval(id) function. 24. Explain the “this” keyword. 20. What is the NaN property in JavaScript? 21. What is the usefulness of the window object? 22. What is the functioning of timers in JavaScript? 23. What are the various types of errors in JavaScript? Javascript Interview Questions for Intermediate Developers
  • 12. Ans. 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. Ans. 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 to contain 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. Ans. 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 the Deferred, scripts would delay execution of the script until the HTML parser is operating. It decreases the web pages’ loading time and they get showcased faster. The “this” keyword refers to the object that the function is a property of. The value of the “this” keyword will always depend on the object that is invoking the function. 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”. Example 26. How is DOM used in JavaScript? 27. What is the role of deferred scripts in JavaScript? 25. Explain the difference between .call() and .apply(). 28. What are the different functional components in JavaScript? var obj = { } } obj.getName(); name: "ScholarHat", getName: function(){ console.log(this.name); HTML to PDF
  • 13. 2. 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. Ans. The following DOM Methods are used to capture the HTML element and manipulate it. 1. getElementById('idname') - > This function is used to select the HTML element based on the ID property of the HTML element. Ans. Functional components 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. 29. What are the different ways to access the HTML elements in JavaScript? <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title> </title> </head> <!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>
  • 14. 3. 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. 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. 30. What is the difference between function declarations and function expressions? <!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> <style> .lblMsg { color: #000; } </style> <body> <label id="myelement" class="lblMsg"></label> <script> document.getElementsByClassName('lblMsg')[0].innerHTML = '<h3> Welcome </h3>' </script> </body> </html>
  • 15. 33. 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(). 31. What are the types of errors in javascript? There are two types of errors in javascript. 32. What is the use of a TypedArray object in JavaScript? The JavaScript TypedArray object illustrates an array like a view of an underlying binary data buffer. There are several different global properties, whose values are TypedArray constructors for specific element types. 1. 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. 2. 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. let obj1 = {message:"Hello ScholarHat"}; function display() { var arr1= [11,12,3,4,5,6,17,8,9,10]; arr1.copyWithin(2) ; document.write(arr1); } display(); 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
  • 16. 35. 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. 36. What are the advantages of JavaScript? Following are some of the advantages of JavaScript: 34. 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. 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 is executed on the client side as well as server-side also. There are a variety of Frontend 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 quite quick. Javascript Interview Questions for Experienced Developers function display() { x = 20; y = 15; z = x + y; debugger; document.write(z); document.write(a); } display(); const newSet3 = new WeakSet([obj1]); console.log(newSet3.has(obj1)); // true
  • 17. 40. Explain WeakMap in JavaScript. We know that Map 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: 37. What are the different events in JavaScript? There are many different events in JavaScript. The following are some of them: 38. Explain higher-order functions in JavaScript. Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. 39. What is the difference between exec() and test() methods in JavaScript? Click: It 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. Higher-order functions are a result of functions being first-class citizens in JavaScript. 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. 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'. const map1 = new Map(); map1.set('Value', 1); function higherOrder() { return function() { } } var x = higherOrder(); x() return "Hello ScholarHat";
  • 18. 43. 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. 42. What is the requirement of 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. 41. 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. To perform debugging, we can use any of the following approaches: Using console.log() method Using debugger keyword Example let x; let message; let obj = {name:"ScholarHat"}; const map3 = new WeakMap(); map3.set(obj, {age:2}); x = 30; // Gives reference error const map2 = new WeakMap(); map2.set('Value', 2.3); // Throws an error function anotherRandomFunc(){ message = "Hello ScholarHat"; // Throws a reference error
  • 19. 46. What is the use of history objects? The history object of a browser can be used to switch to history pages such as back and forward from the current page or another page. There are three methods of history object. 45. Is JavaScript case-sensitive language? Yes, JavaScript is a case-sensitive language. 47. 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. 44. What are the different ways to access an HTML element in JavaScript? There are mainly three ways to access an HTML element in JavaScript: 1. Using the getElementById() method: The getElementById() method takes a string as an argument and returns the HTML element with the specified ID. 2. 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. 3. Using the querySelector() method: The querySelector() method takes a CSS selector as an argument and returns the first HTML element that matches the selector. 1. history.back() - It loads the previous page. 2. history.forward() - It loads the next page. 3. history.go(number) - The number may be positive for forward, and negative for backward. It loads the given page number. Example } anotherRandomFunc(); 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();
  • 20. splice() is used to modify an array by adding, removing, or replacing elements at a specific position. slice() is used to create a new array that contains a portion of an existing array, specified by the starting and ending indices. Netscape provided the JavaScript language. Microsoft changed the name and called it JScript to avoid the trademark issue. In other words, you can say JScript is the same as JavaScript, but Microsoft provides it. Promise object has four states - 1. Pending - Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is pending. 2. Fulfilled - This state represents that the promise has been fulfilled, meaning the async operation is completed. 3. Rejected - This state represents that the promise has been rejected for some reason, meaning the async operation has failed. 4. Settled - This state represents that the promise has been either rejected or fulfilled. 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. localStorage persists data even after the browser window is closed and is accessible across different browser tabs/windows of the same origin. sessionStorage stores data for a single browser session and is accessible only within the same tab or window. 51. What is event delegation in JavaScript? 49. What is the difference between splice() and slice()? 48. What is the difference between JavaScript and JScript? 50. What are the four states of promise object in javascript? Item 1 Item 2 slice(optional start parameter, optional end parameter) splice(start, optional delete count, optional items to add)
  • 21. 53. 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: 52. Explain the for-in loop in JavaScript. The for-in loop is used to loop through the properties or keys of an object. Syntax The iteration here continues until there are no more keys left to iterate. Output Example 10 2 0 3 0 4 0 55 Item 3 for (key in object) { }; // body for (const element of arr) { console.log(element); } const arr = [10, 20, 30, 40, 55]; document.getElementById("list").addEventListener ("click", function(event) { if (event.target.nodeName === "LI" ) { } }); console.log(event.target.textContent);
  • 22. innerText Retrieves and sets the content in plain text We can not insert the HTML tags It ignores the spaces. It returns text without an inner element tag. 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 innerHTML Retrieves and sets the content in HTML format We can insert the HTML tags It considers the spaces. It returns a tag with an inner element tag. The unshift() method adds new elements to the beginning of an array. It overwrites the original array. The two major drawbacks are: Cyber security 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. 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. 55. Differentiate innerText from innerHTML. 57. What is an event bubbling in JavaScript? 56. What is the unshift method in JavaScript? 54. Why should you not use innerHTML in JavaScript? Syntax array.unshift(item1, item2, ..., itemX)
  • 23. Run Code >> The 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. 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. 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. 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. Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables, classes, or imports to the top of their scope, before execution of the code. Hence, we can use the function or a variable before declaration. 58. What is hoisting in JS? 60. What is Negative Infinity? 59. What is a debounce function? Output Example undefined // use demo variable before declaring console.log(demo); // declare and initialize demo variable var demo = 5; HTML to PDF
  • 24. Read More: JavaScript Developer Salary How to Become a Full Stack JavaScript Developer? I hope these questions and answers will help you to crack your JavaScript Interview. These interview questions have been taken from our newly released eBook JavaScript Interview Questions & Answers. This book 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. In a JavaScript interview, you can expect a mix of theoretical questions to assess your understanding of language fundamentals and practical coding problems to evaluate your problem-solving skills. Questions may cover topics such as closures, event handling, object manipulation, asynchronous programming, and JavaScript frameworks. 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. To prepare for a JavaScript programming interview, it's crucial to have a solid understanding of fundamental concepts such as variables, data types, functions, and control flow. Additionally, practice coding exercises, familiarize yourself with common JavaScript libraries and frameworks, and review advanced topics such as closures, prototypes, and asynchronous programming. Summary Buy this eBook at a Discounted Price! FAQs Q1. How should I prepare for a JavaScript programming interview? Q3. What are the different types of JavaScript interview questions? Q2. What types of questions can I expect in a JavaScript interview?
  • 25. 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. You can learn more about JavaScript through online platforms comprehensive guides and tutorials, various certification programs, etc. Behavioral: Explore your teamwork, communication, and problem-solving skills on past projects. In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill. To ace your JavaScript interview, thoroughly understand core concepts like closures, async/await, and the event loop and practice solving coding problems. like ScholarHat, which provides In JavaScript, objects and their properties are managed using dot notation or bracket notation to access, add, modify, or delete properties. For example, object.property or object['property'] can be used to interact with object properties. Key features of JavaScript functions include first-class functions, meaning they can be assigned to variables, passed as arguments, and returned from other functions, and closures, which allow functions to access variables from their defining scope even after that scope has closed. Q6. What are the key features of functions in JavaScript? Q7. What are some tips for acing your JavaScript interview? Q5. How do you handle objects and their properties in JavaScript? Q8. Where can I find resources for learning more about Javascript? Q4. What are some common pitfalls to avoid during JavaScript interviews? Take our Javascript skill challenge to evaluate yourself! GET FREE CHALLENGE