Here are the answers to the JavaScript interview questions:
1. Basic Concepts
- What are the different data types in JavaScript?
JavaScript has the following data types:- Primitive Types:
String
,Number
,Boolean
,Null
,Undefined
,Symbol
,BigInt
- Non-Primitive Types:
Object
(includingArray
,Function
, and others)
- Primitive Types:
- Explain the difference between
var
,let
, andconst
.var
: Function-scoped, can be re-declared and updated, hoisted to the top of the function.let
: Block-scoped, cannot be re-declared in the same scope, can be updated, not hoisted to the top of the block.const
: Block-scoped, cannot be re-declared or updated (except for object properties), not hoisted.
- What is the difference between
==
and===
?==
: Loose equality operator; compares two values for equality after performing type conversion.===
: Strict equality operator; compares two values for equality without type conversion (both type and value must match).
- How does JavaScript handle automatic type conversion?
JavaScript uses type coercion to automatically convert one data type to another when operators involve mixed types. For example,5 + '5'
results in the string'55'
due to string coercion. - What is the difference between
null
andundefined
?null
: Represents an intentional absence of value. It is explicitly set by the developer.undefined
: Represents the absence of value where no value has been assigned, typically used by JavaScript when a variable is declared but not initialized.
2. Functions and Scope
- What is the difference between function declaration and function expression?
- Function Declaration: A named function that is defined using the
function
keyword. It is hoisted to the top of its scope, so it can be called before it’s defined. - Function Expression: A function assigned to a variable. It is not hoisted, so it cannot be called before its definition.
- Function Declaration: A named function that is defined using the
- Explain closures in JavaScript.
A closure is a function that retains access to its lexical scope even when the function is executed outside that scope. It allows a function to “remember” the environment in which it was created. - What is hoisting in JavaScript?
Hoisting is JavaScript’s behavior of moving declarations (variables and functions) to the top of their containing scope during compilation. Variables declared withvar
are hoisted and initialized asundefined
, whilelet
andconst
declarations are hoisted but not initialized. - How does JavaScript handle scope and scope chain?
JavaScript uses lexical scoping, meaning that functions are executed using the scope in which they were defined, not the scope in which they are called. The scope chain is the mechanism that JavaScript uses to resolve variable references; it checks the current scope, then moves up to outer scopes until it finds the variable or reaches the global scope. - What are arrow functions, and how do they differ from regular functions?
Arrow functions are a shorthand syntax for writing functions in JavaScript:- They do not have their own
this
context; they inheritthis
from the surrounding scope. - They cannot be used as constructors (
new
cannot be used with them). - They have implicit returns for single expression functions.
- They do not have their own
3. Objects and Prototypes
- How do you create an object in JavaScript?
Objects can be created in JavaScript using several methods:- Object literal:
const obj = {};
- Constructor function:
const obj = new Object();
Object.create()
:const obj = Object.create(null);
- ES6 classes:
class MyClass { constructor() { this.property = value; } }
- Object literal:
- What is the prototype chain?
The prototype chain is a mechanism through which JavaScript objects inherit properties and methods from other objects. Each object has a prototype, which is another object, and this chain of prototypes is used to resolve methods or properties that are not found directly on an object. - What are ES6 classes, and how do they relate to prototypes?
ES6 classes are a syntactical sugar over JavaScript’s existing prototype-based inheritance. They provide a clearer and more concise syntax to create constructor functions and handle inheritance, but under the hood, they still use prototypes. - Explain the concept of
this
keyword in JavaScript.
Thethis
keyword refers to the object from which a function is called. In a global context,this
refers to the global object (window
in browsers). In methods,this
refers to the object the method is called on. The value ofthis
can vary based on how a function is invoked (e.g., as a method, function, or usingcall
/apply
/bind
). - What are getters and setters in JavaScript?
Getters and setters are special methods in objects that allow you to define how properties are accessed and mutated. Getters are used to access properties, while setters are used to update properties.
4. Asynchronous JavaScript
- What is the event loop, and how does it work?
The event loop is the mechanism in JavaScript that allows it to handle asynchronous operations. It continually checks the call stack and the message queue (or callback queue). If the stack is empty, the event loop picks the first function from the queue and pushes it onto the stack to execute it. - Explain the difference between
setTimeout
andsetInterval
.setTimeout
: Executes a function after a specified delay (in milliseconds).setInterval
: Repeatedly executes a function at specified intervals (in milliseconds) until cleared usingclearInterval
.
- What are Promises, and how do they work?
A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states:- Pending: Initial state, neither fulfilled nor rejected.
- Fulfilled: Operation completed successfully.
- Rejected: Operation failed.
Promises handle asynchronous operations by chaining.then()
for fulfilled cases and.catch()
for errors.
- Explain async/await in JavaScript.
async
andawait
are syntactic sugar over Promises, providing a way to write asynchronous code that looks synchronous.async
functions always return a Promise, andawait
pauses the function execution until the Promise is resolved. - What are callbacks, and how are they used in JavaScript?
A callback is a function passed into another function as an argument to be executed later. Callbacks are often used for handling asynchronous operations before Promises were introduced.
5. Error Handling
- How do you handle errors in JavaScript?
Errors in JavaScript can be handled usingtry/catch
blocks,throw
statements, and using error handling callbacks or methods like.catch()
for Promises. - What is a try/catch block, and how is it used?
Atry/catch
block is used to handle exceptions in JavaScript:try { // code that might throw an error } catch (error) { // code to handle the error }
If an error occurs within thetry
block, the control jumps to thecatch
block. - What is the difference between
throw
andconsole.error()
?throw
: Immediately stops the execution of the script and throws an exception that can be caught bytry/catch
.console.error()
: Logs an error message to the console without stopping the execution.
6. JavaScript in the Browser
- How does JavaScript interact with the DOM?
JavaScript interacts with the DOM (Document Object Model) to manipulate the structure, style, and content of web pages using methods likedocument.getElementById()
,document.querySelector()
,element.innerHTML
,element.style
, and event listeners. - What are event listeners, and how do they work?
Event listeners are functions that wait for specific events (like clicks, keypresses) to happen on elements. They can be added usingelement.addEventListener(event, function)
and are triggered when the event occurs. - What is event delegation?
Event delegation is a technique of handling events at a higher level in the DOM hierarchy (usually at a parent element) rather than attaching event listeners to each target element. It works by taking advantage of event bubbling, where the event propagates up the DOM tree. - Explain the concept of bubbling and capturing in DOM events.
- Bubbling: The event starts from the target element and bubbles up to the root element (usually the document).
- Capturing: The event starts from the root element and propagates down to the target element.
Event listeners can be set to trigger during the capturing or bubbling phase.
- What is the difference between
localStorage
,sessionStorage
, andcookies
?localStorage
: Stores data with no expiration time. The data persists even after the browser is closed and reopened.
– sessionStorage
: Stores data for the duration of the page session. The data is cleared when the page is closed.
– Cookies: Small pieces of data stored in the browser with expiration dates. They are sent to the server with every HTTP request.
7. ES6+ Features
- What are template literals, and how are they used?
Template literals are string literals that allow embedded expressions. They are enclosed by backticks (`
) and can contain placeholders indicated by${expression}
:const name = 'John'; const greeting = `Hello, ${name}!`;
- What are destructuring assignments in JavaScript?
Destructuring assignment is a syntax that allows unpacking values from arrays or properties from objects into distinct variables:const [a, b] = [1, 2]; // Array destructuring const {name, age} = {name: 'John', age: 30}; // Object destructuring
- Explain the spread and rest operators.
- Spread Operator (
...
): Expands elements of an iterable (like an array) into individual elements. Used in function arguments, array literals, and object literals.
const arr = [1, 2, 3]; console.log(...arr); // 1 2 3
- Rest Operator (
...
): Collects all remaining elements into an array. Used in function parameters and destructuring assignments.
function sum(...numbers) { return numbers.reduce((acc, num) => acc + num, 0); }
- Spread Operator (
- What are modules in JavaScript, and how are they used?
Modules in JavaScript allow you to encapsulate code in separate files and export functions, objects, or values for use in other files. ES6 introduced theimport
andexport
syntax for modules:// export.js export const name = 'John'; // import.js import { name } from './export.js';
- What is the difference between
map()
,filter()
, andreduce()
methods in arrays?map()
: Creates a new array with the results of calling a provided function on every element in the array.filter()
: Creates a new array with all elements that pass the test implemented by the provided function.reduce()
: Executes a reducer function on each element of the array, resulting in a single output value.
8. Miscellaneous
- What is the difference between synchronous and asynchronous code in JavaScript?
- Synchronous Code: Executes in a sequence, blocking subsequent operations until the current one completes.
- Asynchronous Code: Executes independently of the main program flow, allowing other operations to run without waiting for the asynchronous operation to complete.
- Explain the concept of
debounce
andthrottle
functions.debounce()
: Delays the execution of a function until a certain amount of time has passed since the last time it was invoked. It is useful for limiting the rate of execution of functions triggered by rapid events (e.g., window resize).throttle()
: Ensures a function is executed at most once within a specified time frame, no matter how many times it is triggered.
- How does JavaScript handle memory management and garbage collection?
JavaScript uses automatic memory management and garbage collection, which tracks object references and reclaims memory by removing objects that are no longer reachable in the code. - What are higher-order functions?
A higher-order function is a function that either takes one or more functions as arguments, returns a function, or both. Examples includemap
,filter
, andreduce
. - What is the difference between a shallow copy and a deep copy in JavaScript?
- Shallow Copy: Copies only the immediate properties of an object. Nested objects are not copied, so changes to nested objects in the copied object will affect the original.
- Deep Copy: Recursively copies all properties of an object, including nested objects, so that the copy is entirely independent of the original.
9. Framework/Library Related
- Explain the difference between JavaScript and TypeScript.
TypeScript is a superset of JavaScript that adds static typing, interfaces, and other features to enhance code quality and maintainability. JavaScript is dynamically typed, while TypeScript’s type system helps catch errors during development. - What are the main features of ES6/ES7?
- ES6 (ES2015): Introduced features like
let
andconst
, arrow functions, classes, template literals, destructuring, default parameters, spread/rest operators, modules, and Promises. - ES7 (ES2016): Introduced the
exponentiation operator (**)
andArray.prototype.includes
.
- ES6 (ES2015): Introduced features like
- How do you manage state in React?
State in React can be managed using:- Local state with the
useState
hook. - Context API for global state.
- External state management libraries like Redux, MobX, or Zustand.
- Local state with the
- What is the Virtual DOM, and how does it work in React?
The Virtual DOM is an in-memory representation of the real DOM. React updates the Virtual DOM first, then compares it with the previous version (using a diffing algorithm), and efficiently updates only the parts of the actual DOM that have changed. - What is the purpose of Redux or any other state management library?
Redux and other state management libraries are used to manage the application state in a predictable manner. They centralize state in a single store, which can be accessed by any component in the application, making state management more consistent and easier to debug.
41