DSA with JS - Self Paced JS Tutorial JS Exercise JS Interview Questions JS Array JS String
JavaScript Interview Questions and Answers
Last Updated : 15 Oct, 2024
JavaScript (JS) is the most popular lightweight, scripting, and interpreted
programming language. It was developed by Brendan Eich in 1995.
JavaScript is well-known as a scripting language for web pages, mobile
apps, web servers, and many other platforms. It is essential for
both front-end and back-end developers to have a strong command of
JavaScript, as many job roles require fluency in this language.
Below, we have compiled the Top 45+ JavaScript Interview Questions and
Answers tailored for both freshers and experienced developers with 3, 5,
and 8 years of experience. Here, we will cover everything, including Core
JavaScript Concepts, ES6+ features, DOM manipulation, asynchronous
JavaScript, error handling, JavaScript frameworks and libraries, and more,
that will surely help you crack your next JavaScript interview.
JavaScript Interview Questions
Note: Before proceeding to learn JavaScript interview questions and
answers, if you are completely new to the language, we recommend
building a solid foundation first by exploring our free JavaScript
Tutorial
Open In App
Table of Content
JavaScript Interview Questions for Freshers
JavaScript Intermediate Interview Questions
JavaScript Interview Questions for Experienced
JavaScript Interview Questions for Freshers
Let’s discuss some common questions that you should prepare for the
interviews. These questions will be helpful in clearing the interviews
specially for the frontend development role.
1. What are the differences between Java and JavaScript?
Java is an object Oriented Programming language while JavaScript is a
client-side scripting language. Both of them are totally different from each
other.
Java: It is one of the most popular programming languages. It is an
object-oriented programming language and has a virtual machine
platform that allows you to create compiled programs that run on
nearly every platform. Java promised, “Write Once, Run Anywhere”.
JavaScript: It is a light-weighted programming language (“scripting
language”) for developing interactive web pages. It can insert dynamic
text into the HTML elements. JavaScript is also known as the browser’s
language.
To give yourself an extra edge, consider taking our JavaScript Course,
which not only covers core topics but also provides interview preparation
tips, practice problems, and insights from industry experts.
2. What are Data Types in JavaScript?
JavaScript data types are categorized into two parts i.e. primitive and non-
primitive types.
Open In App
Primitive Data Type: The predefined data types provided by JavaScript
language are known as primitive data type. Primitive data types are
also known as in-built data types.
Numbers
Strings
Boolean
Symbol
Undefined
Null
BigInt
Non-Premitive Data Type: The data types that are derived from
primitive data types are known as non-primitive data types. It is also
known as derived data types or reference data types.
Objects
Functions
Arrays
3. Which symbol is used for comments in JavaScript?
Comments prevent the execution of statements. Comments are ignored
while the compiler executes the code. There are two type of symbols to
represent comments in JavaScript:
Double slash: It is known as a single-line comment.
// Single line comment
Slash with Asterisk: It is known as a multi-line comment.
/*
Multi-line comments
. . .
*/
Open In App
4. What would be the result of 3+2+”7″?
Here, 3 and 2 behave like an integer, and “7” behaves like a string. So 3
plus 2 will be 5. Then the output will be 5+”7″ = 57.
5. What is the use of the isNaN function?
The number isNan function determines whether the passed value is NaN
(Not a number) and is of the type “Number”. In JavaScript, the value NaN
is considered a type of number. It returns true if the argument is not a
number, else it returns false.
6. Which is faster in JavaScript and ASP script?
JavaScript is faster compared to ASP Script. JavaScript is a client-side
scripting language and does not depend on the server to execute. The
ASP script is a server-side scripting language always dependable on the
server.
7. What is negative infinity?
The negative infinity is a constant value represents the lowest available
value. It means that no other number is lesser than this value. It can be
generate using a self-made function or by an arithmetic operation.
JavaScript shows the NEGATIVE_INFINITY value as -Infinity.
8. Is it possible to break JavaScript Code into several lines?
Yes, it is possible to break the JavaScript code into several lines in a string
statement. It can be broken by using the backslash n ‘\n’.
For example:
console.log("A Online Computer Science Portal\n for Geeks")
Open In App
The code-breaking line is avoid by JavaScript which is not preferable.
let gfg= 10, GFG = 5,
Geeks =
gfg + GFG;
9. Which company developed JavaScript?
Netscape developed JavaScript and was created by Brenden Eich in the
year of 1995.
10. What are undeclared and undefined variables?
Undefined: It occurs when a variable is declare but not assign any
value. Undefined is not a keyword.
Undeclared: It occurs when we try to access any variable which is not
initialize or declare earlier using the var or const keyword. If we use
‘typeof’ operator to get the value of an undeclare variable, we will face
the runtime error with the return value as “undefined”. The scope of the
undeclare variables is always global.
11. Write a JavaScript code for adding new elements dynamically.
html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<button onclick="create()">
Click Here!
</button>
<script>
function create() {
let geeks =Open In App
document.createElement('geeks');
geeks.textContent = "Geeksforgeeks";
geeks.setAttribute('class', 'note');
document.body.appendChild(geeks);
}
</script>
</body>
</html>
12. What are global variables? How are these variables declared, and
what are the problems associated with them?
In contrast, global variables are the variables that define outside of
functions. These variables have a global scope, so they can be used by
any function without passing them to the function as parameters.
Example:
javascript
let petName = "Rocky"; // Global Variable
myFunction();
function myFunction() {
console.log("Inside myFunction - Type of petName:", typeof
petName);
console.log("Inside myFunction - petName:", petName);
}
console.log("Outside myFunction - Type of petName:", typeof
petName);
console.log("Outside myFunction - petName:", petName);
Output
Inside myFunction - Type of petName: string
Inside myFunction - petName: Rocky
Outside myFunction - Type of petName: string
Outside myFunction - petName: Rocky
Open In App
It is difficult to debug and test the code that relies on global variables.
13. What do you mean by NULL in JavaScript?
The NULL value represents that no value or no object. It is known as
empty value/object.
14. How to delete property-specific values?
The delete keyword deletes the whole property and all the values at once
like
let gfg={Course: "DSA", Duration:30};
delete gfg.Course;
15. What is a prompt box?
The prompt box is a dialog box with an optional message prompting the
user to input some text. It is often used if the user wants to input a value
before entering a page. It returns a string containing the text entered by
the user, or null.
16. What is the ‘this’ keyword in JavaScript?
Functions in JavaScript are essential objects. Like objects, it can be
assign to variables, pass to other functions, and return from functions.
And much like objects, they have their own properties. ‘this’ stores the
current execution context of the JavaScript program. Thus, when it use
inside a function, the value of ‘this’ will change depending on how the
function is defined, how it is invoked, and the default execution context.
17. Explain the working of timers in JavaScript. Also explain the
drawbacks of using the timer, if any.
Open In App
The timer executes some specific code at a specific time or any small
amount of code in repetition to do that you need to use the functions
setTimout, setInterval, and clearInterval. If the JavaScript code sets the
timer to 2 minutes and when the times are up then the page displays an
alert message “times up”. The setTimeout() method calls a function or
evaluates an expression after a specified number of milliseconds.
18. What is the difference between ViewState and SessionState?
ViewState: It is specific to a single page in a session.
SessionState: It is user specific that can access all the data on the web
pages.
19. How to submit a form using JavaScript?
You can use document.form[0].submit()method to submit the form in
JavaScript.
20. Does JavaScript support automatic type conversion?
Yes, JavaScript supports automatic type conversion.
JavaScript Intermediate Interview Questions
21. What are all the looping structures in JavaScript?
while loop: A while loop is a control flow statement that allows code to
be executed repeatedly based on a given Boolean condition. The while
loop can be thought of as a repeating if statement.
for loop: A for loop provides a concise way of writing the loop
structure. Unlike a while loop, for statement consumes the
initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping.
Open In App
do while: A do-while loop is similar to while loop with the only
difference that it checks the condition after executing the statements,
and therefore is an example of Exit Control Loop.
22. How can the style/class of an element be changed?
To change the style/class of an element there are two possible ways. We
use document.getElementByID method
document.getElementById("myText").style.fontSize = "16px;
document.getElementById("myText").className = "class";
23. Explain how to read and write a file using JavaScript?
The readFile() functions is used for reading operation.
readFile( Path, Options, Callback)
The writeFile() functions is used for writing operation.
writeFile( Path, Data, Callback)
24. What is called Variable typing in JavaScript ?
The variable typing is the type of variable used to store a number and
using that same variable to assign a “string”.
Geeks = 42;
Geeks = "GeeksforGeeks";
25. How to convert the string of any base to integer in JavaScript?
Open In App
In JavaScript, parseInt() function is used to convert the string to an
integer. This function returns an integer of base which is specified in
second argument of parseInt() function. The parseInt() function returns
Nan (not a number) when the string doesn’t contain number.
26. Explain how to detect the operating system on the client machine?
To detect the operating system on the client machine, one can simply use
navigator.appVersion or navigator.userAgent property. The Navigator
appVersion property is a read-only property and it returns the string that
represents the version information of the browser.
27. What are the types of Pop up boxes available in JavaScript?
There are three types of pop boxes available in JavaScript.
Alert
Confirm
Prompt
28. What is the difference between an alert box and a confirmation box?
An alert box will display only one button which is the OK button. It is used
to inform the user about the agreement has to agree. But a Confirmation
box displays two buttons OK and cancel, where the user can decide to
agree or not.
29. What is the disadvantage of using innerHTML in JavaScript?
There are lots of disadvantages of using the innerHTML in JavaScript as
the content will replace everywhere. If you use += like “innerHTML =
innerHTML + ‘html’” still the old content is replaced by HTML. It preserves
event handlers attached to any DOM elements.
30. What is the use of void(0) ?Open In App
The void(0) is used to call another method without refreshing the page
during the calling time parameter “zero” will be passed.
For further reading, check out our dedicated article on Intermediate
Javascript Interview Questions. Inside, you’ll discover over 20
questions with detailed answers.
JavaScript Interview Questions for Experienced
31. What is the ‘Strict’ mode in JavaScript and how can it be enabled?
Strict Mode is a new feature in ECMAScript 5 that allows you to place a
program or a function in a “strict” operating context. This strict context
prevents certain actions from being taken and throws more exceptions.
The statement “use strict” instructs the browser to use the Strict mode,
which is a reduced and safer feature set of JavaScript.
32. How to get the status of a CheckBox?
The DOM Input Checkbox Property is used to set or return the checked
status of a checkbox field. This property is used to reflect the HTML
Checked attribute.
document.getElementById("GFG").checked;
If the CheckBox is checked then it returns True.
33. How to explain closures in JavaScript and when to use it?
The closure is created when a child functions to keep the environment of
the parent’s scope even after the parent’s function has already executed.
The Closure is a locally declared variable related to a function. The
closure will provide better control over the code when using them.
Open In App
JavaScript
// Explanation of closure
function foo() {
let b = 1;
function inner() {
return b;
}
return inner;
}
let get_func_inner = foo();
console.log(get_func_inner());
console.log(get_func_inner());
console.log(get_func_inner());
Output
1
1
1
34. What is the difference between call() and apply() methods ?
Both methods are used in a different situation
call() Method: It calls the method, taking the owner object as
argument. The keyword this refers to the ‘owner’ of the function or the
object it belongs to. We can call a method that can be used on different
objects.
apply() Method: The apply() method is used to write methods, which
can be used on different objects. It is different from the function call()
because it takes arguments as an array.
35. How to target a particular frame from a hyperlink in JavaScript ?
This can be done by using the target attribute in the hyperlink. Like
Open In App
<a href="/geeksforgeeks.htm" target="newframe">New Page</a>
36. Write the errors shown in JavaScript?
There are three different types of errors in JavaScript.
Syntax error: A syntax error is an error in the syntax of a sequence of
characters or tokens that are intended to be written in a particular
programming language.
Logical error: It is the most difficult error to be traced as it is the error
on the logical part of the coding or logical error is a bug in a program
that causes to operate incorrectly and terminate abnormally.
Runtime Error: A runtime error is an error that occurs during the
running of the program, also known as an exception.
37. What is the difference between JavaScript and Jscript?
JavaScript
It is a scripting language developed by Netscape.
It is used to design client and server-side applications.
It is completely independent of Java language.
Jscript
It is a scripting language developed by Microsoft.
It is used to design active online content for the word wide Web.
38. What does var myArray = [[]]; statement declares?
In JavaScript, this statement is used to declare a two-dimensional array.
39. How many ways an HTML element can be accessed in JavaScript
code?
Open In App
There are four possible ways to access HTML elements in JavaScript
which are:
getElementById() Method: It is used to get the element by its id name.
getElementsByClass() Method: It is used to get all the elements that
have the given classname.
getElementsByTagName() Method: It is used to get all the elements
that have the given tag name.
querySelector() Method: This function takes CSS style selector and
returns the first selected element.
40. What is the difference between innerHTML & innerText?
The innerText property sets or returns the text content as plain text of the
specified node, and all its descendants whereas the innerHTML property
sets or returns the plain text or HTML contents in the elements. Unlike
innerText, inner HTML lets you work with HTML rich text and doesn’t
automatically encode and decode text.
41. What is an event bubbling in JavaScript?
Consider a situation an element is present inside another element and
both of them handle an event. When an event occurs in bubbling, the
innermost element handles the event first, then the outer, and so on.
For further reading, check out our dedicated article on Advanced
Javascript Interview Questions. Inside, you’ll discover 20+ questions
with detailed answers.
JavaScript MCQ Coding Interview Questions
42. What will be the output of the following code?
JavaScript Open In App
(function() {
var a = b = 5;
})();
console.log(typeof a);
console.log(typeof b);
Options:
1. typeof a: "undefined"
typeof b: "number"
2. typeof a: “number”
typeof b: “number”
3. typeof a: “undefined”
typeof b: “undefined”
4. typeof a: “number”
typeof b: “undefined”
Answer:
Explanation:
Inside the IIFE, b = 5 is treated as a global variable (since no var, let,
or const keyword is used).
However, a is declared with var and is local to the function, so it
is undefined outside.
43. What will be logged in the console?
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);
Options: Open In App
1. true, true
2. true, false
3. false, true
4. false, false
Answer:
Explanation:
1 < 2 < 3 is evaluated as (1 < 2) < 3, which becomes true < 3. In
JavaScript, true is treated as 1, so 1 < 3 is true.
3 > 2 > 1 becomes (3 > 2) > 1, which results in true > 1.
Since true is 1, the comparison becomes 1 > 1, which is false.
44. What will be the output of the following code?
const obj1 = { a: 1 };
const obj2 = { a: 1 };
console.log(obj1 == obj2);
console.log(obj1 === obj2);
Options:
1. true, true
2. false, false
3. false, true
4. True, false
Answer:
Open In App
2
Explanation:
In JavaScript, objects are compared by reference, not by value.
Since obj1 and obj2 point to different memory locations,
both == and === comparisons return false.
45. What will be the result of the following code?
let x = 10;
let y = (x++, x + 1, x * 2);
console.log(y);
1. 11
2. 22
3. 12
4. 20
Answer:
Explanation:
The comma operator ( , ) evaluates all expressions but returns the
value of the last one.
x++ increments x to 11, but the result of this expression is the
original 10.
x + 1 becomes 11 + 1 = 12, and the final expression x * 2 evaluates
to 11 * 2 = 22, which is assigned to y.
46. What will be the output of this asynchronous JavaScript code?
Open In App
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
1. A D B C
2. A B C D
3. A D C B
4. A C D B
Answer:
Explanation:
The synchronous code runs first, logging 'A' and 'D'.
Promise callbacks (microtasks) are executed
before setTimeout (macrotasks). So 'C' is logged before 'B'.
47. What will be the output of this recursive function?
function foo(num) {
if (num === 0) return 1;
return num + foo(num - 1);
}
console.log(foo(3));
1. 3
2. 6
3. 7
4. 10
Open In App
Answer:
3
Explanation:
The function works recursively:
foo(3) →3 + foo(2)
foo(2) →2 + foo(1)
foo(1) →1 + foo(0)
foo(0) →1
So, the total is 3 + 2 + 1 + 1 = 7.
48. What will be printed in the following code?
let a = [1, 2, 3];
let b = a;
b.push(4);
console.log(a);
console.log(b);
Options:
1. [1, 2, 3]
[1, 2, 3, 4]
2. [1, 2, 3, 4]
[1, 2, 3, 4]
3. [1, 2, 3]
[1, 2, 3]
4. [1, 2, 3, 4]
[1, 2, 3]
Answer:
2
Open In App
Explanation:
In JavaScript, arrays are reference types. Both a and b point to the
same array in memory. Modifying b also affects a.
49. What will be logged by the following code?
function test() {
console.log(this);
}
test.call(null);
1. null
2. undefined
3. Window or global object
4. TypeError
Answer:
Explanation:
In non-strict mode, calling a function with this set to null defaults to
the global object (Window in browsers or global in Node.js).
Javascript Frequently Asked Questions – FAQs
What are the primitive data types in JavaScript?
There are six: number, string, boolean, null, undefined, and symbol.
Open In App
How do you explain ‘hoisting’ in JavaScript?
Variable declarations are hoisted to the top of their scope, allowing
access before their actual definition.
What’s the difference between ‘===’ and ‘==’?
=== checks for strict equality (value and type), while == performs type
coercion before comparison.
How can you loop through the elements of an array?
Use a for loop or a forEach method to iterate over each item in the
array.
Are you feeling lost in OS, DBMS, CN, SQL, and DSA chaos? Our Complete
Interview Preparation Course is your solution! Trusted by over 100,000+
Geeks, it covers all essential topics, ensuring you're well-prepared for
technical challenges. Join the ranks of successful candidates and unlock
your placement potential. Enroll now and start your journey to a
successful career!
Open In App
S Saby… Follow 79
Previous Article Next Article
CSS Interview Questions and Answers JavaScript Interview Questions and
Answers (2024) - Intermediate Level
Similar Reads
Kafka Interview Questions - Top 70+ Questions and Answers for…
Apache Kafka has become a cornerstone in modern distributed systems
and data-driven architectures. As organizations increasingly adopt real-tim…
15+ min read
Active Directory Interview Questions - Top 50+ Questions and…
Active Directory (AD) is a crucial component of modern enterprise IT
infrastructure, providing centralized authentication, authorization, and…
15+ min read
Teacher Interview Questions - Top 70 Questions and Answers for…
Teaching is a noble profession that requires a unique blend of knowledge,
skills, and passion. As educators, teachers play a crucial role in shaping th…
15+ min read
JavaScript String Interview Questions and Answers
JavaScript (JS) is the world's most popular lightweight programming
language, created by Brendan Eich in 1995. It is a must-have skill for web…
14 min read
JavaScript Interview Questions and Answers (2024) - Intermediat…
Open In App
In this article, you will learn JavaScript interview questions and answers
intermediate level that are most frequently asked in interviews. Before…
6 min read
JavaScript Interview Questions and Answers (2024) - Advanced…
In this article, you will learn JavaScript interview questions and answers
Advanced level that are most frequently asked in interviews. Before…
6 min read
JavaScript Array Interview Questions and Answers
JavaScript Array Interview Questions and Answers contains the list of top
50 array based questions that are frequently asked in interviews. The…
15+ min read
Top 50 Blockchain Interview Questions and Answers
Blockchain is one of the most trending technologies out there in the tech
world. It is basically concerned with a distributed database that maintains…
15+ min read
Merge Sort Interview Questions and Answers
Merge sort is defined as a sorting algorithm that works by dividing an array
into smaller subarrays, sorting each subarray, and then merging the sorted…
4 min read
Deloitte Interview Questions and Answers for Technical Profiles
Deloitte is a leading global professional services firm with over 345,000
employees in more than 150 countries. The company offers a variety of…
13 min read
ION Group Interview Questions and Answers for Technical Profiles
ION Group is a global technology leader, providing innovative solutions for
digital transformation and delivering cutting-edge services for businesses…
12 min read
Open In App
KPMG Interview Questions and Answers for Technical Profiles
KPMG is one of the Big Four accounting firms, and it offers a variety of
technical roles in areas such as auditing, tax, consulting, and technology.…
15+ min read
Nvidia Interview Questions and Answers for Technical Profiles
Nvidia Corporation, an American technology company based in Santa Clara,
California, is a leading designer of graphics processing units (GPUs) for th…
14 min read
Qualcomm Interview Questions and Answers for Technical Profiles
Qualcomm is an American multinational semiconductor and
telecommunications equipment company that designs and markets…
15+ min read
Siemens Interview Questions and Answers for Technical Profiles
In this article we prepare for your Siemens technical interview with our
comprehensive list of interview questions and expertly crafted answers.…
15 min read
IT Auditor Interview Questions and Answers
"Unlocking Your IT Auditor Career" is your one-stop guide to ace interviews.
We've compiled a list of 30 crucial interview questions in this helpful piece,…
15+ min read
BNY Mellon Interview Questions and Answers for Technical Profiles
BNY Mellon is a huge financial company that operates all over the world and
has more than 50,000 employees. They have various technical job opening…
12 min read
Tiger Analytics Interview Questions and Answers for Technical…
Open In App
Think globally, and impact millions. That's the driving force behind Tiger
Analytics, a data-driven powerhouse leading the AI and analytics consultin…
15 min read
Site Reliability Engineering(SRE) Interview Questions and Answers
SRE, or Site Reliability Engineering, is a rapidly growing field that is essential
for ensuring the smooth operation of large-scale systems. SREs are…
13 min read
Delta X Interview Questions and Answers
Aspiring software engineers seeking to crack the code of success at DeltaX,
buckle up! This article dissects the interviews at DeltaX, offering an…
5 min read
Article Tags : Interview Questions JavaScript Web Technologies interview-preparation
+3 More
Corporate & Communications
Address:- A-143, 9th Floor, Sovereign
Corporate Tower, Sector- 136, Noida,
Uttar Pradesh (201305) | Registered
Address:- K 061, Tower K, Gulshan
Vivante Apartment, Sector 137,
Noida, Gautam Buddh Nagar, Uttar
Pradesh, 201305
Open In App
Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Careers GfG Weekly Contest
In Media Offline Classes (Delhi/NCR)
Contact Us DSA in JAVA/C++
Advertise with us Master System Design
GFG Corporate Solution Master CP
Placement Training Program GeeksforGeeks Videos
Geeks Community
Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL DSA Interview Questions
R Language Competitive Programming
Android Tutorial
Data Science & ML Web Technologies
Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning JavaScript
ML Maths TypeScript
Data Visualisation ReactJS
Pandas NextJS
NumPy NodeJs
NLP Bootstrap
Deep Learning Tailwind CSS
Python Tutorial Computer Science
Python Programming Examples GATE CS Notes
Django Tutorial Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Tutorial Digital Logic Design
Python Interview Question Engineering Maths
DevOps System Design
Git High Level Design
AWS Low Level Design
Docker Open In App UML Diagrams
Kubernetes Interview Guide
Azure Design Patterns
GCP OOAD
DevOps Roadmap System Design Bootcamp
Interview Questions
School Subjects Commerce
Mathematics Accountancy
Physics Business Studies
Chemistry Economics
Biology Management
Social Science HR Management
English Grammar Finance
Income Tax
Databases Preparation Corner
SQL Company-Wise Recruitment Process
MYSQL Resume Templates
PostgreSQL Aptitude Preparation
PL/SQL Puzzles
MongoDB Company-Wise Preparation
Companies
Colleges
Competitive Exams More Tutorials
JEE Advanced Software Development
UGC NET Software Testing
UPSC Product Management
SSC CGL Project Management
SBI PO Linux
SBI Clerk Excel
IBPS PO All Cheat Sheets
IBPS Clerk Recent Articles
Free Online Tools Write & Earn
Typing Test Write an Article
Image Editor Improve an Article
Code Formatters Pick Topics to Write
Code Converters Share your Experiences
Currency Converter Internships
Random Number Generator
Random Password Generator
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
Open In App