Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
JavaScript Interview Questions and Answer(Fresher + Experience)

JavaScript Interview Questions and Answer(Fresher + Experience)

30 Nov 2024
Question
90.7K Views
59 min read
Learn with an interactive course and practical hands-on labs

Free Javascript Course: Learn Javascript In 21 Days

Crack Your JavaScript Interview

JavaScript interview preparation might be challenging, right? But don't worry; you've got this! JavaScript is a unique and strong language. I'm here to help you with callbacks, closures, async/await, and even the hard keyword issues. Let's look at some of the most popular JavaScript interview questions and answers to ensure you're prepared to ace your interview with confidence!

Hence in this JavaScript Tutorial, we'll unlock the secrets to acing your JavaScript interview with a curated selection of the best JavaScript interview questions and answers for 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.
  • Now Let's see the most commonly asked JavaScript interview questions and answers in a JavaScript or front-end technologies Interview.

JavaScript Interview Questions for Beginners

TopicDescription
Basic ConceptsWhat is JavaScript, and how does it differ from other programming languages?
Data TypesPrimitive vs. reference types (string, number, boolean, object, undefined, null).
DOM ManipulationUnderstanding the DOM, and how to select and modify elements.
EventsWhat are events in JavaScript, and how to handle them (addEventListener, event bubbling)?
FunctionsDifference between regular functions and arrow functions.
ScopeUnderstanding local, global, and block scope.
ClosuresWhat is a closure, and how does it work?
this KeywordExplanation of how this works in different contexts.
ArraysBasic operations: push, pop, map, filter, reduce.
Promises & Async/AwaitBasic understanding of asynchronous programming in JavaScript.

JavaScript Interview Questions for 3 Years of Experience

TopicDescription
ES6 FeaturesUnderstanding let, const, template literals, destructuring, and spread/rest operators.
Event DelegationHow and why event delegation is used in JavaScript.
Prototypes & InheritanceHow JavaScript implements prototypal inheritance.
Asynchronous HandlingDifference between Promises, async/await, and Callbacks.
Error HandlingUsing try...catch and custom error handling.
HoistingExplanation of how hoisting works for variables and functions.
ModulesWorking with import and export.
DOM OptimizationImproving performance with DocumentFragment, event delegation, and lazy loading.
Browser APIsUnderstanding basic APIs like fetch, localStorage, and sessionStorage.
TestingBasic understanding of unit testing frameworks (e.g., Jest, Mocha).

JavaScript Interview Questions for 10 Years of Experience

TopicDescription
JavaScript FrameworksDeep understanding of frameworks like React, Angular, or Vue.
Web PerformanceAdvanced optimization techniques (e.g., code splitting, tree shaking).
Functional ProgrammingApplication of functional programming concepts in JavaScript.
ScalabilityArchitecting large-scale JavaScript applications.
Server-Side JavaScriptWorking with Node.js for backend development.
Advanced TestingIntegration and end-to-end testing with tools like Cypress, Selenium.
State ManagementUsing libraries like Redux, MobX, or context API for managing application state.
Microservices ArchitectureJavaScript in microservices and serverless environments.
DevOps PracticesCI/CD for JavaScript applications and Dockerization.
Real-Time ApplicationsBuilding real-time applications using WebSockets and frameworks like Socket.IO.
Let's explore Javascript Interview Questions and answers one by one.

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.

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).

Major Advantages of using the JavaScript

  • Full integration with HTML/CSS.
  • Supported by all major browsers which are enabled by default.

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.

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.

Watch the Video - Introduction to ECMA Script

3. Which data types are supported by JavaScript?

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

youtubeWatch the Video - Data Type in JavaScript | Primitive and Non Primitive Data Type

4. What is the difference between undefined and not defined?

Ans. Consider the below example

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))

It will print the number in the console

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.

6. What is the instanceof operator?

Ans. instanceof operator checks whether the object is an instance of a class or not.


function Country(name){this.name=name}; 
var country = new Country("India");
console.log(country instanceof Country) // return true

It will also consider inheritance


let arr = ['apple', 'orange', 'grapes'];
console.log(arr instanceof Array); //prints true in console
console.log(arr instanceof Object); //prints true in console 

Here, arr is an array, but it also belongs to the object, because array prototypal inherits from the object.

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 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

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


const employee = { name: "Ram", age: 25 }
employee.name = "Raju" // it is possible 
use strict";
x = 10; // this will give error

local scope


x = 10; // This will not give error. 
myFunction();
function myFunction() {
 "use strict";
 y = 15; // This will give error
 }

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.

But with JavaScript, the methods and properties are also available to primitive values, because JavaScript treats primitive values as an object when executing the methods and properties.


var str = 'hello';
console.log(str);//print hello

Read More: Strings in JavaScript

9. What are the differences between search() and indexOf()?

Ans: The differences between search() and indexOf() methods are given below:

  • search(): It is used to find a specified value and returns the position of the match, the value can be a string or a regular expression.
  • indexOf(): It is used to find a specified value and returns the position of the match, the value should be a string, it won’t accept a regular expression
var m = /e/;
var m = /e/;
var str = "apple";
str.search(m)//return 4
var str = "apple";
str.indexOf(m)//return -1

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

var str = 'Hello find me test me';
str.indexOf('me') // return 11

var str = 'Hello find me test me';
 str.lastIndexOf('me') // return 19

11. What are the differences between substr() and substring()?

Ans: The differences between substr() and substring() methods are given below:

  • substr(): It is used to return the characters in a string beginning at the specified index and returns the number of characters based on the length provided
  • substring(): It is used to return the characters in a string beginning at the specified index and returns the number of characters based on the length provided minus 1.

var x = "hello";
console.log((x.substr(1, 4) == "ello"))//It will print true in the log

var x = "hello"; 
console.log((x.substring(1, 4) == "ello"))//It will print false in the log
var x = "hello";
console.log((x.substring(1, 5) == "ello"))//print true in console

12. What are the differences between an array and an object?

Ans: The differences between array and object are given below:

ArrayObject
The array uses the numbered indexes to access the element in itThe 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 numberYou should use an object when you want the element name to be a string
It is an ordered collection.It is a collection of unordered properties

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.

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
 })();

14. What is the arrow function?

Ans. The arrow function in Javascript will support in JavaScript only after ES6 or above, it is a short way to write function expressions.

The arrow function is a shorter syntax for using a function that does not have its own "this", below is a simple example of the same.

function add(a, b) {
 return a + b;
 }
console.log(add(1, 2));//3

Using arrow 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.


var browsername = navigator.appName;
console.log(browsername); 

16. How to redirect the user to a new page?

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/"

17. What is the output of the below code?


var num = "10"; 

(function () {
    console.log("Original Number " + num); 
    var num = "50"; // This is the inner variable
    console.log("New Number " + num); 
})();

Output

Original Number undefined
New Number 50

Reason: You will expect the original number will take the value from the outer scope, but the salary value was undefined, because of hoisting.

18. What is DOM?

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 Tree of objects

The DOM represents HTML as a tree structure of tags. Here’s how it looks in the browser inspect the element

19. What is BOM?

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.

Read More: Understanding DOM and BOM

20. What is the NaN property in JavaScript?

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.

Javascript Interview Questions for Intermediate Developers

21. What is the usefulness of the window object?

A browser’s history object could be used to switch to history pages like back and forward from the existing page or another page. 3 methods of 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.

22. What is the functioning of timers in JavaScript?

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 within the stated delay and only stops when canceled. The timer learns when to stop with the clearInterval(id) function.

23. What are the various types of errors in JavaScript?

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 occur because of bad logic carried out on a function with a varied operation.

24. Explain the “this” keyword.

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.

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”.

25. Explain the difference between .call() and .apply().

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.

26. How is DOM used in JavaScript?

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 by including actions like add or delete. Furthermore, DOM is also useful to equip a web page with extra capabilities. The use of API provides a benefit compared to other prevailing models.

27. What is the role of deferred scripts in JavaScript?

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 Deferred, scripts delay execution until the HTML parser is operating. This decreases web pages’ loading time and showcases them faster.

28. What are the different functional components in JavaScript?

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.

    
    <!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>
    
  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.

    
    <!DOCTYPE html>
    <html>
    <head>
     <meta charset="utf-8" />
     <title></title>
    </head>
    <style>
     .lblMsg {
     color: #000;
     }
    </style>
    <body>
     <label id="myelement" class="lblMsg"></label>
     <script>
     document.getElementsByClassName('lblMsg')[0].innerHTML = '<h3> Welcome </h3>'
     </script>
    </body>
    </html>
    
  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.

    
    <!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>
    

30. What is the difference between function declarations and function expressions?

Ans. Function declarations are defined using the function keyword, while function expressions are defined by assigning a function to a variable. Function declarations are hoisted, while function expressions are not.

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.

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.


function display()  
{  
var arr1= [11,12,3,4,5,6,17,8,9,10];     
       arr1.copyWithin(2) ;   
       document.write(arr1);    
}  
display(); 

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().

const newSet = new Set([4, 5, 16, 7]);
console.log(newSet);// Outputs Set {4,5,16,7}

const newSet2 = new WeakSet([3, 4, 5]); //Throws an error


let obj1 = {message:"Hello ScholarHat"};
const newSet3 = new WeakSet([obj1]);
console.log(newSet3.has(obj1)); // true

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.


function display()  
{  
x = 20;    
y = 15;    
z = x + y;    
debugger;    
document.write(z);    
document.write(a);     
}     
display();

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.

The Prototype pattern is hardly used in traditional languages, however, it is used in the development of new objects and templates in JavaScript, which is a prototypal language.

Javascript Interview Questions for Experienced Developers

36. What are the advantages of JavaScript?

Following are some of the advantages of JavaScript:

  • 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:

  • 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.

38. Explain higher-order functions in JavaScript.

Higher-order functions are functions that operate on other functions, either by taking them as arguments or by returning them.Higher-order functions are a result of functions being first-class citizens in JavaScript.


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'.

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:
  • The keys and values in weakmap should always be an object.
  • If there are no references to the object, the object will be garbage collected.

const map1 = new Map();
map1.set('Value', 1);

const map2 = new WeakMap();
map2.set('Value', 2.3); // Throws an error

let obj = {name:"ScholarHat"};
const map3 = new WeakMap();
map3.set(obj, {age:2});

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.

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.

To perform debugging, we can use any of the following approaches:

  • Using console.log() method
  • Using debugger keyword

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.

Example


x = 30; // Gives reference error

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.

45. Is JavaScript case-sensitive language?

Yes, JavaScript is a case-sensitive language.

Example


Var msg = "ScholarHat by DotNetTriks"; //Here, var should be used to declare a variable  
function display()   
{  
document.writeln(msg); // It will not display the result.  
}   
display();

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.

  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.

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.

  • 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.

48. What is the difference between JavaScript and JScript?

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.

49. What is the difference between splice() and slice()?

  • splice() is used to modify an array by adding, removing, or replacing elements at a specific position.
    
    splice(start, optional delete count, optional items to add)
    
  • slice() is used to create a new array that contains a portion of an existing array, specified by the starting and ending indices.
    
    slice(optional start parameter, optional end parameter)
    

50. What are the four states of promise object in javascript?

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.

51. What is event delegation in JavaScript?

Event delegation is a technique of attaching a single event listener to a parent element. This event listener handles events occurring on its child elements. It helps optimize performance and reduce memory consumption.


Item 1 
Item 2 
Item 3

document.getElementById("list").addEventListener
("click", function(event)  {
  if (event.target.nodeName === "LI" ) {
    console.log(event.target.textContent);
}
});

52. Explain the for-in loop in JavaScript.

The for-in loop in javascript is used to loop through the properties or keys of an object. Syntax


for (key in object) {
    // body 
};

The iteration here continues until there are no more keys left to iterate.

Example


const arr = [10, 20, 30, 40, 55];

for (const element of arr) {
  console.log(element);
}

Output

10
20
30
40
55

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:

  • 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

54. Why should you not use innerHTML in JavaScript?

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.

55. Differentiate innerText from innerHTML.

innerTextinnerHTML
Retrieves and sets the content in plain textRetrieves and sets the content in HTML format
We can not insert the HTML tagsWe can insert the HTML tags
It ignores the spaces.It considers the spaces.
It returns text without an inner element tag.It returns a tag with an inner element tag.

56. What is the unshift method in JavaScript?

The unshift() method adds new elements to the beginning of an array. It overwrites the original array.

Syntax


array.unshift(item1, item2, ..., itemX)

57. What is an event bubbling in JavaScript?

Event bubbling is one of the event propagation methods in the DOM (Document Object Model). They dictate the order in which events are processed in the DOM tree.

In event bubbling, events are processed from the innermost element and then propagated up to the parent elements. With this, we can handle multiple events with a single event listener. The event first triggers on the target element and then propagates up the DOM tree.

What is an event bubbling in JavaScript?

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.

58. What is hoisting in JS?

Hoisting inJSrefers to the process whereby the interpreter appears to move the declaration of functions, variables, classes, or imports to the top of their scope before the code is executed. Hence, we can use afunction or a variable before declaration.

Example


// use demo variable before declaring
console.log(demo);

// declare and initialize demo variable
var demo = 5;

Here, we can use the demo variable before declaration because of variable hoisting. But, we get undefined as output because the variable hasn't been initialized at the time it's printed.

Output

undefined

59. What is a debounce function?

Debounce optimizes event handling by delaying the execution of a function until after a specified period of dormancy. When an event is triggered, the debounce function starts a timer. If the function is called again within the delay period, the timer is reset. This delay helps prevent unnecessary or premature function calls, resulting in more efficient event handling.

60. What is Negative Infinity?

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.

Read More:
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.

Buy this eBook at a Discounted Price!

JavaScript Interview Questions & Answers ebook

Download this PDF Now - JavaScript Interview Questions and Answers PDF By ScholarHat

FAQs

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.

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.
  • Behavioral: Explore your teamwork, communication, and problem-solving skills on past projects.

  • Not understanding the difference between var, let, and const.
  • Struggling with closures and scope chain concepts.
  • Being unfamiliar with common browser APIs and event handling.
  • Neglecting best practices for clean, readable code.
  • Getting nervous or flustered under pressure.

 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. 

 To ace your JavaScript interview, thoroughly understand core concepts like closures, async/await, and the event loop and practice solving coding problems. 

You can learn more about JavaScript through online platforms like ScholarHat, which provides comprehensive guides and tutorials, various certification programs, etc.


Take our Javascript skill challenge to evaluate yourself!

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

GET FREE CHALLENGE

Share Article
About Author
Gowtham K (Microsoft MVP and Sr. Software Engineer)

He is having around 5 years of working experience in various technologies like C#, ASP.NET, MVC, Azure, JavaScript, jQuery, CSS and HTML. He loves to work on various web technologies, his passion is to learn, experiment, and share knowledge.
Accept cookies & close this