Here are 100 Javascript Interview Question and Answer to help you prepare:
Basic Questions
- What is JavaScript?
- JavaScript is a high-level, interpreted programming language used to make web pages interactive.
- What are the data types supported by JavaScript?
- JavaScript supports the following data types: Number, String, Boolean, Object, Undefined, Null, Symbol, and BigInt.
- What is the difference between
==
and===
?==
checks for value equality with type coercion, while===
checks for both value and type equality.
- What is
NaN
in JavaScript?NaN
stands for “Not-a-Number” and indicates a value that is not a legal number.
- What is the use of the
typeof
operator?typeof
is used to determine the data type of a variable.
Intermediate Questions
- 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.
- 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.
- What is event delegation?
- Event delegation is a technique to handle events efficiently by using a single event listener to manage all child elements.
- What is the difference between
null
andundefined
?null
is an assigned value representing no value, whileundefined
means a variable has been declared but not assigned a value.
- What is the purpose of the
let
andconst
keywords?let
allows you to declare variables that are block-scoped, whileconst
allows you to declare block-scoped constants.
Advanced Questions
- 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.
- What are arrow functions?
- Arrow functions are a concise syntax for writing functions using the
=>
notation and do not have their ownthis
context.
- Arrow functions are a concise syntax for writing functions using the
- Explain the concept of Promises in JavaScript.
- Promises represent the eventual completion (or failure) of an asynchronous operation and its resulting value.
- What is the purpose of the
async
andawait
keywords?async
makes a function return a Promise, andawait
pauses the function execution until the Promise is resolved.
- What is the difference between
map
andforEach
?map
creates a new array with the results of calling a function on every element, whileforEach
executes a provided function once for each array element but does not return a new array.
Object-Oriented Programming
- What is prototypal inheritance?
- Prototypal inheritance is a feature in JavaScript where objects can inherit properties and methods from other objects.
- 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.
- What are getters and setters?
- Getters and setters are special methods that provide controlled access to an object’s properties.
- Explain the concept of
super
in JavaScript.super
is used to call functions on an object’s parent class.
- 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
- What is the DOM?
- The DOM (Document Object Model) is an interface that represents HTML or XML documents as a tree structure.
- How do you select DOM elements in JavaScript?
- DOM elements can be selected using methods like
getElementById
,getElementsByClassName
,getElementsByTagName
,querySelector
, andquerySelectorAll
.
- DOM elements can be selected using methods like
- 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.
- How do you add an event listener to a DOM element?
- Use the
addEventListener
method to attach an event handler to a DOM element.
- Use the
- What is the difference between
stopPropagation
andpreventDefault
?stopPropagation
prevents the event from bubbling up or capturing down, whilepreventDefault
prevents the default action associated with the event.
Asynchronous JavaScript
- What are callbacks?
- Callbacks are functions passed as arguments to other functions and executed after some operation has been completed.
- 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.
- What is a Promise chain?
- A Promise chain is a sequence of
.then()
methods, each returning a new Promise.
- A Promise chain is a sequence of
- What are the different states of a Promise?
- A Promise can be in one of three states: pending, fulfilled, or rejected.
- 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
- 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 thecatch
block.
- A try-catch block is used to handle exceptions, with code that might throw an error placed in the
- What is the difference between
throw
andreturn
?throw
is used to raise an exception, whilereturn
is used to return a value from a function.
- 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.
- The
- How do you create a custom error in JavaScript?
- Create a custom error by extending the
Error
class.
- Create a custom error by extending the
- 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
- 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.
- Why is it important to avoid global variables?
- Global variables can lead to naming collisions and unintended side effects across the codebase.
- What are pure functions?
- Pure functions are functions that have no side effects and return the same output for the same input.
- 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.
- 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
- What are ES6 features?
- Some ES6 features include let and const, arrow functions, template literals, destructuring, default parameters, classes, modules, and promises.
- What are template literals?
- Template literals are string literals allowing embedded expressions, using backticks
`
, with the syntax${expression}
for interpolation.
- Template literals are string literals allowing embedded expressions, using backticks
- What is destructuring in JavaScript?
- Destructuring is a syntax that allows unpacking values from arrays or properties from objects into distinct variables.
- What are default parameters?
- Default parameters allow function parameters to be initialized with default values if no value is provided.
- 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.
- The spread operator (
Functional Programming
- 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.
- What are higher-order functions?
- Higher-order functions are functions that take other functions as arguments or return them as results.
- What is immutability?
- Immutability is a principle where data cannot be modified once created, instead new data structures are created for changes.
- What is function composition?
- Function composition is the process of combining two or more functions to produce a new function.
- 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
- 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.
- What is lazy loading?
- Lazy loading is a design pattern that delays the initialization of an object until it is needed.
- What is tree shaking?
- Tree shaking is a technique used in JavaScript bundlers to remove dead code from the final bundle.
- 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.
- What are web workers?
- Web workers are a way to run JavaScript in background threads, allowing concurrent execution of scripts to improve performance.
Security
- 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.
- 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.
- 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.
- 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.
- 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
- 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.
- 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.
- What is the
fetch
API?- The
fetch
API provides a modern interface for making HTTP requests to servers and handling responses.
- The
- What are modules in JavaScript?
- Modules are reusable pieces of code that can be imported and exported between different files using
import
andexport
statements.
- Modules are reusable pieces of code that can be imported and exported between different files using
- What is a polyfill?
- A polyfill is code that provides modern functionality on older browsers that do not natively support it.
Regular Expressions
- What are regular expressions?
- Regular expressions are patterns used to match character combinations in strings.
- 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/
).
- A regular expression can be created using the
- What are some common methods used with regular expressions?
- Common methods include
test
,exec
,match
,replace
,search
, andsplit
.
- Common methods include
- What is the difference between
test
andexec
methods?- The
test
method checks if a pattern exists in a string and returnstrue
orfalse
, while theexec
method searches for a match and returns the result as an array ornull
.
- The
- What are character classes in regular expressions?
- Character classes define a set of characters to match, such as
[abc]
for matchinga
,b
, orc
.
- Character classes define a set of characters to match, such as
Arrays and Objects
- How do you create an array in JavaScript?
- An array can be created using the array literal notation (
[]
) or theArray
constructor.
- An array can be created using the array literal notation (
- What are some common array methods?
- Common array methods include
push
,pop
,shift
,unshift
,map
,filter
,reduce
,forEach
,slice
, andsplice
.
- Common array methods include
- How do you merge two arrays?
- Two arrays can be merged using the
concat
method or the spread operator (...
).
- Two arrays can be merged using the
- What is the difference between
slice
andsplice
?slice
returns a shallow copy of a portion of an array without modifying the original array, whilesplice
changes the contents of an array by removing or replacing existing elements.
- How do you create an object in JavaScript?
- An object can be created using the object literal notation (
{}
) or theObject
constructor.
- An object can be created using the object literal notation (
Strings
- How do you concatenate strings in JavaScript?
- Strings can be concatenated using the
+
operator or template literals.
- Strings can be concatenated using the
- What are some common string methods?
- Common string methods include
charAt
,concat
,includes
,indexOf
,replace
,split
,substr
,substring
, andtoLowerCase
.
- Common string methods include
- 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.
- A string can be converted to a number using
- What is the difference between
substr
andsubstring
?substr
takes a start index and a length, whilesubstring
takes two indices, representing the start and end of the substring.
- How do you check if a string contains a substring?
- Use the
includes
method to check if a string contains a substring.
- Use the
Numbers
- How do you convert a number to a string?
- A number can be converted to a string using the
toString
method or template literals.
- A number can be converted to a string using the
- What are some common number methods?
- Common number methods include
toFixed
,toPrecision
,toExponential
,parseInt
, andparseFloat
.
- Common number methods include
- 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).
- Use the
- What is the difference between
parseInt
andparseFloat
?parseInt
parses a string and returns an integer, whileparseFloat
parses a string and returns a floating-point number.
- 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.
- Use the
Date and Time
- How do you create a date object in JavaScript?
- Use the
Date
constructor to create a date object.
- Use the
- What are some common date methods?
- Common date methods include
getFullYear
,getMonth
,getDate
,getHours
,getMinutes
,getSeconds
,setFullYear
,setMonth
, andsetDate
.
- Common date methods include
- How do you get the current date and time?
- Use
new Date()
to get the current date and time.
- Use
- How do you format a date in JavaScript?
- Use methods like
toLocaleDateString
,toLocaleTimeString
, or libraries likemoment.js
for formatting dates.
- Use methods like
- 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
- What is a symbol in JavaScript?
- A symbol is a unique and immutable primitive value used to create unique object keys.
- What is the
Map
object?- The
Map
object is a collection of key-value pairs where keys can be of any data type.
- The
- What is the
Set
object?- The
Set
object is a collection of unique values.
- The
- 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.
- The
- What is the
WeakSet
object?- The
WeakSet
object is a collection of objects, where objects are weakly referenced.
- The
Miscellaneous
- What is
eval
in JavaScript?eval
is a function that evaluates a string of JavaScript code in the current context.
- What is the difference between
localStorage
andsessionStorage
?localStorage
stores data with no expiration date, whilesessionStorage
stores data for the duration of the page session.
- 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
, andfinally
.
- Promises are objects representing the eventual completion or failure of an asynchronous operation, and they provide methods like
- What is the purpose of the
bind
method?- The
bind
method creates a new function that, when called, has itsthis
keyword set to the provided value, with a given sequence of arguments.
- The
- What is the difference between
call
andapply
? –call
invokes a function with a giventhis
value and arguments provided individually, whileapply
invokes a function with a giventhis
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!