Home/Blog/Interview Prep/Top 10 JavaScript interview questions
Home/Blog/Interview Prep/Top 10 JavaScript interview questions

Top 10 JavaScript interview questions

10 min read
Oct 28, 2024

JavaScript is a powerful language that plays a central role in web development, enabling you to create interactive and dynamic web pages. As you learn JavaScript, you’ll encounter various concepts and features essential for building robust applications. Mastering these fundamentals is crucial for success in coding interviews.

10 key JavaScript interview questions#

JavaScript is built on a foundation of key concepts that every beginner should understand, such as data types, functions, operators, and string manipulation. Mastering these basics is important for tackling interview questions and building confidence in your coding skills.

In this blog, we will address the following top 10 commonly asked interview questions to help you prepare effectively for JavaScript interviews:

  1. What is the difference between JavaScript and Java?

  2. What is ECMAScript?

  3. Which data types are supported by JavaScript?

  4. What is the typeof operator in JavaScript?

  5. What is the instanceof operator in JavaScript?

  6. What is the NaN property in JavaScript?

  7. What is an arrow function in JavaScript?

  8. What is the strict mode in JavaScript?

  9. What are the top 15 commonly used string methods in JavaScript?

  10. What are timers in JavaScript?

What is the difference between JavaScript and Java?#

JavaScript and Java are two programming languages that are often confused due to their similar names, but they serve different purposes and have distinct characteristics. JavaScript is mainly used for web development to make websites interactive, while Java is a general-purpose language for various applications, including mobile and enterprise software.

Here’s a brief comparison table to highlight their key differences:

JavaScript

Java

Purpose and Use Cases

Primarily for web development and server-side scripting, used to build interactive websites and applications

General-purpose programming, including web, mobile, and desktop applications

Execution Environment

Runs in web browsers and on servers (Node.js)

Runs on Java virtual machine (JVM)

Typing

Dynamic typing

Static typing

Syntax

Flexible and less strict

Strict and verbose

Compilation

Interpreted (no need for explicit compilation)

Compiled into bytecode

Object-Oriented

Prototype-based inheritance

Class-based inheritance

What is ECMAScript?#

ECMAScript is a standardized scripting language specification that is the foundation for JavaScript. It’s maintained by the European Computer Manufacturers Association (ECMA). it defines the language’s rules, syntax, and features. Each version of ECMAScript introduces new features and improvements to enhance JavaScript. Key updates include ES5 (2009) with strict mode and new Array methods, JavaScript ES6 (2015) with let, const, and arrow functions, and recent versions adding features like async/await and optional chaining. Understanding ECMAScript helps ensure consistent behavior across different JavaScript environments.

JavaScript Versions: How JavaScript has changed over the years is an interesting read on how different ECMAScripts proposed features for JavaScript over time.

Which data types are supported by JavaScript?#

JavaScript supports a variety of data types, which can be categorized into two main groups: primitive types and non-primitive types.

Primitive data types:#

  • String: Represents textual data, e.g., “Hello, World!”.

  • Number: Represents integers and floating-point numbers, e.g., 42 or 3.14.

  • Boolean: Represents logical values, either true or false.

  • Undefined: A variable that has been declared but not assigned a value.

  • Null: Represents the intentional absence of any object value, e.g., let user = null;.

  • Symbol: Introduced in ES6, it represents a unique value that can be used as an identifier for object properties, ensuring no conflicts with other property keys. Following is an example of using the symbol as an identifier:

const uniqueId = Symbol('id'); // 'uniqueId' is a unique identifier
const obj = { [uniqueId]: 123 };
  • BigInt: Introduced in ES11, it represents integers with arbitrary precision, e.g., 1234567890123456789012345n.

Non-primitive data types:#

In JavaScript, non-primitive types, also known as reference types, are data types not directly stored as values but as references. This means that when you assign or pass a non-primitive type, you refer to the actual data rather than the data itself.

The main non-primitive types in JavaScript are:

  • Object: It’s a collection of key-value pairs where each key is a string (or Symbol), and each value can be of any type. Objects store structured data, e.g., { name: “John”, age: 30 };.

  • Array: It’s a special object that stores ordered collections of values. Arrays are useful for storing lists of data, e.g. [1, 2, 3, 4, 5];.

  • Function: It’s a block of code designed to perform a specific task. Functions in JavaScript are also objects.

  • RegExp: It’s an object for matching text with a pattern (regular expressions).

Non-primitive types are stored as references in memory, meaning that when you assign a non-primitive type to another variable, both variables refer to the same object in memory. This behavior is different from primitive types, which are copied by value.

If you’re looking to create your first JavaScript portfolio, you may find the following blogs worth visiting:

What is the typeof operator in JavaScript?#

The typeof operator in JavaScript determines the type of a variable or expression, returning a string that indicates its type. This is useful for type checking and debugging. Here’s a useful code example demonstrating how the typeof operator can be used in a practical scenario, such as validating input types:

function processInput(input) {
if (typeof input === 'string') {
console.log("Processing string - output: ", input.toUpperCase());
} else if (typeof input === 'number') {
console.log("Processing number - output: ", input * 2);
} else if (typeof input === 'boolean') {
console.log("Processing boolean - output: ", !input);
} else {
console.log("Unsupported type:", typeof input);
}
}
// Following code tests the function with different types of input
processInput("hello"); // Output: Processing string: HELLO
processInput(10); // Output: Processing number: 20
processInput(true); // Output: Processing boolean: false
processInput([1, 2, 3]); // Output: Unsupported type: object

function processInput(input) {
if (typeof input === 'string') {
console.log("Processing string - output: ", input.toUpperCase());
} else if (typeof input === 'number') {
console.log("Processing number - output: ", input * 2);
} else if (typeof input === 'boolean') {
console.log("Processing boolean - output: ", !input);
} else {
console.log("Unsupported type:", typeof input);
}
}
// Following code tests the function with different types of input
processInput("hello"); // Output: Processing string: HELLO
processInput(10); // Output: Processing number: 20
processInput(true); // Output: Processing boolean: false
processInput([1, 2, 3]); // Output: Unsupported type: object

What is the instanceof operator in JavaScript?#

The instanceof operator checks if an object belongs to a specific class or constructor. It returns TRUE if the object is an instance of the given class or constructor, and FALSE otherwise. In the code example below, instanceof determines whether a vehicle is a Car or a Truck, illustrating how it’s ideal for working with custom objects in applications.

class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
}
class Truck {
constructor(make, model) {
this.make = make;
this.model = model;
}
}
function getVehicleType(vehicle) {
if (vehicle instanceof Car) {
console.log("This is a car: " + vehicle.make + " " + vehicle.model);
} else if (vehicle instanceof Truck) {
console.log("This is a truck: " + vehicle.make + " " + vehicle.model);
} else {
console.log("Unknown vehicle type.");
}
}
let myCar = new Car("Toyota", "Corolla");
let myTruck = new Truck("Ford", "F-150");
getVehicleType(myCar); // This is a car: Toyota Corolla
getVehicleType(myTruck); // This is a truck: Ford F-150
Difference between typeof and instanceof #

While typeof is mostly associated with primitive types, it can also check some non-primitive types in a general way. On the other hand, instanceof is specifically used for non-primitive types.

typeof: This operator is mainly used to check the type of primitive data types, but it can also be used on non-primitive types. For example, typeof returns “object” for objects (including arrays and null) and “function” for functions. However, it doesn’t distinguish between different object types (e.g., it can’t tell the difference between an array and an object).

instanceof: This operator is specifically used to check if an object is an instance of a particular class or constructor function, which makes it ideal for checking non-primitive types. It doesn’t work with primitive types like string, number, or boolean.

In addition to understanding typeof and instanceof, it’s important to know special numeric values like NaN. Let’s explore what NaN is and how it behaves in JavaScript.

What is the NaN property in JavaScript?#

NaN is used to signify a value that is not a valid number, often resulting from mathematical operations that don’t produce a meaningful numeric result. Understanding and correctly handling NaN is important for robust error handling and debugging in JavaScript. Following are some key points about NaN:

  • Type: NaN is of type number. Despite its name, it’s technically a numeric value.

  • Usage: It commonly appears in scenarios such as dividing zero by zero or attempting to convert a non-numeric string to a number.

Note: A unique feature of NaN is that it is not equal to itself. This means that NaN === NaN is false.

Here’s another important tip for using NaN:

Tip: To check if a value is NaN, use the Number.isNaN() method rather than the global isNaN() function, which has some quirks. The Number.isNaN() method accurately determines whether a value is NaN and not any non-numeric value.

Let’s consider the following code example to see how NaN works. Feel free to press the “Run” button to see the output:

let result = 0 / 0; // This will produce NaN
console.log(result); // Output: NaN
console.log(result === NaN); // Output: false
// Correct way to check for NaN
console.log(Number.isNaN(result)); // Output: true

If you’re preparing for problem-solving coding interviews and want to practice LeetCode in JavaScript, checking out the following blogs can give you a quick start:

What is an arrow function in JavaScript?#

An arrow function in JavaScript is a compact function syntax introduced in ES6 that uses the => notation. It differs from regular functions by not having its own this, arguments, super, or new.target bindings, making it particularly useful in callbacks and for preserving the context of this. Arrow functions also allow for more concise code, especially when dealing with single-expression functions where the return statement is implicit.

Here’s an example using a Counter object to demonstrate the lexical this with an arrow function:

function Counter() {
this.count = 0;
this.limit = 5; // Limit the count to 10 times
const intervalId = setInterval(() => {
this.count++;
console.log(this.count);
if (this.count === this.limit) {
clearInterval(intervalId); // Stop the interval when the limit is reached
}
}, 1000);
}
const myCounter = new Counter();

To learn the details of the this keyword in JavaScript, consider visiting the blog Understanding “this” in JavaScript. This blog explains the dynamics of this in detail, covering it in a global context, functional context, implicit and explicit binding, and arrow function binding.

What is strict mode in JavaScript?#

Strict mode in JavaScript is a feature that enforces stricter rules and error handling to help developers write cleaner, safer code. Introduced in ES5, it catches common mistakes like undeclared variables and improper use of this. Recent ECMAScript releases have introduced stricter rules for the language, but the strict mode feature remains relevant. Why is that the case? The following note answers this question:

Even with the advancements in the latest JavaScript versions, strict mode remains relevant because it adds an extra layer of protection. It ensures consistent behavior across environments and helps prevent bugs that might be allowed in non-strict code. It’s a valuable tool for maintaining high-quality code, even in modern JavaScript.

What are the top 15 commonly used string methods in JavaScript?#

When preparing for a JavaScript interview, understanding how to work with strings is essential. You’ll frequently rely on various methods to manipulate and analyze strings. These methods help you perform tasks such as extracting substrings, searching for specific content, or modifying the strings.

The following table shows the category-wise division of various string methods used in JavaScript. These are organized to help you quickly find and understand the most commonly used functions.

Extracting substrings#

Method

Description

Example

Output

charAt(index)

Returns the character at the specified index.

let str = "Hello";

console.log(str.charAt(1));

e

slice(start, end)

Extracts a string section starting from index start and ending at end-1.

let str = "Hello World";

console.log(str.slice(0, 5));

Hello

substr(start, length)

Extracts a substring, starting at a specified position and extending for a given length.

let str = "Hello World";

console.log(str.substr(6, 5));

World

substring(start, end)

Extracts characters from a string between two specified indexes.

let str = "Hello World";

console.log(str.substring(6, 11));

World

Searching and indexing#

Method

Description

Example

Output

indexOf(substring)

Returns the first index of the first occurrence of a substring.

let str = "Hello World";

console.log(str.indexOf("World"));

6

lastIndexOf(substring)

Returns the first index of the last occurrence of a substring.

let str = "Hello World World";

console.log(str.lastIndexOf("World"));

12

search(regex)

Searches for a match to a regular expression and returns the index of the first match.

let str = "Hello World";

console.log(str.search(/World/));

6

Modifying strings#

Method

Description

Example

Output

concat(...strings)

Joins two or more strings and returns a new string.

let str1 = "Hello";

let str2 = "World";

console.log(str1.concat(" ", str2));

Hello World

replace(searchValue, newValue)

Replaces the first occurrence of a specified substring or regex with a new substring.

let str = "Hello World";

console.log(str.replace("World", "JavaScript"));

Hello JavaScript

toLowerCase()

Converts all characters in the string to a lowercase.

let str = "Hello World";

console.log(str.toLowerCase());

hello world

toUpperCase()

Converts all characters in the string to an uppercase.

let str = "Hello World";

console.log(str.toUpperCase());

HELLO WORLD

trim()

Removes whitespace from both ends of the string.

let str = " Hello World ";

console.log(str.trim());

Hello World

repeat(count)

Returns a new string that repeats the original string a specified number of times.

let str = "Hello ";

console.log(str.repeat(3));

Hello Hello Hello

Splitting and joining#

Method

Description

Example

Output

split(separator)

Splits a string into an array of substrings based on a separator.

let str = "Hello World";

console.log(str.split(" "));

[“Hello”, “World”]

join(separator)

Joins all elements of an array into a single string, with a specified separator between each element.

let arr = ["Hello", "World"];

console.log(arr.join(" "));

Hello World

What are timers in JavaScript?#

Timers in JavaScript are functions that allow you to execute code after a certain amount of time has passed or repeatedly at specified intervals. The two primary functions used for timers are setTimeout and setInterval. Timers are useful for scheduling tasks, creating delays, and running code at regular intervals. Following are a few use cases of each of these methods:

  • setTimeout: Delays the execution of code, such as showing a notification after a delay or postponing an animation.

  • setInterval: Runs code repeatedly, such as updating a clock, rotating a slideshow, or polling a server at regular intervals.

Here’s the code example that demonstrates the use of setInterval, setTimeout, and clearInterval:

// Initialize counter
let counter = 0;
// Start an interval that increments the counter every second
const intervalId = setInterval(() => {
counter++;
console.log("Counter:", counter);
// Clear the interval after 5 increments
if (counter === 5) {
clearInterval(intervalId);
console.log("Interval cleared");
}
}, 1000);
// Schedule a timeout to clear the interval after 8 seconds
setTimeout(() => {
clearInterval(intervalId); // This will not affect the interval since it's already cleared
console.log("Timeout cleared the interval");
}, 8000);
console.log("Interval and timeout scheduled");

In the code example above, setInterval increments and logs a counter every second. After eight seconds, setTimeout clears the interval using clearInterval, stopping further increments.

Cover
Ace the JavaScript Coding Interview

JavaScript is a lightweight, high-level programming language that is event-driven and functional and can be either interpreted or just-in-time compiled. It is one of the core technologies of web development and allows us to use multiple frameworks. JavaScript continues to rise in popularity, but it also continues to evolve and support new functionality very rapidly. This Skill Path will take you through all that you need to know to crack your JavaScript interviews with confidence. You’ll cover everything from data structures to object-oriented design. You will also get to know the essential patterns behind popular coding interview questions. By the time you are done, your skills will be polished to ace the interview of any company.

185hrs
Intermediate
113 Challenges
242 Quizzes

Moving forward#

As you continue your JavaScript journey, diving deeper into advanced features that will further enhance your skills is important. After mastering the fundamental concepts covered in this blog, consider exploring topics like Promises and async/await for handling asynchronous code, JavaScript modules for better code organization, and closures for more complex function behaviors. Understanding event delegation, prototypal inheritance, and advanced ES6+ features such as spread/rest operators and destructuring will prepare you for more complex development tasks and improve your readiness for technical interviews. Keep building your knowledge, and you’ll be well on your way to mastering JavaScript!

If you’re looking to build a solid foundation in JavaScript, Educative offers the Zero to Hero in JavaScript path. This comprehensive learning path covers everything you need to know, including:

- The basics of JavaScript
- Object-oriented programming in JavaScript
- Data structures in JavaScript
- Creating a Tetris game with JavaScript

These modules are designed to help you master JavaScript from the ground up, making it a great choice for anyone eager to learn and apply their skills.

Educative offers a comprehensive course JavaScript in Detail: From Beginner to Advanced for learning basic to advanced JavaScript concepts. Have a look and enjoy your learning.

Cover
JavaScript in Detail: From Beginner to Advanced

In this project-based course you will dissect every part of JavaScript from beginning concepts to more advanced. You will start by running through JS fundamentals such as arrays, types, variables, and conditional statements. You’ll then move on to more advanced concepts like OOP, regular expressions, and asynchronous programming. Throughout this course, you will be tasked with 4 projects that will test different parts of your understanding. At the end you will take a final exam to really hammer in what you’ve learned. Once you finish this course, you will have an advanced grasp of the language and you will be ready to tackle more advanced projects. Plus you’ll have some great intro projects to add to your portfolio.

12hrs
Beginner
20 Challenges
14 Quizzes

If you’re just getting started with JavaScript, the following blogs will help you outline a learning roadmap and provide useful resources to kickstart your journey:

  1. JavaScript developer roadmap

  2. The best ways to master JavaScript

Frequently Asked Questions

What are some of the basic JavaScript interview questions?

Some of the frequently asked JavaScript interview questions are as follows:

  1. What is JavaScript, and how is it different from Java?
  2. What are the different data types supported by JavaScript?
  3. What is undefined vs. null in JavaScript?
  4. What is the difference between var, let, and const?
  5. What are functions and arrow functions in JavaScript?
  6. What is the difference between == and === in JavaScript?
  7. What are JavaScript promises, and how do they work?
  8. What is the difference between synchronous and asynchronous code?
  9. What is the purpose of setTimeout and setInterval?
  10. What is strict mode in JavaScript, and why is it used?

What is the best answer to define JavaScript?

What is the difference between `==` and `===` in JavaScript interview questions?

How many data types are in JavaScript?

What is JavaScript in HTML?


Written By:
Ishrat Fatima
 
Join 2.5 million developers at
Explore the catalog

Free Resources