đĄ 30 Essential Javascript Interview Questions and Answers From Easy to Hard
Hey there! Iâm Syakir, a senior front-end engineer.
Back in the days when i was looking for job, i had plenty of interview experiences as Front-end / Javascript developer. Iâve been through the process many times and learned a lot along the way.
I know how tough technical interviews can be, especially when facing tricky JavaScript questions.
Thatâs why, in this article, Iâve put together this list of 30 essential javascript interview questions. I sort them from simple basics to more advanced topics you might encounter.
Iâve kept the answers comprehensive with code examples, but to the point, just like youâll need them in an interview. By practicing these, youâll feel more prepared and confident.
You might want to summarize key points in each question, so it will be easy to remember them.
This article is written with the help of AI. The question list are based on experiences and some references. The answers are fact-checked and the code examples are also manually tested.
Basic Javascript Interview Questions
1. What are the different data types in JavaScript?
In JavaScript, there are several data types:
Primitive types:
- Number: Represents both integer and floating-point numbers
- String: Represents textual data
- Boolean: Represents true or false
- Undefined: Represents a variable that has been declared but not assigned a value
- Null: Represents a deliberate non-value
- Symbol: Represents a unique identifier (introduced in ES6)
- BigInt: Represents integers larger than 2^53 - 1 (introduced in ES11)
Object type:
- Object: Represents a collection of key-value pairs
Itâs important to note that arrays and functions are also objects in JavaScript, but they have special behaviors and properties. Additionally, the typeof
operator can be used to determine the type of a value, although it has some quirks (e.g., typeof null
returns âobjectâ, which is a known legacy issue in the language).
Further reads:
2. What is hoisting in JavaScript?
Hoisting in JavaScript is a behavior where variable and function declarations are conceptually moved to the top of their containing scope during the compilation phase, before code execution.
Key points:
-
Variable declarations using
var
are hoisted and initialized withundefined
. -
Function declarations are fully hoisted, including their implementation.
-
let
andconst
declarations are hoisted but not initialized, creating a temporal dead zone. -
Only declarations are hoisted, not initializations or assignments.
-
This behavior can lead to unexpected results, especially with
var
.
Hereâs a code example that demonstrates hoisting behavior in JavaScript:
Further read: Javascript Hoisting
3. What is the difference between var
, let
, and const
?
var
:
- Function-scoped or globally-scoped
- Hoisted and initialized with
undefined
- Can be reassigned
- Can be declared without initialization
- Creates a property on the global object
let
:
- Block-scoped
- Hoisted but not initialized (temporal dead zone)
- Can be reassigned
- Can be declared without initialization
- Does not create a property on the global object
const
:
- Block-scoped
- Hoisted but not initialized (temporal dead zone)
- Cannot be reassigned after initialization
- Must be initialized upon declaration
- Does not create a property on the global object
A brief code example to illustrate these differences:
4. Explain how ==
and ===
differ in JavaScript.
In JavaScript, ==
and ===
are comparison operators, but they behave differently in terms of type comparison.
-
==
(Loose Equality): It compares two values for equality after performing type coercion, which means it tries to convert the operands to the same type before comparing. This can lead to unexpected results when types differ. -
===
(Strict Equality): It compares both the value and the type of the operands. No type coercion occurs, so the comparison is stricter.
Recommendation: Use ===
for comparisons to avoid unexpected type coercion and ensure accuracy.
5. What is a function in JavaScript?
A function in JavaScript is a block of reusable code designed to perform a specific task. It allows you to encapsulate a set of statements that can be executed whenever you call the function. Functions help organize code, promote reuse, and make programs more modular and maintainable.
Types of Functions in JavaScript:
-
Function Declaration: A named function that can be called before its declaration due to hoisting.
-
Function Expression: A function assigned to a variable. Itâs not hoisted, so it can only be called after its definition.
-
Arrow Function: A concise way to define functions, introduced in ES6. It also handles the
this
keyword differently. -
Immediately Invoked Function Expression (IIFE): A function that runs immediately after itâs defined.
6. What is an arrow function, and how does it differ from a regular function?
An arrow function is a more concise syntax for writing functions in JavaScript, introduced in ES6. It offers several key differences from regular (traditional) functions, especially in terms of handling the this
keyword and syntax.
An arrow function uses the =>
(âfat arrowâ) syntax.
Key Differences Between Arrow Functions and Regular Functions:
-
this
Binding:- Arrow Functions: Do not have their own
this
. Instead, they inheritthis
from the surrounding (lexical) context in which they are defined. - Regular Functions: Have their own
this
, which can change based on how the function is called (e.g., method calls, event handlers).
- Arrow Functions: Do not have their own
-
Constructors:
- Arrow Functions: Cannot be used as constructors. If you try to use
new
with an arrow function, it will throw an error. - Regular Functions: Can be used as constructors with the
new
keyword to create object instances.
- Arrow Functions: Cannot be used as constructors. If you try to use
-
arguments
Object:- Arrow Functions: Do not have their own
arguments
object. If you need access to the arguments of an arrow function, you have to use rest parameters (...args
). - Regular Functions: Have access to the
arguments
object, which is an array-like object containing the functionâs parameters.
- Arrow Functions: Do not have their own
Arrow functions are more concise and do not have their own this
or arguments
object.
Use arrow functions when you need a function to inherit this
from the surrounding context, or when you need a shorter syntax. Use regular functions when you need dynamic this
, constructors, or access to the arguments
object.
7. What is null
vs undefined
in JavaScript?
In JavaScript, null
and undefined
both represent the absence of value but differ in usage:
-
undefined
: Automatically assigned to uninitialized variables or missing function arguments. -
null
: Explicitly set to indicate âno value.â
Key Differences:
null == undefined
istrue
, butnull === undefined
isfalse
.undefined
is a type, whilenull
is an object.
Use null
to explicitly clear values; let undefined
be the default for uninitialized ones.
8. What are template literals?
Template literals in JavaScript use backticks (`
) for flexible string creation. Key features:
-
String Interpolation: Embed variables and expressions with
${}
. -
Multiline Strings: Easily create strings over multiple lines.
-
Expression Evaluation: Directly evaluate expressions inside strings.
Summary:
- Backticks and
${}
allow dynamic and multiline strings efficiently.
9. What is a closure in JavaScript?
A closure in JavaScript is a feature where a function retains access to its lexical scope, even after the function has finished executing. This allows the inner function to access variables from its outer (enclosing) function.
Key Points:
- Lexical Scope: Closures capture variables from their creation context.
- Encapsulation: They enable data encapsulation and can be used to create private variables.
In this example:
increment
retains access tocount
, even aftercreateCounter
has finished executing.count
is not accessible directly from outsidecreateCounter
, demonstrating encapsulation.
Closures allow functions to access variables from their outer scope, enabling powerful patterns like data hiding and stateful functions.
10. What is the difference between function declarations and function expressions?
Function declarations and function expressions are two ways to define functions in JavaScript. Declarations use function
keyword, while expressions assign a function to a variable.
-
Function Declarations:
- Hoisted; callable before defined.
- Available throughout the entire scope.
-
Function Expressions:
- Not hoisted; callable only after defined.
- Scoped to the variable holding the function.
Moderate Javascript Interview Questions
11. What is the this
keyword in JavaScript, and how does it behave in different contexts?
The this
keyword in JavaScript refers to the context in which a function is executed. Its value depends on how the function is called:
- In Global Context,
this
refers to the global object (window
in browsers).
- In Object Methods,
this
refers to the object the method is called on.
- In a Constructor Function,
this
refers to the newly created instance.
- In Arrow Functions,
this
refers to their enclosing context. Arrow functions do not have their ownthis
.
- In Event Handlers,
this
refers to the element that triggered the event.
12. What is event delegation?
Event delegation is a technique where you attach a single event listener to a parent element to handle events for its child elements, instead of attaching listeners to each child. It leverages event bubbling and can improve performance and memory usage, especially for dynamically created elements.
This code adds one listener to the parent <ul>
, handling clicks on all child <li>
elements, even those added dynamically after the initial page load.
13. What are promises, and how do they differ from callbacks?
Promises are objects representing the eventual completion or failure of an asynchronous operation. They provide a cleaner, more manageable way to handle asynchronous code compared to callbacks.
Callbacks are functions passed as arguments to be executed after a task completes, but they can lead to âcallback hellâ when nested.
Key Differences
- Chaining: Promises allow easy chaining of asynchronous operations.
- Error handling: Promises use .catch() for centralized error handling.
- State: Promises have clear states (pending, fulfilled, rejected).
- Readability: Promises often lead to more readable code, avoiding âcallback hellâ.
14. What is destructuring in JavaScript?
Destructuring in JavaScript is a syntax that allows you to extract values from arrays or properties from objects and assign them to variables in a more concise way. It provides a convenient method to unpack values from data structures into distinct variables.
Key points:
- Works with both arrays and objects
- Allows default values
- Can be used in function parameters
- Supports nested destructuring
- Enables easy variable swapping
This syntax enhances code readability and reduces the amount of code needed to access data from complex structures.
Further reading:
15. What is the spread operator (...
), and how is it used?
The spread operator (...
) in JavaScript is used to expand iterable objects into individual elements. It has multiple use cases:
- Array manipulation: Copying, concatenating, or inserting elements.
- Function arguments: Passing array elements as separate arguments.
- Object literals: Copying properties from one object to another.
- Rest parameters: Collecting multiple arguments into an array.
Example demonstrating these uses:
The spread operator enhances code readability and provides a concise way to work with arrays and objects.
16. What are higher-order functions?
Higher-order functions are functions that can take other functions as arguments or return functions as their results. They enable powerful abstractions and are a key concept in functional programming.
Key points:
- Can accept functions as arguments
- Can return functions
- Enable function composition and abstraction
- Common in array methods like map, filter, and reduce
- Facilitate code reuse and modularity
Example:
This example demonstrates both accepting functions as arguments and returning functions, showcasing the versatility of higher-order functions.
17. What is prototypal inheritance in JavaScript?
Prototypal inheritance in JavaScript is a mechanism where objects can inherit properties and methods from other objects. Each object has an internal link to another object called its prototype. When a property is accessed on an object and not found, JavaScript looks for it in the prototype chain.
Key points:
- Objects inherit from objects.
- Thereâs a prototype chain.
- Itâs dynamic - changes to the prototype affect all inheriting objects.
- Itâs the basis for JavaScriptâs object-oriented programming model.
In this example, cat
inherits the sayHello
method from Animal.prototype
.
18. What is the difference between map()
, forEach()
, and filter()
?
map()
, forEach()
, and filter()
are array methods in JavaScript with distinct purposes:
map()
: Transforms each element of an array, returning a new array of the same length.forEach()
: Executes a function on each array element, but doesnât return a new array.filter()
: Creates a new array with elements that pass a test function.
Key differences:
map()
andfilter()
return new arrays;forEach()
doesnât.map()
transforms elements;filter()
selects elements;forEach()
just iterates.- Use
map()
for transformation,filter()
for selection, andforEach()
for side effects.
19. What are call()
, apply()
, and bind()
methods?
call()
, apply()
, and bind()
are methods used to manipulate the this
context in JavaScript functions:
call()
: Invokes a function with a specifiedthis
value and arguments provided individually.apply()
: Similar tocall()
, but accepts arguments as an array.bind()
: Returns a new function with a fixedthis
value, without executing it immediately.
Example:
These methods are crucial for controlling function context, especially in scenarios involving callbacks, event handlers, or when borrowing methods from other objects.
20. What is the event loop in JavaScript?
The event loop in JavaScript is a mechanism that handles asynchronous operations. Itâs a single-threaded process that manages code execution, events, and asynchronous tasks. It continuously:
- Checks the call stack: If empty, it moves on.
- Processes tasks from the task queue: These are callbacks from asynchronous operations (e.g., network requests, timers).
- Waits for new events: Like user interactions or browser messages.
This non-blocking approach allows JavaScript to feel responsive even while handling long-running tasks.
In this example, setTimeout
is placed in the task queue and only executed after the synchronous code (like console.log(âEndâ)) finishes. The event loop handles moving the callback from the queue to the call stack when ready.
21. What is the difference between synchronous and asynchronous code in JavaScript?
The difference between synchronous and asynchronous code in JavaScript lies in how tasks are executed:
- Synchronous code is executed line by line, blocking further execution until the current task is completed. It waits for each operation to finish before moving on to the next one.
- Asynchronous code allows the program to continue executing without waiting for an operation (like fetching data or reading files) to complete. The result of the async operation is handled later, often with callbacks, promises, or
async/await
.
In the async example, fetchData
runs in the background, allowing console.log('End')
to execute without waiting for it.
22. What are async
and await
in JavaScript?
async
and await
are modern JavaScript features for handling asynchronous operations in a cleaner, more readable way compared to promises.
Key points:
async
functions return a promise, making them inherently asynchronous.await
pauses the execution insideasync
functions, waiting for a promise to resolve or reject.- They eliminate the need for
.then()
chaining, improving code readability. - Error handling can be done using
try...catch
withinasync
functions.
In this example, await
pauses the function until the fetch resolves, making the code easier to follow than using .then()
chains.
23. What is the difference between shallow copy and deep copy in JavaScript?
In JavaScript, shallow copy and deep copy refer to how objects and arrays are duplicated.
-
Shallow Copy: Copies the objectâs top level. Nested objects or arrays are still referenced, not cloned. Changes to nested structures affect the original object.
-
Deep Copy: Recursively copies all levels of the object, creating entirely new instances of nested objects and arrays. Changes do not affect the original.
Further reading:
24. What is a module in JavaScript, and how are they implemented?
Modules in JavaScript are a way to encapsulate and organize code into separate files. They help manage dependencies and improve code maintainability by allowing functions, objects, or values to be imported and exported between files.
Key points:
- Encapsulation: Modules keep code isolated in separate files.
- Imports and Exports: Use
import
andexport
to share code between files. - ES6 Standard: Modern JavaScript uses ES6 module syntax.
module.js
main.js
In this example, greet
is exported from module.js
and imported into main.js
, demonstrating how modules allow code sharing and organization.
Advanced Javascript Interview Questions
25. How does garbage collection work in JavaScript?
Garbage collection in JavaScript is the process of automatically managing memory by cleaning up unused objects and freeing their memory space. JavaScript uses a form of garbage collection called mark-and-sweep.
Key points:
- Marking: The garbage collector identifies which objects are still in use by marking them, starting from global objects and roots (like the call stack).
- Sweeping: It then identifies objects that are no longer reachable (not marked) and reclaims their memory.
- Automatic: Garbage collection is automatic and managed by the JavaScript engine, so developers donât need to manually free memory.
In this example, after keepObject
is set to null
, largeArray
becomes eligible for garbage collection, though the exact timing of cleanup is managed by the JavaScript engine.
26. What is the new
keyword, and how does it work in JavaScript?
The new
keyword in JavaScript is used to create instances of user-defined objects or built-in objects. It sets up a new object, binds this
to that object, and initializes the object with properties and methods defined in a constructor function.
Key points:
- Creates a new object: A new, empty object is created.
- Sets the prototype: The prototype of the new object is set to the prototype of the constructor function.
- Binds
this
: Inside the constructor,this
refers to the new object. - Returns the object: The newly created object is returned (unless the constructor explicitly returns a different object).
In this example, new Person('John')
creates a new object with name
set to âJohnâ and sayHello
as a method, demonstrating how the new
keyword sets up and initializes the object.
27. What is Object.create()
, and how does it differ from using a constructor function?
Object.create()
is a method that creates a new object with the specified prototype object and properties. It allows for setting up inheritance without needing a constructor function.
Key points:
- Directly sets prototype:
Object.create()
sets the prototype of the new object directly, providing more control over inheritance. - No need for a constructor: Unlike constructor functions, it does not involve the
new
keyword orthis
binding. - Flexible prototype setup: You can define the prototype and additional properties in one step.
Difference:
Object.create()
directly sets the prototype without a constructor, offering a more flexible way to create objects with a specific prototype.- Constructor functions create instances that inherit from the prototype chain set up via
prototype
.
28. What is memoization in JavaScript, and how can it improve performance?
Memoization in JavaScript is an optimization technique that caches the results of expensive function calls and returns the cached result when the same inputs occur again. This reduces the need for repeated computations, improving performance for functions with overlapping inputs.
Key points:
- Caches Results: Stores function results based on input arguments.
- Reduces Computation: Avoids redundant calculations.
- Improves Performance: Especially useful for functions that are called frequently with the same arguments.
In this example, memoize
caches the results of the factorial
function. Subsequent calls with the same argument return the cached result instead of recomputing it.
29. What is the difference between classical inheritance and prototypal inheritance?
Classical Inheritance vs. Prototypal Inheritance
Classical Inheritance is based on the concept of classes and objects. Classes are blueprints for creating objects, and inheritance is achieved by creating subclasses that extend a base class. This is common in object-oriented programming languages like Java or C++.
Prototypal Inheritance in JavaScript allows objects to directly inherit from other objects. Instead of creating subclasses, objects can be created based on existing objects, and their prototype can be modified to include inherited properties and methods.
Key points:
- Classical Inheritance uses classes and constructors, with a clear hierarchy of base and derived classes.
- Prototypal Inheritance uses prototypes, where objects inherit directly from other objects.
- Classical Inheritance is often more rigid and requires defining classes upfront.
- Prototypal Inheritance is more flexible and dynamic, allowing for more direct object-to-object inheritance.
In the classical example, Dog
inherits from Animal
using class-based inheritance. In the prototypal example, dog2
inherits from animal
directly using the prototype chain.
30. What are generator functions, and how are they used?
Generator functions are special functions in JavaScript that can pause their execution and resume later. They are defined using the function*
syntax and use the yield
keyword to produce a series of values.
Key points:
- Defined with
function*
: Creates a generator function. - Uses
yield
: Pauses execution and returns a value. - Returns an iterator: Allows iterating over values produced by
yield
. - Resumable: Can resume from where it was paused using
.next()
.
In this example, numberGenerator
is a generator function that yields an infinite sequence of numbers. The next()
method is used to resume the generator and get the next value.
Conclusion
Youâve now covered 30 essential JavaScript interview questions. From basics to advanced concepts, these questions should give you a solid foundation for your next interview. Practicing these will help you explain your thought process clearly and confidently.
If you found this helpful, feel free to share it with others or drop a comment below with your thoughts or questions. Iâd love to hear from you.
Good luck with your interviews!