Top 50 interview question and answers for JavaScript

JavaScript could be a scripting or artificial language that enables you to implement advanced options on websites each time an internet page will quite simply sit there and show static info for you to seem at displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc. you’ll be able to bet that JavaScript is maybe concerned. It’s the third layer of the cake of normal net technologies, 2 of that (HTML and CSS) we’ve lived in rather more detail in alternative elements of the training space.

So, without wasting anymore time, let’s begin with our topic of FAQ, interview questions and answers!

FAQ and interview questions and answers for JavaScript:-

  1. What is JavaScript?
what is javascript

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.

2. What are the data types supported by JavaScript?

The data types supported by JavaScript are:

  • Undefined
  • Null
  • Boolean
  • String
  • Symbol
  • Number
  • Object
  •  What are the features of JavaScript?

Following are the features of JavaScript:

  • It is a lightweight, interpreted programming language.
  • It is designed for creating network-centric applications.
  • It is complementary to and integrated with Java.
  • It is an open and cross-platform scripting language.

3. Is JavaScript a case-sensitive language?

Yes, JavaScript is a case sensitive language.  The language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

4. What are the advantages of JavaScript?

advantages of javascript

Following are the advantages of using JavaScript −

  • Less server interaction − you can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
  • Immediate feedback to the visitors − they don’t have to wait for a page reload to see if they have forgotten to enter something.
  • Increased interactivity − you can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
  • Richer interfaces − you can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.

5.How can you create an object in JavaScript?

JavaScript supports Object concept very well. You can create an object using the object literal as follows −

var emp = {
name: "Daniel",
age: 23
  1. What are undeclared and undefined variables?

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

7. Write the code for adding new elements dynamically?

<script type="text/javascript"> 
    function addNode () { var newP = document. createElement("p"); 
    var textNode = document.createTextNode(" This is a new text node"); 
    newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); } 
</script> </head> 
<body> <p id="firstP">firstP<p> </body> 

8.  What are global variables? How are these variable declared?

Global variables are available throughout the length of the code so that it has no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared.


// Declare a global: globalVariable = “Test”;

The problems faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.

9. What is a prompt box?

A prompt box is a box that allows the user to enter input by providing a text box. A label and box will be provided to enter the text or number.

10. What is ‘this’ keyword in JavaScript?

‘This’ keyword refers to the object from where it was called. What is the working of timers in JavaScript?

Timers are used to execute a piece of code at a set time or repeat the code in a given interval. This is done by using the functions setTimeout, setInterval, and clearInterval.

The setTimeout(function, delay) function is used to start a timer that calls a particular function after the mentioned delay. The setInterval(function, delay) function repeatedly executes the given function in the mentioned delay and only halts when canceled. The clearInterval(id) function instructs the timer to stop.

Timers are operated within a single thread, and thus events might queue up, waiting to be executed.

12. Which symbol is used for comments in JavaScript?

// for Single line comments and
/* Multi

13. What is the difference between ViewState and SessionState?

ViewState’ is specific to a page in a session.

‘SessionState’ is specific to user-specific data that can be accessed across all web application page

14.  What is === operator?

=== is called a strict equality operator, which returns true when the two operands have the same value without conversion

15.   How you can submit a form using JavaScript?

To submit a form using JavaScript use


16. Does JavaScript support automatic type conversion?

Yes, JavaScript does support automatic type conversion. It is the common way of type conversion used by JavaScript developers

 17. How can the style/class of an element be changed?

It can be done in the following way:

document.getElementById("myText"). style. fontSize = "20";
document. getElementById ("myText"). className = "anyclass";
How to validate a form in JavaScript?
function validateform(){  
var password=document.myform.password.value;  
if (name==null || name==""){  
  alert("Name can't be blank");  
  return false;  
}else if(password.length<6){  
  alert("Password must be at least 6 characters long.");  
  return false;  
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >  
Name: <input type="text" name="name"><br/>  
Password: <input type="password" name="password"><br/>  
<input type="submit" value="register">  

18. How to validate email in JavaScript?

function validateemail()  
var atposition=x.indexOf("@");  
var dotposition=x.lastIndexOf(".");  
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){  
  alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);  
  return false;  
<form name="myform"  method="post" action="#" onsubmit="return validateemail();">  
Email: <input type="text" name="email"><br/>  
<input type="submit" value="register">  

19. What is this keyword in JavaScript?

The this keyword is a reference variable that refers to the current object. For example:

var address=    
return" "" "+this.state;    
var fetch=address.fullAddress();    

20. How can I remove a specific item from an array?

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

const array = [2, 5, 9];


const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1); // 2nd parameter means remove one item only

// array = [2, 9]

The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.

For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:

function removeItemOnce(arr, value) {
  var index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  return arr;

function removeItemAll(arr, value) {
  var i = 0;
  while (i < arr.length) {
    if (arr[i] === value) {
      arr.splice(i, 1);
    } else {
  return arr;
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))

21. Could you enumerate the various features of JavaScript?

Some important features of JavaScript are:

  • A lightweight interpreted a programming language with some object-oriented capabilities.
  • An open, cross-platform scripting language
  • Complements and integrates with the Java programming language as well as other backend technologies.
  • Designed especially for creating network-centric applications

22. Can you differentiate between let and var?

Both let and var are used for variable and method declaration in JavaScript. However, the most important difference between the two JS keywords is that while the var keyword is function scoped, the let keyword is block scoped.

23. What are the escape characters in JavaScript?

 In JavaScript, we use escape characters, typically backslash (\ \) while working with special characters, such as ampersands (&), apostrophes (‘), double quotes (“ “), and single quotes (‘ ‘). Whatever enclosed within the escape, characters get displayed by the JavaScript.

Six additional escape characters are also available in JavaScript:

\b – Backspace

\f – Form feed

\n – Newline

\r – Carriage return

\t – Horizontal tabulator

\v – Vertical tabulator

These aren’t in anyway executed in the HTML or JS code. These were originally designed for controlling fax machines, teletypes, and typewriters.

24. Please describe the most important advantages of using JavaScript?

There are several advantages to using JavaScript. Most notable amongst them are listed down as follows:

  • Enhanced interactivity – JavaScript allows creating interfaces that react when the user activates them via the keyboard or merely hovers the cursor over the same.
  • Immediate feedback – Visitors need not wait for a page reload to see if they had forgotten to enter some important details.
  • Low server interaction – JS allows validating user input before sending the webpage to the server. It means less server traffic and hence, less load on the server.
  • Rich interfaces – JS has items like drag-and-drop components and sliders to present a richer interface to the website visitors.

25. What are the different types of Error Name values in JavaScript?

There are 6 types of Error Name values. Each one of them is briefly explained as follows:

  • Eval Error – Thrown when coming across an error in eval() (Newer JS releases don’t have it)
  • Range Error – Generated when a number outside the specified range is used
  • Reference Error – It comes into play when an undeclared variable is used.
  • Syntax Error – When the incorrect syntax is used, we get this error
  • Type Error – This error is thrown when a value outside the range of data types is tried to be used.
  • URI Error – Generated due to the use of illegal characters

26. Explain the difference between function declaration and function expression?

Following are the differences between function declaration and function expression:

  • Definition – A function declared as a separate statement in the main code flow is termed the function declaration. When a function is created inside an expression or another syntax construct, it is called a function expression.
  • Strict Mode – When a function declaration is within a code block in the Strict mode, it is visible everywhere inside that block but not outside of it. This isn’t the case for a function expression.
  • Time of Use – A function expression is created when the execution reaches it. The function expression is usable only from that moment onwards. A function declaration, on the other hand, can be called before the same is defined.
  • When to Use – Function declaration offers better readability and offers more freedom in organizing the code. Function expressions are typically restricted to be used when there is a need for a conditional declaration.

27. What are the various ways of embedding JavaScript code in an HTML file?

There are 4 ways of embedding JS code within HTML documents:

Adding it between tags From an external file that is specified by the src attribute of a tag. Old browsers treat this JS code as a long HTML comment.

Typically, JS code is hidden from old browsers for solving compatibility and UI issues. Interestingly, browsers that support JavaScript will take as one-line comments.

28. Explain event bubbling and how one may prevent it

Event bubbling is the concept in which an event triggers at the deepest possible element, and triggers on parent elements in nesting order. As a result, when clicking on a child element one may exhibit the handler of the parent activating.

One way to prevent event bubbling is using event.stopPropagation() or event.cancelBubble on IE <

29. What is let keyword in JavaScript?

In addition to creating declarations for variables at the function level, ES6 lets you declare variables to belong to individual blocks (pairs of { .. }), using the let keyword.

30. What is IIFEs (Immediately Invoked Function Expressions)?

It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created:

(function IIFE(){
    console.log( "Hello!" );
// "Hello!"

This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.

31. How to compare two objects in JavaScript?

Two non-primitive values, like objects (including function and array) held by reference, so both == and === comparisons will simply check whether the references match, not anything about the underlying values.

For example, arrays are by default coerced to strings by simply joining all the values with commas (,) in between. So two arrays with the same contents would not be == equal:

var a = [1,2,3];
var b = [1,2,3];
var c = "1,2,3";

a == c;     // true
b == c;     // true
a == b;     // false

32. Could you explain the difference between ES5 and ES6

ECMAScript 5 (ES5): The 5th edition of ECMAScript, standardized in 2009. This standard has been implemented fairly completely in all modern browsers

ECMAScript 6 (ES6)/ ECMAScript 2015 (ES2015): The 6th edition of ECMAScript, standardized in 2015. This standard has been partially implemented in most modern browsers.

Here are some key differences between ES5 and ES6:

Arrow functions & string interpolation: Consider:
const greetings = (name) => {
      return `hello ${name}`;
and even:
const greetings = name => `hello ${name}`;

Const. Const works like a constant in other languages in many ways but there are some caveats. Const stands for ‘constant reference’ to a value. So with const, you can actually mutate the properties of an object being referenced by the variable. You just can’t change the reference itself.

const NAMES = [];
console.log(NAMES.length === 1); // true
NAMES = ["Steve", "John"]; // error

Block-scoped variables. The new ES6 keyword let allows developers to scope variables at the block level. Let doesn’t hoist in the same way var does.

Default parameter values Default parameters allow us to initialize functions with default values. A default is used when an argument is either omitted or undefined — meaning null is a valid value.

// Basic syntax
function multiply (a, b = 2) {
     return a * b;
multiply(5); // 10

Class Definition and Inheritance

ES6 introduces language support for classes (class keyword), constructors (constructor keyword), and the extend keyword for inheritance.

for-of operator

The for…of statement creates a loop iterating over iterable objects.

Spread Operator

For objects merging

const obj1 = { a: 1, b: 2 }
const obj2 = { a: 2, c: 3, d: 4}
const obj3 = {...obj1, ...obj2}

Promises Promises provide a mechanism to handle the results and errors from asynchronous operations. You can accomplish the same thing with callbacks, but promises provide improved readability via method chaining and succinct error handling.

const isGreater = (a, b) => {
  return new Promise ((resolve, reject) => {
    if(a > b) {
    } else {
isGreater(1, 2)
  .then(result => {
 .catch(result => {
Modules exporting & importing Consider module exporting:
const myModule = { x: 1, y: () => { console.log('This is ES5') }}
export default myModule;
and importing:
import myModule from './myModule';

34. What is the difference between anonymous and named functions?

var foo = function() { // anonymous function assigned to variable foo
    // ..

var x = function bar(){ // named function (bar) assigned to variable x 
    // ..

foo(); // actual function execution

35. What is the use of a Set object in JavaScript?

The JavaScript Set object is used to store the elements with unique values. The values can be of any type i.e. whether primitive values or object references. For example:

function display()  
var set = new Set();    
for (let elements of set) {    

36. What is the use of a WeakSet object in JavaScript?

The JavaScript WeakSet object is the type of collection that allows us to store weakly held objects. Unlike Set, the WeakSet are the collections of objects only. It doesn’t contain the arbitrary values. For example:

function display()  
var ws = new WeakSet();    
var obj1={};    
var obj2={};    
//Let's check whether the WeakSet object contains the added object    

37. What is the use of a Map object in JavaScript?

The JavaScript Map object is used to map keys to values. It stores each element as key-value pair. It operates the elements such as search, update and delete on the basis of specified key. For example:

function display()  
var wm = new WeakMap();    
var obj1 = {};    
var obj2 = {};    
var obj3= {};    
wm.set(obj1, "jQuery");    
wm.set(obj2, "AngularJS");    

38. What are the false values in JavaScript, and how can we check if a value is falsy?

Those values which become false while converting to Boolean are called falsy values.

const falsyValues = ['', 0, null, undefined, NaN, false];   

39. What do you understand by hoisting in JavaScript?

Hoisting is the default behavior of JavaScript where all the variable and function declarations are moved on top. In simple words, we can say that Hoisting is a process in which, irrespective of where the variables and functions are declared, they are moved on top of the scope. The scope can be both local and global.

40. What is BOM?

BOM stands for Browser Object Model. It provides interaction with the browser. The default object of a browser is a window. So, you can call all the functions of the window by specifying the window or directly. The window object provides various properties like document, history, screen, navigator, location, innerHeight, innerWidth,

41. What is DOM? What is the use of document object?

DOM stands for Document Object Model. A document object represents the HTML document. It can be used to access and change the content of HTML.

More Details: Document Object Model

42. What is the use of window object?

The window object is created automatically by the browser that represents a window of a browser. It is not an object of JavaScript. It is a browser object.

43. What is the use of history object?

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.

history.back() - It loads the previous page.
history.forward() - It loads the next page.
history.go(number) - The number may be positive for forward, negative for backward. It loads the given page number.

44. How to write a comment in JavaScript?

There are two types of comments in JavaScript.

Single Line Comment: It is represented by // (double forward slash)

Multi-Line Comment: Slash represents it with asterisk symbol as /* write comment here */

What are the different data types present in JavaScript?

There are two types of data types in JavaScript:

  • Primitive data types
  • Non- Primitive data types
  • Primitive data types

The primitive data types are as follows:

String: The string data type represents a sequence of characters. It is written within quotes and can be represented using a single or a double quote.


var str1 = "Hello JavaTpoint"; //using double quotes  
var str2 = 'Hello Javatpoint'; //using single quotes  
Number: The number data type is used to represent numeric values and can be written with or without decimals.


var x = 5; //without decimal  
var y = 5.0; //with decimal  
Boolean: The Boolean data type is used to represent a Boolean value, either false or true. This data type is generally used for conditional testing.


var x = 5;  
var y =  6;  
var z =  5;  
(x == y) // returns false  
(x == z) //returns true  

45. What is the procedure to merge two arrays?

Ans. Syntax:

var arr1 = [1,2,3]

var arr2 = [4,5,6,7]

var mergedArrays = […arr1, …arr2]

document.write(‘Merged arrays’, mergedArrays)

46. Explain Loops in JavaScript.

Ans. In JavaScript, Loops are used to execute a block of code repeatedly. Loops offer a quick and easy way to repeat an action. They execute the same lines of code a specific number of times or as long as a specific condition is true. JavaScript supports the following types of loops:

1. for loop: loops through a block of code a number of times


for(statement1; statement2; statment3)


lines of code to be executed


2. for-in loop: It is used to loop the object through properties.


for (variablename in objectname)


lines of code to be executed


3. while loop: loops through a block of code while a specified condition is true.




lines of code to be executed


4. do/while loop: loops through a block of code while a specified condition is true. It is similar to the while loop. The only difference is that in the do/while loop, the block of code gets executed once even before checking the condition.





block of code to be executed

} while (condition)

47. How do we target a particular frame from a hyperlink?

Ans.  We can target a particular frame from a hyperlink by consisting the name of the required frame and can use ‘target’ attribute in it.

<a href=”/newpage.htm” target=”newframe”>>New Page</a>

48. Name the method we can use to read and write a file in JavaScript?

Ans. JavaScript extensions can be used to read and write a file such as for opening of a file –

fh = fopen(getScriptPath(), 0);

49. Explain what are Screen objects?

Ans. Screen objects hold information from the client’s screen. It is also used to display screen width, pixelDepth, height, etc. Let’s look at the properties of screen objects-

AvailWidth: Provides the width of the client’s screen

AvailHeight: Provides the height of the client’s screen

ColorDepth: Provides the bit depth of images on the client’s screen

Width: Provides the total width of the client’s screen, including the taskbar

Height: Provides the total height of the client’s screen, including the taskbar

Explore the Top Universities Offering Free Online Programming Courses

50. What does the below-given statement specify?

Ans. var myArray = [[[]]];

It specifies a three-dimensional array.

51. What syntax we can use to hide JavaScript codes from old browsers that don’t support JavaScript?

Ans. We can use given codes for hiding JavaScript codes from old browsers:

Use “<!–” without the quotes in the code after the <script> tag.

Use “//–>” without the quotes in the code before the <script> tag.
These codes are not treated by old browsers whereas a browser that supports JavaScript, it will take the “<!–” and “//–>” as one-line comments.

So, here I m ending this question and answer series. I hope this series would help you. If you are candidate who is willing to learn JavaScript and wants to become a JavaScript developer, then enroll and get certified from DevOpsSchool. You may also subscribe to YouTube channel devopsschool and scmgalaxy for more knowledge in DevOps, cloud and containers.

Rajesh Kumar
Follow me
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x