Interview Preparation

JavaScript Interview Questions

Master the most commonly asked interview questions with comprehensive, expert-crafted answers designed to help you succeed.

15
Questions
100%
Expert Answers
Q1
Are JavaScript and Java related?

Java and JavaScript may sound similar, but they are entirely different languages with distinct features and use cases. Below is a comparison to highlight the key differences:

JavaJavaScript
Java is a strongly typed language. Variables must be declared before use. Type checking happens at compile-time.JavaScript is a loosely typed language. It allows variable declarations without explicit types and performs type checking at runtime.
Java is object-oriented and used for developing complex, large-scale enterprise applications.JavaScript is a scripting language primarily used to build interactive and dynamic web pages.
Java applications run on the Java Virtual Machine (JVM), making them platform-independent.Originally ran in browsers, JavaScript can now also run on servers via Node.js.
Java uses class-based object-oriented programming. Every program must contain at least one class.JavaScript uses prototype-based inheritance and does not require classes to create objects (though ES6 introduced class syntax).
Q2
What is the difference between Lexical and Dynamic Scoping?

Lexical Scoping (also known as static scoping) and Dynamic Scoping are two strategies for resolving variable names in nested functions or blocks. They differ in how and where variables are looked up in the code.

Lexical Scoping:

  • Variables are resolved based on the location of the function definition in the source code.
  • The scope is determined at compile-time.
  • JavaScript, Python, and C use lexical scoping.
  • Inner functions have access to variables defined in their outer functions.

Dynamic Scoping:

  • Variables are resolved based on the call stack at runtime.
  • The scope is determined during execution.
  • Languages like older versions of Lisp and Bash use dynamic scoping.
  • A function can access variables from its caller, even if they aren't in the lexical chain.

Example:

let a = 10;
function outer() {
    let a = 20;
    function inner() {
        console.log(a);
    }
    inner();
}
outer();
// Output: 20 (Lexical scope: inner sees 'a' from outer)
Q3
What is the difference between JavaScript and TypeScript?

JavaScript is a dynamic scripting language used to create interactive elements on websites. It runs directly in web browsers and is essential for frontend development.

TypeScript, on the other hand, is a superset of JavaScript developed by Microsoft. It adds optional static typing, interfaces, generics, and other object-oriented features to JavaScript.

Here are the key distinctions:

  • Typing: JavaScript is dynamically typed, while TypeScript supports static typing.
  • Compilation: JavaScript doesn't require compilation; TypeScript must be compiled into JavaScript.
  • Tooling: TypeScript offers better IntelliSense, autocompletion, and error checking in modern IDEs.
  • Use Case: JavaScript is perfect for quick scripts and small applications. TypeScript is ideal for large, scalable applications.
  • Community: JavaScript is more widely adopted, but TypeScript is rapidly growing in popularity, especially in enterprise environments.

Conclusion: TypeScript enhances JavaScript with modern development features. If you're working on large codebases or collaborative projects, TypeScript can help reduce bugs and improve maintainability.

Q4
What is the use of the isNaN function?

The isNaN() function in JavaScript is used to determine whether a given value is an illegal number, specifically whether it is NaN (which stands for 'Not-a-Number'). This function returns true if the value is NaN, and false if it is a valid number or can be successfully coerced into a number.

This function is particularly useful when you need to validate input or check the result of a computation that may not return a numeric value. Since JavaScript is loosely typed and performs automatic type conversions, it's important to confirm that the result of an operation is actually a number before performing further calculations.

Example:

console.log(isNaN(123));       // false (123 is a number)
console.log(isNaN('123'));     // false ('123' can be coerced to a number)
console.log(isNaN('abc'));     // true ('abc' cannot be converted to a number)
console.log(isNaN(NaN));       // true (value is explicitly NaN)
console.log(isNaN(undefined)); // true (undefined cannot be converted to a number)
Q5
What is negative infinity?

Negative Infinity in JavaScript is a special numeric value that represents a value lower than any other number in the language. It is a property of the global Number object and is expressed as Number.NEGATIVE_INFINITY or simply -Infinity.

This value is typically returned when a mathematical operation results in a value beyond the lower bound of the number range JavaScript can represent. For instance, dividing a negative number by zero will return negative infinity.

Example:

console.log(-1 / 0);                      // -Infinity
console.log(Number.NEGATIVE_INFINITY);    // -Infinity
console.log(typeof -Infinity);            // 'number'
console.log(-Infinity < -1e308);          // true

JavaScript treats -Infinity as a valid number type. It can be compared with other numbers and participates in mathematical expressions just like regular numeric values.

Q6
Write a JavaScript code for adding new elements dynamically.

In JavaScript, you can dynamically create and add new elements to the Document Object Model (DOM) using methods such as document.createElement() and appendChild(). This is useful for building interactive web pages where content is generated on the fly in response to user actions.

Below is a basic example that demonstrates how to create a new paragraph element and add it to a <div> container when a button is clicked:

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Element Example</title>
</head>
<body>
    <div id="container">
        <h3>Click the button to add a paragraph:</h3>
    </div>
    <button onclick="addParagraph()">Add Paragraph</button>

    <script>
    function addParagraph() {
        const container = document.getElementById("container");
        const newPara = document.createElement("p");
        newPara.textContent = "This is a dynamically added paragraph.";
        container.appendChild(newPara);
    }
    </script>
</body>
</html>

In this code, the addParagraph() function is called when the user clicks the button. It creates a new <p> element, adds some text to it, and appends it to the <div> with the ID container. This process can be repeated any number of times, allowing dynamic content creation.

Q7
What is a prompt box?

A prompt box in JavaScript is a built-in dialog box that allows the browser to display a message to the user and request input. It is used when the program needs the user to enter a value before continuing. The prompt box pauses script execution until the user enters input or cancels the dialog.

The syntax for using a prompt box is:

let userInput = prompt("Please enter your name:");

This line of code displays a dialog box with the message “Please enter your name:”, a text input field, and OK/Cancel buttons. The value entered by the user is stored in the userInput variable. If the user clicks 'Cancel', the result will be null.

Example:

let age = prompt("How old are you?");
if (age !== null) {
    alert("You are " + age + " years old.");
} else {
    alert("You cancelled the prompt.");
}

Note: Prompt boxes are synchronous and block interaction with the page until the user responds. They are mostly used for quick input, but modern applications often prefer custom modal dialogs for better user experience.

Q8
Explain the working of timers in JavaScript. Also explain the drawbacks of using the timer, if any.

In JavaScript, timers are used to execute functions after a specific delay or at regular intervals. The most commonly used timer functions are setTimeout() and setInterval().

The setTimeout() function is used to execute a block of code or function once after a specified delay in milliseconds. On the other hand, setInterval() is used to repeatedly execute a block of code or function at fixed time intervals.

Internally, JavaScript timers are not part of the ECMAScript specification but are provided by the browser or the runtime environment (like Node.js). These timers work asynchronously and are managed by the browser's Web APIs. When a timer expires, the corresponding callback function is placed in the task queue and executed by the event loop when the call stack is empty.

Drawbacks of using timers:

  • Inaccuracy: Timers are not guaranteed to run exactly on time. Delays may occur due to other code executing on the main thread, leading to timer drift, especially for setInterval().
  • Single-threaded nature of JavaScript: Since JavaScript runs on a single thread, any heavy computation or long-running script can block the execution of the timer callback, causing performance issues or unresponsive UI.
  • Memory Leaks: If timers are not properly cleared using clearTimeout() or clearInterval(), especially in single-page applications, they may cause memory leaks or unexpected behavior.
  • Uncontrolled Repetition: Using setInterval() carelessly can lead to multiple overlapping executions if the interval is shorter than the time taken by the function to complete.
Q9
What is the difference between ViewState and SessionState?

ViewState and SessionState are both mechanisms used to preserve state in web applications, but they operate differently in terms of scope and lifetime.

ViewState is specific to a single page and is used to retain the state of controls between postbacks. It stores data in a hidden field on the page itself, meaning that the information is sent to the server and back to the client with each request. Because it is page-specific, data stored in ViewState is not accessible across different web pages. It is mainly used in ASP.NET Web Forms applications to remember user inputs or control properties within a single page.

SessionState, on the other hand, is user-specific and allows data to be maintained across multiple pages within a user’s session. It stores data on the server and is tied to a specific user's session ID. This enables developers to track user information such as login details, shopping cart contents, or user preferences throughout the entire session. The data in SessionState is preserved until the session expires or is explicitly cleared.

Q10
What is a higher-order function in JavaScript?

A higher-order function in JavaScript is a function that can either accept other functions as arguments, return a function as its result, or do both. This concept is a fundamental part of functional programming and is widely used in JavaScript to create clean, reusable, and abstract logic.

Higher-order functions treat functions as first-class citizens, meaning functions can be assigned to variables, passed around as arguments, and returned just like any other value.

Common examples of higher-order functions in JavaScript include methods like map(), filter(), and reduce(). These methods take a callback function as an argument and apply it to each element of an array to produce a new result.

Example (no need to show in UI): array.map() takes a function that is applied to every element in the array, transforming it and returning a new array based on the original values.

Conclusion: Higher-order functions make JavaScript more expressive and concise. They allow developers to write modular and composable code, enabling powerful patterns such as callbacks, currying, and function composition.

Q11
Explain how to read and write a file using JavaScript?

In JavaScript, file reading and writing operations are typically performed on the server side using Node.js, since JavaScript running in the browser does not have direct access to the file system for security reasons.

To work with files in Node.js, you use the built-in fs (File System) module. This module provides both asynchronous and synchronous methods to read and write files. The most commonly used functions are readFile() and writeFile().

1. readFile(): This function is used to read the content of a file asynchronously. It takes three parameters: the file path, optional encoding or configuration options, and a callback function that handles the result or error.

Syntax: fs.readFile(path, options, callback)

2. writeFile(): This function is used to write data to a file asynchronously. If the file does not exist, it will be created; if it does exist, it will be overwritten. It also takes three parameters: the file path, the data to write, and a callback function to handle success or error.

Syntax: fs.writeFile(path, data, callback)

Example usage (not shown in UI): These methods are commonly used in backend development to handle file operations such as logging, configuration management, data storage, or file manipulation.

Conclusion: To read and write files in JavaScript, you need to use the fs module provided by Node.js. The readFile() function allows you to read content from a file asynchronously, while the writeFile() function is used to write or overwrite file content. These operations are essential for server-side applications that deal with data persistence or file handling.

Q12
What is hoisting in JavaScript?

Hoisting in JavaScript refers to the behavior where variable and function declarations are moved to the top of their containing scope (either function or global scope) during the compilation phase, before the actual code is executed.

This means that you can reference variables and functions in your code before they are formally declared. However, it is important to understand that only the declarations are hoisted — not the initializations or assignments.

Example:

console.log(a); // undefined
var a = 5;

In this case, the declaration var a is hoisted to the top of the scope, but the assignment a = 5 is not. So when the code is executed, a exists but is undefined at the time it is logged.

Hoisting behaves differently for various declarations:

  • var declarations are hoisted and initialized with undefined.
  • let and const are hoisted but not initialized. Accessing them before declaration results in a ReferenceError due to the temporal dead zone (TDZ).
  • Function declarations are fully hoisted, meaning both the function name and its body are moved to the top, so you can invoke them before their appearance in the code.
  • Function expressions using var, let, or const are not hoisted in the same way as function declarations.
Q13
How to convert the string of any base to integer in JavaScript?

In JavaScript, the parseInt() function is used to convert a string representing a number in any base (radix) into an integer. This function takes two arguments: the string to convert and the base of the numerical system (such as binary, octal, decimal, or hexadecimal) as the second argument.

Syntax: parseInt(string, radix)

The radix parameter is essential, as it tells the function which base the number is in. For example, radix 2 is for binary, 8 for octal, 10 for decimal, and 16 for hexadecimal.

Example:

parseInt("1010", 2);     // returns 10 (binary to decimal)
parseInt("20", 8);       // returns 16 (octal to decimal)
parseInt("1F", 16);      // returns 31 (hexadecimal to decimal)
parseInt("123", 10);     // returns 123 (decimal remains unchanged)
parseInt("xyz", 10);     // returns NaN (invalid number in base 10)

If the string contains characters that are not valid in the specified base, parseInt() will return NaN, which stands for 'Not a Number'.

Conclusion: The parseInt() function is a powerful and flexible way to convert strings of different bases into integers in JavaScript. Always specify the base to avoid unexpected results, especially when working with values that may resemble octal or hexadecimal formats.

Q14
Explain the concept of memoization in JavaScript?

Memoization in JavaScript is an optimization technique used to speed up function execution by storing the results of expensive function calls and reusing them when the same inputs occur again. This technique helps avoid redundant calculations by caching previously computed results.

It is especially useful in scenarios where the function is called frequently with the same arguments and involves heavy or time-consuming computations, such as mathematical operations, recursive algorithms, or data fetching.

Memoization is typically implemented using an object or a Map to store the mapping between function arguments and their computed results. When the memoized function is called again with the same arguments, it checks the cache first and returns the cached result instead of recalculating it.

Benefits of memoization:

  • Reduces the number of computations by reusing cached results.
  • Improves application performance, especially in CPU-intensive operations.
  • Enhances responsiveness in frontend applications, particularly when rendering or processing data repeatedly.

Note: Memoization is different from general caching in that it is usually specific to pure functions—those that always produce the same output for the same input and have no side effects.

Q15
Explain the concept of promises and how they work.

A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide a cleaner, more manageable approach to handling asynchronous code compared to traditional callback functions.

A promise can be in one of three states:

  • Pending – The initial state, before the operation has completed.
  • Fulfilled (Resolved) – The operation completed successfully, and the promise has a resulting value.
  • Rejected – The operation failed, and the promise has a reason for the failure (typically an error object).

You create a promise using the new Promise() constructor, which accepts an executor function. This executor function takes two arguments: resolve and reject. You call resolve(value) when the operation is successful, and reject(error) when it fails.

Promises are typically handled using the .then() method to define what should happen when the promise is fulfilled, and .catch() to handle any errors if the promise is rejected. You can also chain multiple .then() calls to manage sequences of asynchronous operations in a readable manner.

Example (not shown in UI): A promise might be used when fetching data from an API. Instead of nesting callbacks, you use fetch() which returns a promise, and then attach .then() and .catch() to handle the result or error.

Why Choose Our Question Bank?

Get access to expertly crafted answers and comprehensive preparation materials

Complete Collection

Access all 15 carefully curated questions covering every aspect of JavaScript interviews

Expert Answers

Get detailed, professional answers crafted by industry experts with real-world experience

Instant Access

Start preparing immediately with instant access to all questions and answers after sign-up