0% found this document useful (0 votes)
48 views

Frontend Questions

Fronten Interview Questions
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Frontend Questions

Fronten Interview Questions
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

HTML Interview Questions

1. What is HTML, and what are its key features?


HTML (HyperText Markup Language) is the standard language used to create web pages. It structures
the content on the web by using elements (tags) that define different parts of a webpage like
headings, paragraphs, links, images, etc.
Key features of HTML:
• Elements and Tags: Basic building blocks of HTML (e.g., <p>, <h1>, <a>).
• Attributes: Used inside tags to provide additional information (e.g., src in an <img> tag to
specify image source).
• Media Support: Embedding images, videos, and audio.
• Hyperlinks: Creating links between web pages.
• Forms: Collecting user input through forms (e.g., text boxes, checkboxes, buttons).

2. What are semantic HTML tags? Why are they important?


Semantic HTML tags clearly describe the purpose of the element. For example, <header>, <footer>,
<article>, and <section> tell you what kind of content they contain.
Importance:
• Accessibility: Helps screen readers and other assistive technologies understand the structure
of the page.
• SEO (Search Engine Optimization): Search engines can better understand the content, which
can improve rankings.
• Code Readability: Easier for developers to read and maintain.

3. What’s the difference between <div> and <span> tags?


• <div> (division): A block-level element used to group larger sections of content. It creates a
block of space.
• <span>: An inline element used for grouping smaller bits of text or elements within a line
without starting a new line.
Example:
• Use <div> for sections like articles or containers.
• Use <span> for styling a word within a sentence.

4. Explain the difference between HTML5 and HTML4.


• HTML5 is an updated version of HTML4, bringing new features:
o New Semantic Tags: Like <header>, <footer>, <nav>, <article>.
o Multimedia Support: Direct embedding of audio and video using <audio> and <video>
tags.
o Local Storage: HTML5 introduced local storage for storing data in the browser.
o Geolocation and APIs: Supports new APIs like Geolocation and WebSockets.
• HTML4 doesn’t support many of these features and requires more external tools (like Flash)
for multimedia.

5. How do you optimize images and assets for web performance?


To optimize web performance, you should:
• Compress images: Use tools like TinyPNG to reduce file size without losing quality.
• Use correct formats: For example, use JPEG for photos and PNG for images with transparency.
WebP is even more optimized.
• Lazy Loading: Load images only when they are needed (when the user scrolls to them).
• Minimize and combine CSS/JS: Compress and combine assets like CSS and JavaScript files to
reduce server requests.
• Use CDN: Content Delivery Networks (CDNs) can serve assets faster by distributing them
across multiple servers globally.

6. What are HTML meta tags? Why are they important?


Meta tags provide metadata about the HTML document. They are placed inside the <head> section.
Importance:
• SEO: Meta tags like <meta name="description"> give search engines a brief description of the
page, improving search rankings.
• Charset: <meta charset="UTF-8"> specifies the character encoding, ensuring proper display of
text.
• Viewport: <meta name="viewport" content="width=device-width, initial-scale=1.0"> ensures
mobile-friendly design by controlling page scaling on different devices.

7. What is the purpose of the alt attribute in image tags?


The alt (alternative text) attribute provides a textual description of an image.
Purpose:
• Accessibility: Helps visually impaired users by providing descriptive text for screen readers.
• SEO: Search engines use alt text to understand the content of the image.
• Fallback: Displays the alt text if the image fails to load.

8. How would you implement accessibility in HTML?


To make a website accessible:
• Use Semantic HTML: Tags like <header>, <nav>, <footer> help assistive technologies
understand the page structure.
• Alt Text for Images: Include alt text in images so screen readers can describe the image to
users.
• Labels for Form Elements: Use <label> for form elements so users know what information to
enter.
• Keyboard Navigation: Ensure users can navigate the site using only a keyboard (e.g., use of
tabindex).
• Aria Attributes: Use ARIA (Accessible Rich Internet Applications) attributes like aria-label to
provide additional context to assistive technologies.

9. What is the difference between block-level and inline elements?


• Block-level elements: Take up the full width of the page and start on a new line. Examples
include <div>, <h1>, <p>, <section>.
• Inline elements: Do not start on a new line and only take up as much space as their content.
Examples include <span>, <a>, <strong>.
Key difference: Block elements create vertical space (line breaks), while inline elements stay within
the same line.

10. What are data attributes in HTML, and when would you use them?
Data attributes allow you to store custom data directly in HTML elements using the data-* format.
Example: <div data-user-id="12345">Username</div>
When to use them:
• Custom Data Storage: When you need to store small amounts of data that JavaScript can
access and manipulate (e.g., storing a user’s ID or additional information).
• JavaScript Interaction: When you want to easily access this data in your JavaScript code
without making an API call or creating a new variable.

CSS Interview Questions


1. What is the box model in CSS, and how does it work?
The CSS box model represents the structure of how elements are displayed on a web page. Every
element is considered a rectangular box made up of four areas:
• Content: The actual content (text, image, etc.).
• Padding: Space between the content and the border.
• Border: A line surrounding the padding (optional).
• Margin: Space outside the border, separating the element from others.
How it works: The total width and height of an element include the content, padding, border, and
margin.

2. Explain the difference between margin and padding.


• Margin: The space outside an element’s border. It creates space between the element and
other elements.
• Padding: The space inside the element, between the content and the border.
Example: If you want space between two boxes, use margin. If you want space between the text
inside a box and its border, use padding.

3. How do CSS selectors work? Can you give examples of different types of selectors?
CSS selectors target HTML elements to apply styles to them. There are different types:
• Element selector: Targets all elements of a specific type, e.g., p { color: blue; } (applies to all
<p> elements).
• Class selector: Targets elements with a specific class, e.g., .button { background: red; }.
• ID selector: Targets an element with a specific ID, e.g., #header { font-size: 20px; }.
• Attribute selector: Targets elements with a specific attribute, e.g., a[href] { color: green; }.
• Pseudo-class selector: Targets elements in a specific state, e.g., a:hover { color: red; }.

4. What is specificity in CSS? How is it calculated?


Specificity determines which CSS rule is applied when multiple rules target the same element. It’s
calculated using a system of "weights":
• Inline styles: Highest priority (style="color: red;").
• ID selectors: Higher specificity (e.g., #header).
• Class, attribute, and pseudo-class selectors: Medium specificity (e.g., .button, a[href],
a:hover).
• Element selectors: Lowest specificity (e.g., p, h1).
Example: If two rules apply to the same element, the one with higher specificity wins.

5. Explain how flexbox works in CSS. What are some use cases?
Flexbox is a layout model that allows items within a container to be aligned and distributed flexibly.
Key features:
• Flexible layout: Items can grow, shrink, and wrap automatically based on available space.
• Alignment: You can easily align items horizontally (justify-content) and vertically (align-items).
• Direction: Use flex-direction to set the direction of items (row or column).
Use cases: Centering items, creating responsive layouts, aligning navigation bars, and distributing
space evenly between elements.

6. What is CSS Grid? How is it different from Flexbox?


CSS Grid is a two-dimensional layout system that allows you to create grid-based layouts with rows
and columns.
Differences from Flexbox:
• Grid: Handles both rows and columns, making it ideal for complex layouts with a fixed grid
structure.
• Flexbox: Primarily focuses on one dimension (either row or column), making it better for
simpler, flexible layouts.
Use cases for Grid: Page layouts with fixed rows and columns, like dashboards or image galleries.

7. What are pseudo-classes and pseudo-elements in CSS?


• Pseudo-classes: Target elements based on their state or position, e.g., :hover, :focus, :nth-
child.
o Example: a:hover { color: blue; } changes link color when hovered.
• Pseudo-elements: Target a specific part of an element, e.g., ::before, ::after, ::first-letter.
o Example: p::first-letter { font-size: 2em; } changes the size of the first letter in a
paragraph.

8. How can you center a div both horizontally and vertically?


Using flexbox:
.container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
height: 100vh; /* Full viewport height */
}

Using CSS Grid:


.container {
display: grid;
place-items: center; /* Centers both horizontally and vertically */
height: 100vh;
}

9. What are the various ways to include CSS in a web page?


1. Inline CSS: Directly in the element using the style attribute.
o Example: <p style="color: red;">Hello</p>
2. Internal CSS: Within the <style> tag inside the <head> section.
o Example:
<style>
p { color: blue; }
</style>
3. External CSS: Linking an external stylesheet using the <link> tag.
o Example: <link rel="stylesheet" href="styles.css">

10. What is responsive design? How do you implement it using CSS?


Responsive design ensures that a website looks good on all devices (desktops, tablets, and mobile
phones) by adjusting the layout based on the screen size.
Ways to implement:
• Media queries: Apply styles based on screen size.
o Example:
@media (max-width: 600px) {
body { font-size: 14px; }
}
• Flexible layouts: Use percentage-based widths or units like vw (viewport width) and vh
(viewport height).
• Flexible images: Ensure images scale with the screen, using max-width: 100%.
11. What is the difference between absolute, relative, fixed, and sticky positioning in CSS?
• Relative: Positioned relative to its normal position. You can adjust it with top, left, right, or
bottom.
o Example: Moves 10px down from its normal position.
• Absolute: Positioned relative to the nearest positioned ancestor (anything not static).
o Example: If no ancestor is positioned, it moves relative to the viewport.
• Fixed: Positioned relative to the viewport, meaning it stays in place even when you scroll.
o Example: A sticky navigation bar that stays at the top of the page.
• Sticky: Behaves like relative until a certain point, then it "sticks" to the viewport when
scrolling.
o Example: A header that sticks at the top once you scroll past it.

12. Explain the concept of media queries in CSS and how they are used for responsiveness.
Media queries allow you to apply CSS rules only when certain conditions are met, such as screen size,
orientation, or resolution.
Example:
@media (max-width: 768px) {
body {
font-size: 14px;
}
}
In this example, the font size will only change if the screen width is 768px or less. This is how websites
adjust their layout to different devices (desktop, tablet, mobile).

JavaScript interview questions:


1. What is JavaScript, and how is it different from Java?
JavaScript is a lightweight, interpreted programming language used primarily to create interactive
and dynamic web content. It's mainly used for client-side web development (in browsers).
Difference from Java:
• Java is a statically-typed, compiled programming language designed for building large
applications, while JavaScript is dynamically typed and interpreted.
• Java needs a virtual machine (JVM) to run, whereas JavaScript runs directly in the browser or
in environments like Node.js.

2. What is the difference between var, let, and const?


• var: Function-scoped and can be re-declared and updated. It is hoisted (but initialized with
undefined).
• let: Block-scoped and can be updated but not re-declared in the same block. It’s not hoisted
like var.
• const: Block-scoped and cannot be re-assigned or re-declared. Useful for constants. Like let,
it’s not hoisted.

3. What are arrow functions in JavaScript, and how are they different from regular functions?
Arrow functions are a shorter syntax for writing functions:
const add = (a, b) => a + b;
Differences from regular functions:
• Arrow functions don’t have their own this value; they inherit it from their surrounding context.
• They cannot be used as constructors and don’t have a prototype property.
4. Explain how closures work in JavaScript. Can you provide an example?
A closure is a function that remembers and can access variables from its outer scope, even after the
outer function has finished executing.
Example:
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
}
}
const counter = outer();
counter(); // 1
counter(); // 2
Here, inner is a closure that remembers the count variable from outer.

5. What is the difference between == and === in JavaScript?


• ==: Loose equality, compares two values after type conversion. For example, 5 == '5' is true.
• ===: Strict equality, compares both value and type. For example, 5 === '5' is false because one
is a number, the other is a string.

6. Explain event delegation in JavaScript and its benefits.


Event delegation is a technique where a single event listener is added to a parent element to manage
events for its child elements. The event bubbles up from the child to the parent, allowing the parent
to handle the event.
Benefits:
• Improves performance: Fewer event listeners are attached.
• Simplifies code: You can manage events for dynamically added elements without having to
attach new event listeners.

7. How does JavaScript handle asynchronous operations? What is the difference between callback,
promise, and async/await?
JavaScript uses asynchronous operations for tasks like API calls or timers without blocking the main
thread.
• Callback: A function passed as an argument to another function, which is executed after an
asynchronous task.
o Example: setTimeout(() => console.log('Hello'), 1000);
• Promise: An object representing a future value, either resolved (success) or rejected (failure).
o Example:
let promise = new Promise((resolve, reject) => {
resolve('Success!');
});
promise.then(result => console.log(result));
• Async/Await: Syntactic sugar over promises, making asynchronous code look like synchronous
code.
o Example:
async function fetchData() {
let data = await fetch('url');
console.log(data);
}

8. What is hoisting in JavaScript?


Hoisting is JavaScript’s behavior of moving declarations to the top of the scope before code execution.
Example:
console.log(x); // undefined
var x = 5;
In this case, var x is hoisted to the top, but its initialization (assigning 5) is not, so it prints undefined.

9. What is the difference between call(), apply(), and bind() in JavaScript?


• call(): Invokes a function with a specific this value and individual arguments.
o Example: func.call(context, arg1, arg2);
• apply(): Invokes a function with a specific this value but passes arguments as an array.
o Example: func.apply(context, [arg1, arg2]);
• bind(): Returns a new function with a bound this value. It doesn't invoke the function
immediately.
o Example: let newFunc = func.bind(context);

10. What is a prototype in JavaScript? How does inheritance work using prototypes?
Every JavaScript object has a prototype, which is another object from which it inherits properties and
methods.
Inheritance using prototypes works by linking an object to another object (the prototype). When you
access a property or method on an object, JavaScript first checks the object itself. If it doesn't find the
property, it checks the object's prototype.

11. What is the difference between null and undefined?


• null: Explicitly set to represent "no value."
o Example: let x = null;
• undefined: A variable that has been declared but not assigned a value.
o Example: let y; console.log(y); // undefined

12. Explain the concept of the "this" keyword in JavaScript.


In JavaScript, this refers to the object that is currently executing the code.
How it works:
• In a method: this refers to the object the method belongs to.
• In the global context (in browsers): this refers to the global object (window).
• In event handlers: this refers to the element that received the event.

13. How do you handle errors in JavaScript? What are try, catch, and finally blocks?
Errors in JavaScript can be handled using the try...catch...finally blocks:
• try: Code that may throw an error is placed inside this block.
• catch: This block handles any error that occurs in the try block.
• finally: This block executes regardless of whether an error occurred or not.
Example:
try {
// Code that might throw an error
} catch (error) {
console.log(error.message); // Handle the error
} finally {
console.log('This always runs');
}

14. What is the difference between synchronous and asynchronous programming in JavaScript?
• Synchronous: Code runs sequentially, one task after another. Each task waits for the previous
one to finish before executing.
o Example: Console logs executed one after another.
• Asynchronous: Code allows multiple tasks to be processed at the same time, without waiting
for others to complete. Commonly used for tasks like network requests or file reading.
o Example: Using setTimeout, promises, or async/await for non-blocking operations.

15. How do you create and manipulate arrays and objects in JavaScript?
• Creating arrays:
let arr = [1, 2, 3];
• Manipulating arrays:
o Add: arr.push(4); (adds to the end)
o Remove: arr.pop(); (removes the last element)
o Iterate: arr.forEach(item => console.log(item));
• Creating objects:
let obj = { name: "John", age: 30 };
• Manipulating objects:
o Access: obj.name or obj['name']
o Add/update: obj.gender = "male";
o Delete: delete obj.age;

React interview questions


1. What is React, and why is it popular?
React is a JavaScript library used to build user interfaces, especially for single-page applications. It’s
popular because it allows developers to create reusable UI components, has a fast and efficient virtual
DOM for updates, and has a large ecosystem and community.

2. Explain the concept of virtual DOM in React.


The virtual DOM is a lightweight copy of the actual DOM. When a React component’s state changes,
React updates the virtual DOM first, compares it with the real DOM (using a process called
reconciliation), and updates only the parts that have changed. This makes React very fast and
efficient.

3. What are React components? How are functional components different from class components?
• React components are building blocks of a React application that represent parts of the user
interface.
• Functional components are simple JavaScript functions that return JSX. They don’t have state
or lifecycle methods unless you use React hooks.
• Class components are ES6 classes that extend React.Component and can have state and
lifecycle methods. Class components are now less common with the introduction of hooks.

4. What is JSX in React? Why is it used?


JSX (JavaScript XML) is a syntax extension that allows you to write HTML-like code inside JavaScript.
It’s used because it makes code easier to read and write by combining HTML structure with JavaScript
logic in a single file.
Example:
const element = <h1>Hello, world!</h1>;

5. What are props in React? How are they different from state?
• Props are inputs passed to a component from its parent, making components reusable. They
are read-only and cannot be changed by the component itself.
• State is an internal object managed by the component itself. It is mutable and can be changed
using setState or useState.

6. Explain the concept of state in React. How is state managed?


State represents dynamic data that can change over time and is specific to a component. In functional
components, state is managed using the useState hook, while in class components, it’s managed using
this.setState().
Example:
const [count, setCount] = useState(0);

7. What is the difference between controlled and uncontrolled components in React?


• Controlled components: The form elements (input, select, etc.) are controlled by React, and
their values are managed via state. You update state every time the input changes.
• Uncontrolled components: The form elements manage their own state internally without
React controlling their value. You typically use ref to access the values.

8. What are React hooks? Can you explain useState and useEffect hooks with examples?
Hooks are functions that let you use state and other React features in functional components.
• useState: Manages state in functional components.
const [count, setCount] = useState(0);
• useEffect: Runs side effects in functional components (e.g., fetching data or updating the
DOM).
useEffect(() => {
console.log('Component mounted or updated');
}, [count]); // Runs when 'count' changes

9. What is the context API in React, and how is it used?


The Context API is a way to pass data down the component tree without using props (avoiding prop
drilling). It is used for global data like themes or user authentication.
Example:
const ThemeContext = React.createContext('light');
<ThemeContext.Provider value="dark">
<App />
</ThemeContext.Provider>

10. What is React Router, and how do you implement routing in a React application?
React Router is a library for handling navigation in React applications. It allows you to switch between
different views (pages) without refreshing the browser.
Example:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
<Router>
<Switch>
<Route path="/home" component={Home} />
<Route path="/about" component={About} />
</Switch>
</Router>

11. How do you handle forms in React? What are some best practices?
Forms in React can be handled using controlled components. You update state on every input change
and submit the form by handling the onSubmit event.
Best practices:
• Keep form state local to the component.
• Validate input data before submission.
• Use libraries like Formik for larger forms.

12. What is the significance of key in React lists?


The key prop helps React identify which items in a list have changed, been added, or removed. It
improves performance by avoiding unnecessary re-renders.
Example:
{items.map(item => <li key={item.id}>{item.name}</li>)}

13. How does React handle updates and re-renders?


React re-renders a component when its state or props change. It uses the virtual DOM to calculate
the minimal updates required and then efficiently updates the real DOM.

14. What is prop drilling, and how can you avoid it?
Prop drilling occurs when you pass props through multiple layers like Redux.

15. Explain how React's useMemo and useCallback hooks help in performance optimization.
• useMemo: Memoizes the result of a function, only recalculating when dependencies change.
It optimizes expensive calculations.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
• useCallback: Memoizes a function, preventing it from being recreated on every render. It’s
useful for passing stable functions to child components.
const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]);

16. What are higher-order components (HOCs) in React?


HOCs are functions that take a component and return a new component with additional functionality.
They are used to reuse component logic.
Example:
function withLogging(WrappedComponent) {
return function(props) {
console.log('Component rendered');
return <WrappedComponent {...props} />;
};
}

17. How do you manage global state in React applications?


Global state can be managed using:
• Context API: For simple global state.
• Redux: A more complex state management library, useful when the app grows large.

18. What is Redux, and how does it work with React?


Redux is a state management library that provides a single source of truth (a global state) for your
entire application. It works with React by using the connect() function or useSelector and useDispatch
hooks to read from and update the global state.

19. What is lazy loading in React, and how do you implement it?
Lazy loading is a technique that delays loading components or resources until they are needed. In
React, you can use React.lazy and Suspense to load components lazily.
Example:
const LazyComponent = React.lazy(() => import('./LazyComponent'));
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>

20. How do you handle side effects in React? Explain how to use useEffect for handling side effects.
Side effects include actions like data fetching, subscriptions, or manually updating the DOM. In React,
you handle side effects using the useEffect hook.
Example:
useEffect(() => {
fetchData();
}, []); // Empty array means it runs only once (on mount)
useEffect runs after every render unless you specify dependencies.

Additional JavaScript frameworks and concepts:


1. What is the difference between React and other JavaScript frameworks like Angular or Vue.js?
• React:
o React is a library for building user interfaces, focusing on view in the MVC (Model-
View-Controller) architecture.
o It’s component-based, where everything is a reusable component.
o Uses a virtual DOM to efficiently update UI.
o Offers flexibility in choosing libraries or tools like routing or state management (e.g.,
React Router, Redux).
• Angular:
o Angular is a framework (more opinionated and feature-rich) for building full-fledged
single-page applications (SPA).
o Developed by Google, it follows the MVVM (Model-View-ViewModel) pattern.
o It has two-way data binding, a powerful templating system, built-in dependency
injection, and comes with its own router and HTTP module.
• Vue.js:
o Vue is a progressive framework, meaning it can be used for small parts of a web app
or to build full apps like Angular.
o It's similar to React but offers more built-in functionalities, like state management
(Vuex) and routing (Vue Router).
o Vue uses two-way data binding like Angular, and it's easier to learn compared to
Angular due to its simpler API.
In summary, React is a flexible library focused only on UI, Angular is a full framework with more built-
in tools, and Vue.js provides a middle ground with a simpler learning curve but more built-in features
than React.

2. Explain how REST APIs work and how you would interact with them using React and JavaScript.
• REST API (Representational State Transfer API) is a way for two systems (client and server) to
communicate over HTTP using standard methods like:
o GET: Retrieve data
o POST: Send new data
o PUT/PATCH: Update existing data
o DELETE: Remove data
A REST API usually responds with JSON data, which can be consumed by frontend applications.
• In React, you can interact with REST APIs using fetch() or libraries like Axios.
Example with fetch():
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error('Error fetching data:', error));
}, []);
Example with Axios:
import axios from 'axios';

useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => setData(response.data))
.catch(error => console.error('Error fetching data:', error));
}, []);
Both methods make a request to the API, receive a response (usually in JSON format), and update the
state with the fetched data.

3. What is the role of Webpack in React applications?


Webpack is a module bundler that helps in bundling all your JavaScript, CSS, images, and other assets
into a single or smaller set of files that can be efficiently loaded by the browser.
In a React app, Webpack:
• Bundles multiple files into a single bundle for performance.
• Transpiles modern JavaScript (ES6+) using Babel so that browsers can understand it.
• Optimizes code by minifying and tree shaking (removing unused code).
• Allows for features like Hot Module Replacement (HMR), where changes in the code can be
reflected in the browser without a full reload.
Webpack plays a key role in automating and optimizing the build process for React applications,
ensuring that code runs smoothly in the browser.

4. How do you manage asynchronous data fetching in React? How would you use fetch() or libraries
like Axios?
To manage asynchronous data fetching in React, you typically use useEffect to perform side effects
like API calls. You can either use the built-in fetch() function or a third-party library like Axios.
Using fetch():
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
setData(data);
} catch (error) {
console.error('Error fetching data:', error);
}
};

fetchData();
}, []);
• The fetch() function returns a Promise, and await is used to wait for the response.
• You convert the response into JSON using response.json().

Using Axios:
import axios from 'axios';

useEffect(() => {
const fetchData = async () => {
try {
const result = await axios.get('https://api.example.com/data');
setData(result.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};

fetchData();
}, []);
• Axios is simpler to use because it automatically handles JSON parsing and has better error
handling than fetch().
For both approaches, you should handle errors properly (using try-catch) and manage loading states
to give users a good experience while data is being fetched.

General frontend questions


1. How do you optimize the performance of a web application?
Optimizing web application performance involves several techniques to ensure fast loading, smooth
interaction, and efficient resource usage. Key methods include:
• Minifying assets: Compress JavaScript, CSS, and images to reduce file size.
• Lazy loading: Load resources (images, videos, components) only when they are needed.
• Code splitting: Split code into smaller bundles and load them dynamically to avoid loading
everything at once.
• Caching: Use browser and server-side caching to avoid reloading resources.
• Reduce HTTP requests: Combine files like CSS or JavaScript where possible.
• Optimize images: Use modern formats (like WebP), compress images, and use responsive
image techniques.
• Defer non-critical scripts: Load JavaScript that is not essential for the initial page render after
the page has loaded.

2. What are web workers, and how do they improve performance?


Web workers allow you to run JavaScript in the background without affecting the performance of the
main thread (UI). This is useful for tasks like:
• Handling large calculations
• Parsing large files
• Performing complex computations
By offloading these tasks to a separate thread, web workers prevent the main UI from freezing,
improving the responsiveness and performance of your web app.

Example:
const worker = new Worker('worker.js'); // Initialize web worker
worker.postMessage('Start Task'); // Send task to worker

worker.onmessage = function(event) { // Receive result from worker


console.log('Task finished', event.data);
};

3. How do you ensure cross-browser compatibility in your frontend code?


Ensuring cross-browser compatibility means making sure your web app works across all major
browsers. You can achieve this by:
• Using standard web technologies: Stick to widely supported HTML, CSS, and JavaScript
features.
• CSS resets/normalize.css: Use these to standardize styling across browsers.
• Vendor prefixes: Use prefixes like -webkit-, -moz-, and -ms- for CSS properties that require
them.
• Testing on multiple browsers: Regularly test your app on different browsers (Chrome, Firefox,
Safari, Edge) and devices (mobile, desktop).
• Polyfills: Use polyfills (e.g., babel-polyfill) to add support for newer features in older browsers.
• Feature detection: Use libraries like Modernizr to detect if a feature is supported and provide
fallbacks if needed.

4. What are CORS, and how do you handle CORS issues in frontend development?
CORS (Cross-Origin Resource Sharing) is a security feature implemented by browsers to control how
web pages from one domain interact with resources from another domain. It prevents malicious
scripts from making requests to different domains than the one that served the web page.
When a request is made from a frontend to a backend on a different domain, the server must include
proper CORS headers (like Access-Control-Allow-Origin) to allow the request.
Handling CORS issues:
• Server-side solution: Configure the backend server to include the correct Access-Control-
Allow-Origin header, allowing cross-origin requests from trusted sources.
• Proxy: You can use a proxy (either in development or production) to bypass CORS issues by
making requests to the proxy instead of directly to the server.

5. How do you secure a web application from common vulnerabilities like XSS and CSRF?
Securing a web application from vulnerabilities like XSS (Cross-Site Scripting) and CSRF (Cross-Site
Request Forgery) involves several practices:
• XSS protection:
o Sanitize inputs: Always sanitize and escape user inputs before rendering them on the
page to avoid injecting malicious scripts.
o Content Security Policy (CSP): Use CSP headers to control which sources of scripts are
allowed to execute.
o Use HTTPS: Secure communication with the server to prevent man-in-the-middle
attacks.
• CSRF protection:
o Use anti-CSRF tokens: Include tokens in forms and verify them on the server side to
ensure the request is legitimate.
o SameSite cookies: Set cookies with the SameSite attribute to prevent them from being
sent along with cross-site requests.

6. What is Progressive Web App (PWA), and how do you create one?
A Progressive Web App (PWA) is a web application that combines the best features of web and mobile
apps. PWAs can be installed on a user's device and work offline, offering a native-like experience.
Key features of PWAs:
• Service Workers: These are background scripts that enable offline functionality and caching.
• Web App Manifest: A JSON file that provides metadata about the app, such as the app's name,
icons, and theme color.
• Responsive design: PWAs work on any device, regardless of screen size.

Steps to create a PWA:


1. Add a Web App Manifest:
{
"name": "My App",
"short_name": "App",
"icons": [
{ "src": "/icons/icon-192x192.png", "sizes": "192x192", "type": "image/png" }
],
"start_url": "/",
"display": "standalone"
}
2. Implement a Service Worker:
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('my-cache').then((cache) => {
return cache.addAll(['/index.html', '/styles.css', '/script.js']);
})
);
});

self.addEventListener('fetch', (event) => {


event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
3. Serve over HTTPS: PWAs must be served over HTTPS to ensure security.

7. What is lazy loading, and how do you implement it in your application?


Lazy loading is a performance optimization technique where you defer loading of non-essential
resources (like images, components, or scripts) until they are needed, improving initial page load
times.
Lazy loading images:
<img src="placeholder.jpg" data-src="image.jpg" class="lazy">
javascript
Copy code
document.addEventListener("DOMContentLoaded", function() {
const lazyImages = document.querySelectorAll("img.lazy");

lazyImages.forEach((image) => {
image.src = image.dataset.src;
image.classList.remove("lazy");
});
});
Lazy loading in React (React Suspense):
const LazyComponent = React.lazy(() => import('./MyComponent'));

function App() {
return (
<React.Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</React.Suspense>
);
}
This ensures that certain resources are only loaded when needed, reducing the time it takes for the
main content to appear and improving user experience.

Problem-Solving/Logical Questions
1. How would you improve the page load speed of a web application?
Improving page load speed is critical for a good user experience. Here are some ways to optimize it:
• Minimize HTTP requests: Reduce the number of elements loaded by the page (e.g., combining
files, using CSS sprites).
• Use lazy loading: Load images, videos, and components only when they are needed (e.g.,
when they appear in the viewport).
• Optimize images: Use efficient image formats like WebP, compress images, and serve
responsive images.
• Minify and compress files: Minify CSS, JavaScript, and HTML files, and use gzip or Brotli
compression to reduce their size.
• Implement caching: Use browser caching and server-side caching (CDN) to store static
resources.
• Code splitting: In React, split the code into smaller chunks and load them dynamically to avoid
loading unnecessary code all at once.
• Use a CDN: Content Delivery Networks distribute resources across different servers
worldwide, reducing latency.
• Preload critical resources: Preload key CSS and JavaScript files to prioritize their loading.

2. Explain a challenging bug you encountered in a project and how you resolved it.
Example bug: In one of my React projects, I encountered a bug where the UI wasn’t updating correctly
after fetching new data from an API. Despite successfully receiving data from the API, the component
state was not reflecting the changes.
Resolution:
1. Diagnosis: After thorough debugging, I realized that the state update was asynchronous, and
the component was trying to render before the state was fully updated.
2. Solution: I used the useEffect hook with the API call and ensured that the state update
occurred correctly within it. I also used the setState callback function to make sure that the UI
rendered only after the state was updated.
useEffect(() => {
async function fetchData() {
const response = await fetch("api-endpoint");
const data = await response.json();
setData(data);
}
fetchData();
}, []); // Empty array ensures the effect runs only once.
This fixed the issue and allowed the UI to correctly reflect the fetched data.

3. How would you structure a large React project?


Structuring a large React project requires organization to maintain scalability and readability. A good
structure looks like this:
/src
/components # Reusable UI components
/containers # Components that manage state (smart components)
/services # API calls and side effects
/hooks # Custom React hooks
/context # Context API providers and consumers
/utils # Utility functions (helper functions)
/styles # Global styles and theme management
/pages # Page components (routes)
/store # Redux or global state management (if applicable)
/assets # Static files like images, fonts, etc.
/tests # Unit and integration tests for components
index.js # Entry point for the application
App.js # Root component
Additional Tips:
• Modular approach: Break components into small, reusable parts (e.g., buttons, forms).
• Use hooks: Separate logic (such as API calls) into custom hooks.
• Context API or Redux: For state management, Context API or Redux can manage global state.
• Lazy loading: For large applications, use React's Suspense and lazy to load components when
needed.

4. Can you explain the lifecycle of a React component?


The React component lifecycle refers to the different stages a component goes through from creation
to removal from the DOM. There are three main phases: Mounting, Updating, and Unmounting.
Mounting Phase (when the component is created and inserted into the DOM):
1. constructor(): Initializes the component’s state and binds methods.
2. static getDerivedStateFromProps(): Updates the state based on initial props (rarely used).
3. render(): Describes what the UI should look like, returning JSX elements.
4. componentDidMount(): Runs after the component is added to the DOM. Ideal for API calls or
side effects.
Updating Phase (when the component’s props or state change):
1. static getDerivedStateFromProps(): Runs again when props change (rarely used).
2. shouldComponentUpdate(): Determines whether the component should re-render. It can be
used to optimize performance by returning false if an update is unnecessary.
3. render(): Re-renders the component with new props/state.
4. getSnapshotBeforeUpdate(): Captures some information from the DOM before it is updated
(used for things like scroll position).
5. componentDidUpdate(): Runs after the component re-renders. Useful for updating the DOM
or making further API calls based on updated state/props.
Unmounting Phase (when the component is removed from the DOM):
1. componentWillUnmount(): Runs just before the component is destroyed. Use this to clean
up resources like event listeners or timers.
Functional Components:
For functional components, lifecycle methods are replaced by hooks:
• useEffect(): Combines componentDidMount, componentDidUpdate, and
componentWillUnmount based on how it’s used. It allows you to perform side effects in
functional components.
useEffect(() => {
// Code runs on mount
return () => {
// Cleanup code runs on unmount
};
}, []); // Empty dependency array ensures this runs once on mount/unmount
Understanding the lifecycle phases is key to optimizing performance and ensuring proper resource
management in React components.
Testing & Debugging Questions
1. What tools do you use to debug your code?
Several tools are used to debug code, depending on the technology stack:
• Browser Developer Tools (Chrome DevTools, Firefox Developer Tools): These allow you to
inspect HTML, CSS, and JavaScript, debug scripts, profile performance, and analyze network
requests.
• Console.log(): A simple but effective way to print variables or messages to the browser's
console to track the code execution process.
• Debugger statement: In JavaScript, you can add a debugger statement in your code. When
the browser's dev tools are open, it pauses execution at that point, allowing you to step
through your code.
• React Developer Tools: A Chrome/Firefox extension that helps inspect React components,
their state, and props.
• Redux DevTools: For React applications using Redux, this extension allows you to inspect and
track Redux state changes and actions.
• VSCode Debugger: Visual Studio Code has built-in debugging tools for front-end (JavaScript,
TypeScript) and back-end (Node.js) environments.
• Postman/Insomnia: These tools help in debugging API calls, allowing you to make requests
and inspect responses.
• Linting Tools (ESLint): Detects code errors and inconsistencies early in the development
process.

2. What is unit testing, and how would you apply it in a React project?
Unit testing is a type of software testing where individual units or components of a software
application are tested in isolation. In React, unit tests verify the correctness of components, functions,
or methods.
To apply unit testing in a React project:
• Testing framework: Use frameworks like Jest or Mocha to write test cases.
• Testing library: Use React Testing Library to simulate user interactions and assert component
behavior.
• Example of a test:
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';

test('renders the correct heading', () => {


render(<MyComponent />);
const heading = screen.getByRole('heading', { name: /Hello World/i });
expect(heading).toBeInTheDocument();
});
• Component isolation: Test React components in isolation by mocking dependencies like API
calls or child components.
• Snapshot testing: Use Jest snapshots to test that UI components don’t unintentionally change
over time.

3. What is the difference between shallow and deep rendering in testing React components?
• Shallow rendering:
o In shallow rendering, only the component being tested is rendered, and its child
components are not rendered.
o It is useful when you want to test a component’s logic and output without testing the
behavior of its children.
o Example: With Enzyme (a testing utility), shallow rendering can be done using
shallow().
import { shallow } from 'enzyme';
const wrapper = shallow(<MyComponent />);
expect(wrapper.find('h1').text()).toBe('Hello World');
• Deep rendering (Full rendering):
o Deep rendering, also called full rendering, renders the component and all of its
children recursively.
o This is used when you need to test the integration of components and how they work
together.
o Example: Using mount() in Enzyme allows for deep rendering.
import { mount } from 'enzyme';
const wrapper = mount(<MyComponent />);
expect(wrapper.find('ChildComponent').length).toBe(1);
• When to use:
o Use shallow rendering for unit tests when you only want to test a component in
isolation.
o Use deep rendering for integration tests when you need to test the interaction
between a component and its children.

4. How do you test asynchronous code in JavaScript?


Testing asynchronous code involves ensuring that the code waits for the asynchronous operations
(like API calls or timeouts) to complete before assertions are made. Here’s how you can do it:
• Promises: Use return in Jest test cases to wait for the promise to resolve.
test('fetches data successfully', () => {
return fetchData().then(data => {
expect(data).toBe('Hello World');
});
});
• Async/Await: Use async/await in your tests for a more readable syntax.
test('fetches data successfully', async () => {
const data = await fetchData();
expect(data).toBe('Hello World');
});
• Mocking APIs: Use libraries like Jest to mock asynchronous calls like APIs.
jest.mock('axios');
test('fetches data from API', async () => {
axios.get.mockResolvedValue({ data: 'Hello World' });
const data = await fetchData();
expect(data).toBe('Hello World');
});
• Timers: If your code uses setTimeout or setInterval, you can use Jest’s timer mocks.
jest.useFakeTimers();
test('delays action for 1 second', () => {
const callback = jest.fn();
delayFunction(callback);
jest.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalled();
});
These methods ensure that your tests handle asynchronous behavior correctly and wait for all
promises, API calls, or timeouts to resolve before making assertions.

You might also like