100 Javascript Interview Question and Answer

Here are 100 Javascript Interview Question and Answer to help you prepare:

Basic Questions

  1. What is JavaScript?
    • JavaScript is a high-level, interpreted programming language used to make web pages interactive.
  2. What are the data types supported by JavaScript?
    • JavaScript supports the following data types: Number, String, Boolean, Object, Undefined, Null, Symbol, and BigInt.
  3. What is the difference between == and ===?
    • == checks for value equality with type coercion, while === checks for both value and type equality.
  4. What is NaN in JavaScript?
    • NaN stands for “Not-a-Number” and indicates a value that is not a legal number.
  5. What is the use of the typeof operator?
    • typeof is used to determine the data type of a variable.

Intermediate Questions

  1. What are closures in JavaScript?
    • A closure is a function that has access to its own scope, the scope of the outer function, and the global scope.
  2. Explain this keyword in JavaScript.
    • this refers to the object it belongs to. In a method, this refers to the owner object, in a function, this refers to the global object, and in an event, this refers to the element that received the event.
  3. What is event delegation?
    • Event delegation is a technique to handle events efficiently by using a single event listener to manage all child elements.
  4. What is the difference between null and undefined?
    • null is an assigned value representing no value, while undefined means a variable has been declared but not assigned a value.
  5. What is the purpose of the let and const keywords?
    • let allows you to declare variables that are block-scoped, while const allows you to declare block-scoped constants.

Advanced Questions

  1. What is the difference between function declarations and function expressions?
    • Function declarations are hoisted to the top of their scope, while function expressions are not hoisted.
  2. What are arrow functions?
    • Arrow functions are a concise syntax for writing functions using the => notation and do not have their own this context.
  3. Explain the concept of Promises in JavaScript.
    • Promises represent the eventual completion (or failure) of an asynchronous operation and its resulting value.
  4. What is the purpose of the async and await keywords?
    • async makes a function return a Promise, and await pauses the function execution until the Promise is resolved.
  5. What is the difference between map and forEach?
    • map creates a new array with the results of calling a function on every element, while forEach executes a provided function once for each array element but does not return a new array.

Object-Oriented Programming

  1. What is prototypal inheritance?
    • Prototypal inheritance is a feature in JavaScript where objects can inherit properties and methods from other objects.
  2. What are classes in JavaScript?
    • Classes are syntactic sugar over JavaScript’s existing prototype-based inheritance, providing a cleaner and more intuitive syntax for creating objects and handling inheritance.
  3. What are getters and setters?
    • Getters and setters are special methods that provide controlled access to an object’s properties.
  4. Explain the concept of super in JavaScript.
    • super is used to call functions on an object’s parent class.
  5. What are mixins in JavaScript?
    • Mixins are a way to include the behavior of multiple classes in a single class without using inheritance.

DOM and Events

  1. What is the DOM?
    • The DOM (Document Object Model) is an interface that represents HTML or XML documents as a tree structure.
  2. How do you select DOM elements in JavaScript?
    • DOM elements can be selected using methods like getElementById, getElementsByClassName, getElementsByTagName, querySelector, and querySelectorAll.
  3. What is event bubbling and event capturing?
    • Event bubbling is when an event starts from the target element and bubbles up to the root, while event capturing is the reverse.
  4. How do you add an event listener to a DOM element?
    • Use the addEventListener method to attach an event handler to a DOM element.
  5. What is the difference between stopPropagation and preventDefault?
    • stopPropagation prevents the event from bubbling up or capturing down, while preventDefault prevents the default action associated with the event.

Asynchronous JavaScript

  1. What are callbacks?
    • Callbacks are functions passed as arguments to other functions and executed after some operation has been completed.
  2. What is the event loop?
    • The event loop is a mechanism that allows JavaScript to perform non-blocking operations by offloading operations to the system kernel whenever possible.
  3. What is a Promise chain?
    • A Promise chain is a sequence of .then() methods, each returning a new Promise.
  4. What are the different states of a Promise?
    • A Promise can be in one of three states: pending, fulfilled, or rejected.
  5. What is Promise.all?
    • Promise.all takes an array of Promises and returns a single Promise that resolves when all the input Promises have resolved.

Error Handling

  1. What is a try-catch block?
    • A try-catch block is used to handle exceptions, with code that might throw an error placed in the try block and error handling code in the catch block.
  2. What is the difference between throw and return?
    • throw is used to raise an exception, while return is used to return a value from a function.
  3. What is the purpose of the finally block?
    • The finally block contains code that will run regardless of whether an error was thrown or not.
  4. How do you create a custom error in JavaScript?
    • Create a custom error by extending the Error class.
  5. What is a stack trace?
    • A stack trace is a report that provides information about the active stack frames at a specific point in time during the execution of a program.

Best Practices

  1. What is hoisting?
    • Hoisting is JavaScript’s behavior of moving variable and function declarations to the top of their containing scope during the compilation phase.
  2. Why is it important to avoid global variables?
    • Global variables can lead to naming collisions and unintended side effects across the codebase.
  3. What are pure functions?
    • Pure functions are functions that have no side effects and return the same output for the same input.
  4. What is the module pattern?
    • The module pattern is a design pattern that encapsulates private variables and functions within a closure, exposing only the public API.
  5. What is debouncing and throttling?
    • Debouncing delays the execution of a function until a certain period of time has passed since the last time it was invoked, while throttling ensures a function is only called at most once in a specified time interval.

Modern JavaScript

  1. What are ES6 features?
    • Some ES6 features include let and const, arrow functions, template literals, destructuring, default parameters, classes, modules, and promises.
  2. What are template literals?
    • Template literals are string literals allowing embedded expressions, using backticks `, with the syntax ${expression} for interpolation.
  3. What is destructuring in JavaScript?
    • Destructuring is a syntax that allows unpacking values from arrays or properties from objects into distinct variables.
  4. What are default parameters?
    • Default parameters allow function parameters to be initialized with default values if no value is provided.
  5. What is the spread operator?
    • The spread operator (...) allows an iterable such as an array to be expanded in places where zero or more arguments or elements are expected.

Functional Programming

  1. What is functional programming?
    • Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing state and mutable data.
  2. What are higher-order functions?
    • Higher-order functions are functions that take other functions as arguments or return them as results.
  3. What is immutability?
    • Immutability is a principle where data cannot be modified once created, instead new data structures are created for changes.
  4. What is function composition?
    • Function composition is the process of combining two or more functions to produce a new function.
  5. What is currying in JavaScript?
    • Currying is a technique of evaluating a function with multiple arguments, by transforming it into a sequence of functions each with a single argument.

Performance and Optimization

  1. What is memoization?
    • Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result for the same inputs.
  2. What is lazy loading?
    • Lazy loading is a design pattern that delays the initialization of an object until it is needed.
  3. What is tree shaking?
    • Tree shaking is a technique used in JavaScript bundlers to remove dead code from the final bundle.
  4. How can you improve the performance of a JavaScript application?
    • Some ways to improve performance include minimizing DOM access, optimizing loops, using debouncing and throttling, and leveraging caching.
  5. What are web workers?
    • Web workers are a way to run JavaScript in background threads, allowing concurrent execution of scripts to improve performance.

Security

  1. What is Cross-Site Scripting (XSS)?
    • XSS is a security vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users.
  2. What is Cross-Site Request Forgery (CSRF)?
    • CSRF is an attack that forces a user to execute unwanted actions on a web application in which they are authenticated.
  3. What is CORS?
    • CORS (Cross-Origin Resource Sharing) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the resource originated.
  4. What is content security policy (CSP)?
    • CSP is a security feature that helps prevent XSS attacks by specifying which dynamic resources are allowed to load.
  5. What is the Same-Origin Policy?
    • The Same-Origin Policy is a security measure that restricts how a document or script loaded from one origin can interact with resources from another origin.

Miscellaneous

  1. What is the difference between synchronous and asynchronous code?
    • Synchronous code executes sequentially, blocking the execution of subsequent code, while asynchronous code allows for non-blocking execution, enabling other operations to run concurrently.
  2. What is a service worker?
    • A service worker is a script that runs in the background and enables features such as push notifications and background sync.
  3. What is the fetch API?
    • The fetch API provides a modern interface for making HTTP requests to servers and handling responses.
  4. What are modules in JavaScript?
    • Modules are reusable pieces of code that can be imported and exported between different files using import and export statements.
  5. What is a polyfill?
    • A polyfill is code that provides modern functionality on older browsers that do not natively support it.

Regular Expressions

  1. What are regular expressions?
    • Regular expressions are patterns used to match character combinations in strings.
  2. How do you create a regular expression in JavaScript?
    • A regular expression can be created using the RegExp constructor or by enclosing the pattern in forward slashes (/pattern/).
  3. What are some common methods used with regular expressions?
    • Common methods include test, exec, match, replace, search, and split.
  4. What is the difference between test and exec methods?
    • The test method checks if a pattern exists in a string and returns true or false, while the exec method searches for a match and returns the result as an array or null.
  5. What are character classes in regular expressions?
    • Character classes define a set of characters to match, such as [abc] for matching a, b, or c.

Arrays and Objects

  1. How do you create an array in JavaScript?
    • An array can be created using the array literal notation ([]) or the Array constructor.
  2. What are some common array methods?
    • Common array methods include push, pop, shift, unshift, map, filter, reduce, forEach, slice, and splice.
  3. How do you merge two arrays?
    • Two arrays can be merged using the concat method or the spread operator (...).
  4. What is the difference between slice and splice?
    • slice returns a shallow copy of a portion of an array without modifying the original array, while splice changes the contents of an array by removing or replacing existing elements.
  5. How do you create an object in JavaScript?
    • An object can be created using the object literal notation ({}) or the Object constructor.

Strings

  1. How do you concatenate strings in JavaScript?
    • Strings can be concatenated using the + operator or template literals.
  2. What are some common string methods?
    • Common string methods include charAt, concat, includes, indexOf, replace, split, substr, substring, and toLowerCase.
  3. How do you convert a string to a number?
    • A string can be converted to a number using parseInt, parseFloat, or the unary plus (+) operator.
  4. What is the difference between substr and substring?
    • substr takes a start index and a length, while substring takes two indices, representing the start and end of the substring.
  5. How do you check if a string contains a substring?
    • Use the includes method to check if a string contains a substring.

Numbers

  1. How do you convert a number to a string?
    • A number can be converted to a string using the toString method or template literals.
  2. What are some common number methods?
    • Common number methods include toFixed, toPrecision, toExponential, parseInt, and parseFloat.
  3. How do you generate a random number in JavaScript?
    • Use the Math.random method to generate a random number between 0 (inclusive) and 1 (exclusive).
  4. What is the difference between parseInt and parseFloat?
    • parseInt parses a string and returns an integer, while parseFloat parses a string and returns a floating-point number.
  5. How do you round a number to a specific number of decimal places?
    • Use the toFixed method to round a number to a specific number of decimal places.

Date and Time

  1. How do you create a date object in JavaScript?
    • Use the Date constructor to create a date object.
  2. What are some common date methods?
    • Common date methods include getFullYear, getMonth, getDate, getHours, getMinutes, getSeconds, setFullYear, setMonth, and setDate.
  3. How do you get the current date and time?
    • Use new Date() to get the current date and time.
  4. How do you format a date in JavaScript?
    • Use methods like toLocaleDateString, toLocaleTimeString, or libraries like moment.js for formatting dates.
  5. How do you calculate the difference between two dates?
    • Subtract one date object from another to get the difference in milliseconds and then convert it to the desired unit (days, hours, etc.).

Miscellaneous

  1. What is a symbol in JavaScript?
    • A symbol is a unique and immutable primitive value used to create unique object keys.
  2. What is the Map object?
    • The Map object is a collection of key-value pairs where keys can be of any data type.
  3. What is the Set object?
    • The Set object is a collection of unique values.
  4. What is the WeakMap object?
    • The WeakMap object is a collection of key-value pairs where keys are objects and values can be of any data type, with keys being weakly referenced.
  5. What is the WeakSet object?
    • The WeakSet object is a collection of objects, where objects are weakly referenced.

Miscellaneous

  1. What is eval in JavaScript?
    • eval is a function that evaluates a string of JavaScript code in the current context.
  2. What is the difference between localStorage and sessionStorage?
    • localStorage stores data with no expiration date, while sessionStorage stores data for the duration of the page session.
  3. What are promises and how do they work?
    • Promises are objects representing the eventual completion or failure of an asynchronous operation, and they provide methods like then, catch, and finally.
  4. What is the purpose of the bind method?
    • The bind method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments.
  5. What is the difference between call and apply?call invokes a function with a given this value and arguments provided individually, while apply invokes a function with a given this value and arguments provided as an array.

Feel free to ask for more details on any specific topic or if you have any other questions!

Leave a Reply

Your email address will not be published. Required fields are marked *