Javascriptinterviewquestions 240713104909 d9bedd8b (1)
Javascriptinterviewquestions 240713104909 d9bedd8b (1)
+ 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.
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. This article contains the most commonly asked JavaScript interview questions and answers in a
JavaScript or front-end technologies Interview.
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.
React to a user action, like running some event while the user clicks on the mouse or by using the
keyboard.
Get and Set cookies and handle the client-side storage (local and session storage).
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.
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.
Undefined
Null
Boolean
Object
String
Symbol
Number
Watch the Video - Data Type in JavaScript | Primitive and Non Primitive Data Type
var x;
console.log(x);
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.
console.log(y)
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.
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".
var x=10;
console.log(typeof (x))
var x = 10;
console.log(typeof (x) == 'number')
From the above code if the type of x is a number, so from the expression it will print true in the console.
function Country(name){this.name=name};
var country = new Country("India");
console.log(country instanceof Country) // return true
Here, arr is an array, but it also belongs to the object, because array prototypal inherits from the object.
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
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
Global scope
local scope
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
function myFunction() {
"use strict";
y = 15; // This will give error
}
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.
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/;
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
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"))
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
12. What are the differences between an array and an object?
Ans: The differences between array and object are given below:
Array Object
The array uses the numbered indexes to access the The object uses the named indexes to access the
element in it members in it.
You should use an array when you want the element You should use an object when you want the
name to be a number element name to be a string
It is an ordered collection. It is a collection of unordered properties
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.
(function ()
{
//function body
})();
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
15. How to find the browser that is running the web page?
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.
window.location.href="https://www.dotnettricks.com/"
(function () {
console.log("Original Number " + num);
var num = "50"; // This is the inner variable
console.log("New Number " + num);
})();
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:
<!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 represents HTML as a tree structure of tags. Here’s how it looks in the browser inspect the element
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
the browser itself.
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.
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:
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.
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.
Example
var obj = {
name: "ScholarHat",
getName: function(){
console.log(this.name);
} }
obj.getName();
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”.
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.
HTML to PDF
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?
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.
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.
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.
31. What are the types of errors in javascript?
There are two types of errors in javascript.
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.
function display()
{
var arr1= [11,12,3,4,5,6,17,8,9,10];
arr1.copyWithin(2) ;
document.write(arr1);
}
display();
function display() { x
= 20; y = 15; z = x + y;
debugger;
document.write(z);
document.write(a);
}
display();
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.
37. What are the different events in JavaScript?
There are many different events in JavaScript. The following are some of them:
function higherOrder() {
return function() {
return "Hello ScholarHat";
}
}
var x = higherOrder();
x()
39. What is the difference between exec() and test() methods in JavaScript?
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'.
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.
Example
let x;
function anotherRandomFunc(){
message = "Hello ScholarHat"; // Throws a reference error
let message;
}
anotherRandomFunc();
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.
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();
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.
slice() is used to create a new array that contains a portion of an existing array, specified by the starting
and ending indices.
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.
Item 1
Item 2
Item 3
document.getElementById("list").addEventListener
("click", function(event) {
if (event.target.nodeName === "LI" ) {
console.log(event.target.textContent);
} });
The iteration here continues until there are no more keys left to iterate.
Example
Output
10
2
0
3
0
4
0
53.
55
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
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.
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 returns text without an inner element tag. 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.
Syntax
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.
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.
Example
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
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.
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.
HTML to PDF
Read More:
JavaScript Developer Salary
How to Become a Full Stack JavaScript Developer?
Summary
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.
FAQs
Q1. How should I prepare for a JavaScript programming interview?
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.
Q4. What are some common pitfalls to avoid during JavaScript interviews?
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.
Q7. What are some tips for acing your JavaScript interview?
To ace your JavaScript interview, thoroughly understand core concepts like closures, async/await, and the
event loop and practice solving coding problems.
Q8. Where can I find resources for learning more about Javascript?
You can learn more about JavaScript through online platforms like ScholarHat, which provides
comprehensive guides and tutorials, various certification programs, etc.