JavaScript remains a firm favorite among aspiring software developers and seasoned pros, as shown by its number 1 ranking in the annual Stack Overflow Developer Survey.

But whether you’re a JavaScript newbie or an experienced engineer that’s ready for a new challenge, preparing for JavaScript interviews can be nerve-wracking!

That’s why we’ve compiled the top 60 JavaScript interview questions to build your confidence and help you to get interview ready.

So, if you’re looking for help with JavaScript interviews, buckle in, and use this article or the PDF download as a confidence-building resource to prepare for your next JavaScript interview. You can even combine these questions with one of the best JavaScript courses to refresh your skills before the interview.

Advertisements

Basic JavaScript Interview Questions

1. What is JavaScript? 

JavaScript is a popular web scripting language that’s used for client-side and server-side development. JavaScript can be inserted into HTML pages and executed by web browsers.

Apart from web development, it’s used in mobile app development, game development, querying databases, and more.

Note: This is the most basic JavaScript question, so it’s important not to overlook it.

Advertisements

2. List Some Key Features of JavaScript.

  • Lightweight interpreted language with object-oriented programming (OOP)
  • Dynamically-typed
  • Platform-independent
  • Offers client-side validation
Advertisements

3. How Is JavaScript Different From Java?

While they share some letters in their names, they are not interlinked and are designed for different purposes. While Java is an OOP language, JavaScript is an OOP script. This means that JavaScript is written in text and then interpreted, and Java is compiled. In terms of apps, Java is used to create apps on devices or browsers, and JavaScript is mainly used with HTML documents and browsers. 

Advertisements

4. How Do You Add Comments to JavaScript Code?

For a single line of comment, you use two forward slash symbols (//)

// Add a single line of comment

For multi-line comments, wrap them with slashes and asterisks (/* */)

/*
Adding
multiple lines
of comments
*/

Note this is one of the most basic JavaScript programming questions, so ensure you know it.

Advertisements

5. What’s The Difference Between Undeclared & Undefined Variables?

An undeclared variable has not been declared anywhere in the code, so said variable does not exist. If you try to read an undeclared variable, JavaScript throws an error.

An undefined variable has been declared in the program, but no value has been assigned. This means the variable exists, but its value is yet to be defined.

Advertisements

6. Summarize the Primitive JavaScript Data Types.

  • String: Represents text, denoted by single quotes, double quotes, or backticks
  • Number:  Represents numbers (integer & floating-point values)
  • BigInt: Represents very large numbers with precision
  • Boolean: Represents true & false values
  • Null: Represents empty, nothing, and unknown type of values
  • Symbol: Used for creating unique identifiers for objects
  • Undefined: When a variable is declared and not yet assigned a value
Advertisements

7. How Can You Import All Named Exports from a JavaScript File?

You can use the import keyword and the asterisk (*) symbol.

Import * as objectName from'./file-path.js';

Note this is one of those JavaScript coding interview questions that’s good to know.

Advertisements

8. Describe the Most Important Advantages of Using JavaScript.

  • Enhanced interactivity: Allows creation of interfaces that react to user input
  • Immediate feedback: Visitors need not wait for a page reload to see if they’ve forgotten to enter important details
  • Low server interaction: Allows user input validation before sending data to the server, reducing server traffic and load
  • Rich interfaces: Items like drag-and-drop components and sliders enhance the UX
Advertisements

9. What Is the Difference Between Attributes and Property?

Properties can be of various data types and are related to JavaScript DOM objects, much like an instance variable for DOM elements.

Attributes are part of the HTML, and unlike a property, is a String data type.

Advertisements

10. How Can You Embed Javascript Code in an HTML File?

  1. Use the <script> tag to add JavaScript code to an HTML document.
<!DOCTYPE html>
<html>
  <head>
    <script>
      console.log("This is JS code.");
    </script>
  </head>
  <body>
  </body>
</html>
  1. Write JavaScript code in an external file with a .js extension, then use the src property in the script tag.
<pre class="wp-block-syntaxhighlighter-code">&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    <a href="http://file_path.js">http://file_path.js</a>
  &lt;/head&gt;
  &lt;body&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
Advertisements

11. Explain the Difference Between Double(==) And Triple(===) Equals.

Double equals (==) is used to compare values with no regard for types, and triple equals (===) is used to compare values while also taking type into consideration.

This is shown in the example below where firstValue is loosely equal to secondValue, which returns true for double equals.

But when we use strict equality with triple equals, it returns false because while they both have a value of 1, firstValue is a Number type, and secondValue is a String type.

var firstValue = 1;
var secondValue = "1";

console.log(firstValue == secondValue); // true
console.log(firstValue === secondValue); // false
Advertisements

12. What are POSITIVE_INFINITY & NEGATIVE_INFINITY in JavaScript?

These are properties of the Number object in JavaScript, where POSITIVE_INFINITY is higher than any other number and NEGATIVE_INFINITY is lower than any other number. These can only be used as properties of a Number object.

Number.POSITIVE_INFINITY;
Number.NEGATIVE_INFINITY;
Advertisements

13. Draw a Simple JavaScript Dom (Document Object Model).

Advertisements

14. What Is NaN in JavaScript?

NaN, or ‘Not a Number’, indicates that JavaScript does not recognize the value as a legal number. You can check whether a value is NaN with the isNaN() function.

console.log(isNaN("John Doe")); //true
console.log(isNaN(25)); // false
Advertisements

15. What Are the Looping Structures in JavaScript?

  • For loops
  • While loops
  • Do-while loops
Advertisements

16. What Is a Prompt Box?

An input container with a label and a text field that lets a user enter input. 

Advertisements

17. What’s the Difference Between Alert & Confirmation Boxes?

An alert box shows a single ‘OK’ button to the user, while confirmation boxes show two buttons with ‘OK’ and ‘Cancel’.

Advertisements

18. Is JavaScript Case-Sensitive?

Yes. A variable named say Hello and a variable named say hello will be treated as two separate variables.

Advertisements

19. How Can You Handle Exceptions With Javascript?

You use try…catch…finally syntax.

  • try statement: defines the code you want to run
  • catch statement: handle errors
  • finally statement: code you want to run regardless of any errors
try {
// code to run
}


catch(err) {
// code to handle errors
}


finally {
// code to run regardless of try / catch result
}
Advertisements

20. How Do You Run a JavaScript File?

Add a script element in the head or body elements of your HTML file, then link to an external script using the script element’s src attribute.

To run a JavaScript file in your terminal, you must have Node installed on your computer. Open your terminal and navigate to the .js file you want to run. Then, run the command below.

node file_name.js
Advertisements

Intermediate JavaScript Interview Questions

21. How Do You Create an Array in Javascript?

  1. Create an instance with the new keyword:let myArray = newArray('value1', 'value2',..., 'valueN');​
  2. Use the Array.of() method:let myArray = Array.of('value1', 'value2',..., 'valueN');​
  3. Use an array literal:let myArray = [value1, value2,...., valueN];​
Advertisements

Make sure you’re ready for JavaScript array interview questions, as they’re an easy win!

22. How Do You Check if a Value Is in an Array in Javascript?

1. Using .includes()

let myArray = [1, 2, 3, 4, 5,];
console.log(myArray.includes(1)); // true
console.log(myArray.includes(7)); // false

2. Using .indexOf()

let myArray = [1, 2, 3, 4, 5];
console.log(myArray.indexOf(1) !== -1); // true
console.log(myArray.indexOf(7) !== -1) // false

3. Using .find()

let myArray = [1, 2, 3, 4, 5];
console.log(myArray.find(value => value === 1)); // 1
console.log(myArray.find(value => value === 7)); // undefined
Advertisements

23. Are Functions Objects in JavaScript?

Functions are class objects in JavaScript because they can be passed to or returned from other functions, assigned to variables or properties, and they have properties and methods like all objects.

Advertisements

24. What Is a Class in JavaScript?

A blueprint for creating objects, which provides a way to define object methods and properties. You define these with the class keyword.

class Person {
  constructor(name) {
    this.name = name;
  }

  sayHi() {
    console.log(`Hi ${this.name}`);
  }
}

const user = new Person("Jane");
user.sayHi(); // "Hi Jane"
Advertisements

25. Is JavaScript a Class-Based Language?

No, it’s a prototype-based language. JavaScript uses prototypes to define object properties, and objects are not instances of classes, but rather they inherit properties and methods from other objects creating a prototype chain.

In a class-based language, objects are instances of classes, and classes define object properties and methods.

Note this is one of those tricky JavaScript interview questions, so make sure you know it.

26. What Is Hoisting in JavaScript?

Functions or variable declarations are promoted to the top of their scope no matter where they’re located within the code.

This only applies to variables declared with the var keyword, not let or const variables.

Advertisements

27. What’s the Difference Between Async/Await & Promise?

These both handle asynchronous code. Promises use a then() method for handling resolved values and a catch() method for errors. Async/await is a syntax wrapper around a promisethat uses try/catch blocks to handle errors and the await keyword to wait for resolved values.

Advertisements

28. How Do You Create a New Object in JavaScript?

  1. Using object literals
const user = {
  name: "Jane Doe",
  age: 25
};
  1. Using the new keyword
const user = newObject();
user.name = "Jane Doe";
user.age = 25;

This is one of those nice and simple JavaScript coding questions to know.

Advertisements

29. What Is a Constructor in JavaScript?

A constructor is used to create an object instance of a class. To call the constructor, you use the new keyword.

function User(name) {
  this.name = name;
}

let firstUser = new User('John Doe');
Advertisements

30. How Can You Return a Character From a Specified Index?

Use the charAt() method. In the example below, we can retrieve the first char at index 0 to fetch J.

let userName = "John";
console.log(userName.charAt(0)); // "J"
Advertisements

31. What Are the Advantages of Using External JavaScript Files?

It separates HTML and JS code, improves the readability of your code, makes it easy to reuse your code, and improves page load speed with cached JS files.

Advertisements

32. What Is the “This” Keyword in JavaScript?

This allows you to refer to the object which was used to make the function call.

Advertisements

33. What Is the For…In Loop in JavaScript?

This is used to iterate over the properties of a JavaScript object. Every property returns a key, which is used to access the value. 

Advertisements

34. What’s the Difference Between Var, Let, & Const Keywords?

  • Var: Declared variables are functionally scoped, or globally scoped when declared outside a function. You can reassign new values and redeclare them.
  • Let: Declared variables are block-scoped, meaning they can only be accessed within their declaration scope. It’s possible to reassign different values to them, but you cannot redeclare them.
  • Const: These are constants, meaning they are block-scoped, and you cannot reassign new values or redeclare them.

35. What Is a First-Class Function?

Functions that are viewed like any other variable, meaning they can be assigned to other variables, passed as a function argument, or returned by another function.

36. What Is a Higher-Order Function?

Functions capable of accepting other functions as arguments and able to return functions as their return value.

Advertisements

37. What Are the Escape Characters in JavaScript?

We use a backslash in front of special characters when we want to actually print or log these characters. For example, this combination would print the double quote, \”.

38. What Is Garbage Collection in JavaScript?

This type of automatic memory management monitors memory allocation to reclaim and free up allocated memory blocks that are no longer needed by the JavaScript program.

39. List the 7 Error Types in JavaScript.

  • EvalError: Error regarding the global function eval()
  • InternalError: Internal error in the JS engine (stack overflow, etc)
  • RangeError: Numeric variable or parameter is outside of valid range
  • ReferenceError: Invalid variable reference
  • SyntaxError: Syntax error while parsing code in eval()
  • TypeError: Parameter or variable not of a valid type
  • URIError: Invalid parameters passed to decodeURI() or encodeURI()
Advertisements

Advanced JavaScript Interview Questions

40. Explain the Use of Debuggers in JavaScript.

Debuggers help developers identify code errors by executing test runs, setting breakpoints, and checking variable values at different stages. Popular web browsers like Safari, Chrome, Firefox, Opera, etc., have a built-in debugger. 

JavaScript also has a debugger keyword to replicate breakpoints, but it works only when debugging is enabled in web browser settings.

Advertisements

41. What Are Factory Functions in JavaScript?

A function that creates and returns other functions – like a function manufacturer, hence the term factory. These are often closures and have access to values in their parent scope.

Factory functions help when creating similar functions with small changes. For example, functions that perform similar operations but with different inputs, as shown below.

function makeMultiplier(multiplier) {
    return function(x) {
        return x * multiplier;
    }
}

let double = makeMultiplier(2);
console.log(double(5)); // prints 10

let triple = makeMultiplier(3);
console.log(triple(5)); // prints 15
Advertisements

42. Explain the Self-Invoking Function and Its Syntax.

These are functions that run immediately, even without being called. The syntax of a self-invoking function is shown below. Note that you must wrap the function with parentheses, and you must add () to the end.

(function sayHello () {
  console.log("Hello World!")
}) ();
Advertisements

43. What’s the Difference Between a Function Declaration and Expression?

Function DeclarationFunction Expression
Must have a name.Can be declared without a name.
HoistedNot hoisted
Can be accessed before and after the function is defined.Created when execution reaches it, and can only be accessed after definition.
Advertisements

Creating a cookie:

To create a cookie, you must assign a string to the cookie property of the document.

document.cookie = "username=John Doe";

Reading a cookie:

To read a cookie value, you call the cookie property of the document object.

let my_cookie = document.cookie;

Deleting a cookie:

Cookies are deleted by default when a user closes the browser. You can also set a deletion time with an expiration date, and the expires parameter. 

document.cookie = "username=John Doe; expires=Thu, 26 Jan 2023 00:00:00 GMT"; 
Advertisements

45. What Is a Closure in JavaScript?

This is a type of function that can access variables within its parent scope, even after the parent function has returned, as shown below. 

Closures are often used in JavaScript for things like private variables and methods and for factory functions.

function parentFunc(name) {
  let message = `Hello ${name}`;
  
  function childFunc() {
    console.log(message);
  }
  return childFunc;
}

let closure = parentFunc(`Jane`);
console.log(closure()); // "Hello Jane"
Advertisements

46. What Are Arrow Functions in JavaScript?

These are short and concise ways of writing function expressions and are typically preferred for non-method functions. The general syntax is shown below.

const functionName = () => { };

47. What Is Prototypal Inheritance in JavaScript?

A way for objects to inherit properties and methods from other objects in JavaScript. When an object is created, it has a reference to another object called its prototype, and it can access the properties and methods of that prototype object.

Advertisements

48. How Can You Empty an Array in JavaScript?

  1. Assign an empty array as the new value
let myArray = [1, 2, 3, 4];
myArray = [];
console.log(myArray); // []
  1. Assign an array length of 0
let myArray = [1, 2, 3, 4];
myArray.length = 0;
console.log(myArray); // []
  1. Apply the pop method while the length is greater than zero
let myArray = [1, 2, 3, 4];
while(myArray.length > 0) {
  myArray.pop();
}
console.log(myArray); // []
  1. Use the splice method
let myArray = [1, 2, 3, 4];
myArray.splice(0, myArray.length);
console.log(myArray); // []
Advertisements

49. Explain Event Bubbling and Event Capturing.

These relate to the propagation of the JavaScript event-listener from parent to child and in reverse.

  • Event Capturing: The event is handled by the outermost element, which is then propagated to the innermost element
  • Event Bubbling: The event is handled by the innermost element first and then propagated to the outermost element (reverse of event capturing)
Advertisements

50. What’s the Difference Between the JavaScript Engine & JavaScript Runtime?

The JavaScript engine converts JavaScript code into machine code that can be executed by the computer, while the JavaScript runtime is the environment in which the code is executed, such as a web browser or Node.js

Hope you liked our questions and answers on Java Scripts.

Advertisements