BLOG
100 Essential Web Development Questions and Answers (Beginner to Advanced)
HTML & Web Basics 1. What is HTML, and what does it stand for? HTML stands for HyperText Markup Language. It’s the standard markup language used to create the structure and content of web pages. HTML uses a system of tags (like <p>, <div>, <h1>) to define different elements on a page, such as headings, […]
HTML & Web Basics
1. What is HTML, and what does it stand for?
HTML stands for HyperText Markup Language. It’s the standard markup language used to create the structure and content of web pages. HTML uses a system of tags (like <p>, <div>, <h1>) to define different elements on a page, such as headings, paragraphs, links, and images. Browsers read HTML documents and render them as visible web pages.
2. What is the difference between HTML elements and HTML tags?
An HTML tag is the syntax used to mark up content, consisting of angle brackets like <p> or </p>. An HTML element is the complete structure, including the opening tag, content, and closing tag together (e.g., <p>This is content</p>). Some elements are self-closing and don’t have separate closing tags, like <img /> or <br />.
3. What is the DOCTYPE declaration, and why is it important?
The DOCTYPE declaration is the first line in an HTML document that tells the browser which version of HTML the page is written in. In HTML5, it’s simply <!DOCTYPE html>. This declaration ensures the browser renders the page in standards mode rather than quirks mode, which maintains consistent behaviour across different browsers and prevents rendering issues.
4. What is semantic HTML, and why should you use it?
Semantic HTML uses tags that clearly describe their meaning and purpose, like <header>, <nav>, <article>, and <footer>, instead of generic <div> tags. Using semantic HTML improves accessibility for screen readers, helps search engines understand page content better, and makes code more readable and maintainable. It creates a clear document structure that benefits both humans and machines.
5. What is the difference between block-level and inline elements?
Block-level elements (like <div>, <p>, <h1>) start on a new line and take up the full width available, stacking vertically. Inline elements (like <span>, <a>, <strong>) flow within text and only take up as much width as necessary, sitting horizontally next to other inline elements. Block elements can contain inline elements, but inline elements typically shouldn’t contain block elements (with some HTML5 exceptions).
6. What are data attributes in HTML, and how are they used?
Data attributes are custom attributes that start with data- and allow you to store extra information on HTML elements without using non-standard attributes. For example, <div data-user-id="123" data-role="admin"></div> stores custom data that can be accessed via JavaScript using element.dataset.userId or CSS using attribute selectors. They’re useful for storing state, configuration, or metadata that doesn’t fit standard HTML attributes.
7. What is the purpose of the alt attribute in image tags?
An alt attribute provides alternative text for an image if it cannot be displayed or for users who rely on screen readers. It should describe the image’s content and function in the context of the page. Good alt text improves accessibility, helps with SEO, and provides meaningful fallback content when images fail to load.
8. What is the difference between <div> and <span>?
<div> is a block-level container used to group larger sections of content and create layout structures, while <span> is an inline container used to mark up small portions of text or content within a line. <div> creates line breaks before and after itself, whereas it <span> flows with the surrounding text. Both are non-semantic containers used when no other semantic element is appropriate.
9. What are HTML forms, and what is their primary purpose?
HTML forms are sections of a document that collect user input and submit it to a server for processing. They use the <form> element and contain input controls like text fields, checkboxes, radio buttons, and submit buttons. Forms are essential for user interactions like login, registration, search, and data submission, and they define how data is sent (GET or POST method) and where it’s sent (action attribute).
10. What is the difference between GET and POST methods in forms?
GET appends form data to the URL as query parameters, making it visible in the browser’s address bar and suitable for searches or bookmarkable pages with limited data. POST sends data in the request body, keeping it hidden from the URL, and is appropriate for sensitive information, large amounts of data, or operations that modify server state. GET requests can be cached and bookmarked, while POST requests typically cannot.
11. What are meta tags, and what are they used for?
Meta tags are HTML elements placed in a <head> section that provides metadata about the webpage to browsers and search engines. Common meta tags include charset (character encoding), viewport (responsive design settings), description (page summary for search results), and keywords. They don’t appear on the page but influence how the page is indexed, displayed, and shared on social media platforms.
12. What is the viewport meta tag, and why is it crucial for responsive design?
The viewport meta tag (<meta name="viewport" content="width=device-width, initial-scale=1.0">) controls how a webpage is displayed on mobile devices by setting the visible area dimensions. Without it, mobile browsers render pages at desktop widths and scale them down, making content tiny and unreadable. This tag tells the browser to match the screen’s width and set the initial zoom level, which is essential for responsive web design.
13. What is the purpose of the <head> section in an HTML document?
The <head> section contains metadata and resources that aren’t directly displayed on the page but are essential for the document’s functionality and presentation. It includes elements like the page title, character encoding, CSS stylesheets, JavaScript files, meta tags for SEO, and favicon links. Content in the <head> is processed by the browser before rendering the visible <body> content.
14. What are HTML entities, and when should you use them?
HTML entities are special codes used to display reserved characters or symbols that have special meaning in HTML. For example, < displays “<“, > displays “>”, & displays “&”, and creates a non-breaking space. They’re necessary when you want to show HTML syntax as text, display special characters that aren’t on your keyboard, or prevent the browser from interpreting characters as code.
15. What is the difference between id and class attributes?
An id attribute must be unique within a page and is used to identify a single, specific element, while an class attribute can be applied to multiple elements to group them for styling or scripting. IDs have higher specificity in CSS and can be used as anchor targets in URLs (e.g., #section1). Classes are more flexible and reusable, making them preferred for applying styles to multiple elements.
16. What are void elements (self-closing tags) in HTML?
Void elements are HTML elements that don’t have closing tags because they don’t contain any content. Common examples include <img>, <br>, <hr>, <input>, <meta>, and <link>. In HTML5, you can write them with or without a trailing slash (e.g., <img> or <img />), though the slash is required in XHTML for valid syntax.
17. What is the purpose of the <iframe> element?
The <iframe> (inline frame) element embeds another HTML document within the current page, creating a nested browsing context. It’s commonly used to embed videos (YouTube), maps (Google Maps), or content from other websites. Important attributes include src (source URL), width, height, and security-related attributes like sandbox to restrict the embedded content’s capabilities.
18. What are HTML5 storage options, and how do they differ?
HTML5 provides two main client-side storage mechanisms: localStorage and sessionStorage. localStorage stores data with no expiration time and persists even after the browser is closed, making it suitable for long-term storage of user preferences. sessionStorage only maintains data for the duration of the page session and is cleared when the tab is closed, making it ideal for temporary data like form inputs during a multi-step process.
19. What is the purpose of the target attribute in anchor tags?
The target attribute in anchor (<a>) tags specify where to open the linked document. Common values include _self (default, opens in the same window), _blank (opens in a new tab or window), _parent (opens in the parent frame), and _top (opens in the full window body). Using target="_blank" should be accompanied by rel="noopener noreferrer" for security reasons to prevent the new page from accessing the original page’s window object.
20. What is the difference between HTML and XHTML?
XHTML (Extensible HyperText Markup Language) is a stricter, XML-based version of HTML that requires well-formed syntax: all tags must be closed, lowercase, properly nested, and attributes must be quoted. HTML5 is more lenient and allows omitting closing tags for some elements, using unquoted attributes, and other shortcuts. While XHTML enforces strict parsing rules that cause errors for invalid markup, HTML5 browsers attempt to correct and render invalid code gracefully.
CSS & Responsive Design
21. What is CSS, and what does it stand for?
CSS stands for Cascading Style Sheets. It’s a stylesheet language used to describe the presentation and visual styling of HTML documents, including layout, colors, fonts, spacing, and animations. CSS separates content (HTML) from presentation, allowing you to maintain consistent styling across multiple pages and making websites easier to update and maintain.
22. What does the “cascading” in CSS mean?
Cascading refers to the algorithm that determines which CSS rules apply when multiple rules target the same element. The cascade considers three factors in order: specificity (how specific the selector is), source order (later rules override earlier ones), and importance (using !important). This cascading nature allows styles to be inherited from parent elements and overridden at more specific levels, creating a flexible styling hierarchy.
23. What is CSS specificity, and how is it calculated?
CSS specificity determines which styles are applied when multiple rules target the same element. It’s calculated as a four-part value: inline styles (1,0,0,0), IDs (0,1,0,0), classes/attributes/pseudo-classes (0,0,1,0), and elements/pseudo-elements (0,0,0,1). For example, #header .nav a has specificity (0,1,1,1), which beats .nav a with (0,0,1,1). Higher specificity rules override lower specificity rules regardless of source order.
24. What is the CSS box model?
The CSS box model describes how every HTML element is represented as a rectangular box consisting of four areas: content (the actual content), padding (space between content and border), border (surrounds the padding), and margin (space outside the border separating it from other elements). By default (box-sizing: content-box), width and height only apply to the content area, but box-sizing: border-box includes padding and border in the specified dimensions, making layouts more predictable.
25. What is the difference between margin and padding?
Padding is the space between an element’s content and its border, and it’s part of the element itself, meaning it inherits the element’s background colour or image. Margin is the space outside an element’s border that separates it from other elements, and it’s always transparent. Padding increases the element’s total size (unless using border-box), while margins create space between elements and can collapse vertically in certain situations.
26. What is Flexbox, and what problems does it solve?
Flexbox (Flexible Box Layout) is a one-dimensional CSS layout model designed for distributing space and aligning items within a container, either horizontally or vertically. It solves common layout challenges like vertical centering, equal-height columns, and space distribution without using floats or positioning hacks. Key properties include display: flex, justify-content (main axis alignment), align-items (cross-axis alignment), and flex-direction (row or column).
27. What is CSS Grid, and when should you use it over Flexbox?
CSS Grid is a two-dimensional layout system that allows you to create complex layouts with rows and columns simultaneously. Use Grid for overall page layouts and when you need to control both dimensions at once, while Flexbox is better for one-dimensional layouts like navigation bars or card layouts. Grid excels at creating responsive layouts with grid-template-areas, fr units, and automatic placement, while Flexbox is ideal for content-driven layouts where items flow naturally.
28. What are CSS selectors, and what are the most common types?
CSS selectors are patterns used to target HTML elements for styling. Common types include element selectors (p), class selectors (.classname), ID selectors (#idname), attribute selectors ([type="text"]), pseudo-classes (:hover, :first-child), pseudo-elements (::before, ::after), and combinators (descendant , child >, adjacent sibling +, general sibling ~). Complex selectors can combine these to target elements very precisely.
29. What are pseudo-classes and pseudo-elements?
Pseudo-classes (single colon, like :hover, :focus, :nth-child()) select elements based on their state or position in the document tree. Pseudo-elements (double colon, like ::before, ::after, ::first-letter) style specific parts of an element or insert generated content. For example, :hover applies styles when hovering over an element, while ::before inserts content before an element’s actual content.
30. What is responsive web design?
Responsive web design is an approach that makes web pages render well on various devices and screen sizes by using flexible layouts, flexible images, and CSS media queries. Instead of creating separate mobile and desktop versions, responsive design uses a single codebase that adapts its layout and content based on the viewport size. Key techniques include fluid grids (using percentages instead of fixed pixels), flexible images (max-width: 100%), and media queries to apply different styles at specific breakpoints.
31. What are CSS media queries, and how do you use them?
Media queries allow you to apply CSS styles conditionally based on device characteristics like screen width, height, orientation, or resolution. They’re written as @media (condition) { styles }, for example @media (max-width: 768px) { .container { width: 100%; } }. Common breakpoints target mobile phones (up to 768px), tablets (769px-1024px), and desktops (1025px+), following a mobile-first or desktop-first approach.
32. What is the difference between display: none and visibility: hidden?
display: none completely removes the element from the document flow, meaning it takes up no space and other elements behave as if it doesn’t exist. visibility: hidden hides the element visually but maintains its space in the layout, creating a gap where the element would be. Additionally, display: none prevents the element and its children from being accessible to screen readers, while visibility: hidden elements may still be announced depending on the implementation.
33. What are CSS variables (custom properties) and how do you use them?
CSS variables allow you to store values that can be reused throughout your stylesheet, making maintenance easier and enabling dynamic theming. They’re defined using -- prefix (e.g., --primary-color: #3498db) and accessed with the var() function (e.g., color: var(--primary-color)). Variables can be scoped to specific selectors or defined globally on :root, and they can be changed dynamically with JavaScript, making them powerful for themes and responsive design.
34. What is the position property in CSS, and what are its values?
The position property determines how an element is positioned in the document. static (default) follows normal document flow. relative positions the element relative to its normal position without affecting other elements. absolute removes it from the flow and positions it relative to its nearest positioned ancestor. fixed positions it relative to the viewport, staying in place during scrolling. sticky is a hybrid that acts relatively until scrolling reaches a threshold, then becomes fixed.
35. What is the z-index property and how does it work?
The z-index property controls the stacking order of positioned elements (those with a position other than static) along the z-axis (depth). Higher z-index values appear in front of lower values. However, z-index only works within the same stacking context—elements create new stacking contexts when they have certain properties, like position: relative with z-index, opacity less than 1, or transform. Understanding stacking contexts is crucial for managing complex layouts.
36. What are CSS transitions and animations?
CSS transitions smoothly animate property changes over a specified duration when triggered by state changes like :hover. They’re defined using transition: property duration timing-function delay. CSS animations are more complex, allowing you to define keyframe-based sequences that can run automatically or on trigger. Animations use @keyframes to define intermediate states and the animation property to control duration, timing, iteration, and direction, making them suitable for complex, multi-step effects.
37. What is the difference between em, rem, px, and % units?
px (pixels) are absolute units providing fixed sizing. em is relative to the font-size of the element itself (or parent if setting font-size), making it cascade and potentially compound. rem (root em) is always relative to the root element’s font-size, avoiding compounding issues and making responsive design more predictable. % is relative to the parent element’s property value (width, font-size, etc.). rem is often preferred for consistent, scalable typography and spacing.
38. What is mobile-first design, and why is it recommended?
Mobile-first design is an approach where you design and code for mobile devices first, then progressively enhance for larger screens using min-width media queries. This approach is recommended because it forces you to prioritise essential content and features, results in better performance for mobile users (who often have slower connections), and aligns with the growing mobile-first browsing trend. It’s easier to add complexity for larger screens than to strip it away for smaller ones.
39. What are CSS preprocessors, and what are their benefits?
CSS preprocessors like Sass, Less, and Stylus extend CSS with programming features like variables, nesting, mixins (reusable style blocks), functions, and mathematical operations. They make CSS more maintainable and DRY (Don’t Repeat Yourself) by allowing you to organise styles hierarchically, create reusable components, and perform calculations. The preprocessor code is compiled into standard CSS that browsers can understand, combining the power of programming with the simplicity of CSS.
40. What is the CSS calc() Function and when is it useful?
The calc() function performs mathematical calculations to determine CSS property values, allowing you to mix different units. For example, width: calc(100% - 50px) creates a width that’s the full container minus 50 pixels. It’s particularly useful for creating flexible layouts, calculating responsive spacing, and solving layout problems that would otherwise require JavaScript. You can use addition (+), subtraction (-), multiplication (*), and division (/) with proper spacing around operators.
JavaScript Fundamentals
41. What is JavaScript and what is it used for?
JavaScript is a high-level, interpreted programming language primarily used to create interactive and dynamic behaviour on web pages. It runs in the browser and can manipulate the DOM, handle events, make asynchronous requests to servers, validate forms, create animations, and much more. Modern JavaScript (with Node.js) also runs on servers, making it a full-stack language capable of building entire web applications from frontend to backend.
42. What is the difference between var, let, and const?
var is function-scoped, can be redeclared, and is hoisted (initialised as undefined at the top of its scope). let is block-scoped, cannot be redeclared in the same scope, and is hoisted but not initialised (temporal dead zone). const is also block-scoped and hoisted, but creates a constant reference that cannot be reassigned, though the object or array it references can still be mutated. Modern JavaScript prefers const by default, using let only when reassignment is necessary, and avoiding var.
43. What are JavaScript data types?
JavaScript has eight data types: seven primitive types and objects. Primitives include String (text), Number (integers and floats), Boolean (true/false), Undefined (declared but not assigned), Null (intentional absence of value), Symbol (unique identifiers), and BigInt (large integers). Objects are complex data structures that can hold collections of data and more complex entities, including arrays, functions, dates, and user-defined objects. Primitives are immutable, while objects are mutable and passed by reference.
44. What is the difference between == and === in JavaScript?
== (loose equality) performs type coercion, converting operands to the same type before comparing, which can lead to unexpected results like "5" == 5 being true. === (strict equality) checks both value and type without coercion, so "5" === 5 is false. Similarly, != performs type coercion while !== doing strict inequality checking. Best practice is to always use === and !== to avoid bugs caused by implicit type conversion.
45. What are JavaScript functions, and what are the different ways to define them?
Functions are reusable blocks of code that perform specific tasks and can accept inputs (parameters) and return outputs. You can define them using function declarations (function name() {}), function expressions (const name = function() {}), or arrow functions (const name = () => {}). Function declarations are hoisted, while expressions and arrow functions are not. Arrow functions have lexical this binding and more concise syntax, making them popular for callbacks and modern JavaScript.
46. What is the this keyword in JavaScript?
this is a keyword that refers to the object that is executing the current function. Its value depends on how the function is called: in a method, it this refers to the owner object; in a regular function, it refers to the global object (or undefined in strict mode); in an event handler, it refers to the element that received the event; and in arrow functions, this is lexically inherited from the enclosing scope. You can explicitly set this using call(), apply(), or bind() methods.
47. What are JavaScript arrays, and what are common methods for manipulating them?
Arrays are ordered collections of values that can hold any data type, accessed by numeric indices starting at 0. Common methods include push()/pop() (add/remove from end), shift()/unshift() (remove/add at beginning), slice() (extract portion), splice() (add/remove elements), map() (transform each element), filter() (select elements), reduce() (accumulate values), forEach() (iterate), and find()/findIndex() (locate elements). Modern methods like map(), filter(), and reduce() are preferred for their functional programming approach and immutability.
48. What is the DOM, and how do you manipulate it with JavaScript?
The DOM (Document Object Model) is a programming interface that represents HTML documents as a tree structure of objects, allowing JavaScript to access and manipulate page content, structure, and styles dynamically. Common manipulation methods include document.querySelector() and getElementById() for selecting elements, createElement() and appendChild() for adding elements, textContent and innerHTML for changing content, and classList.add/remove() for styling. The DOM API provides complete control over every aspect of the webpage.
49. What are events and event listeners in JavaScript?
Events are actions or occurrences that happen in the browser, such as clicks, key presses, mouse movements, or page loads. Event listeners are functions that wait for specific events and execute code in response. You attach listeners using addEventListener('eventName', callbackFunction), which is preferred over inline handlers like onclick. Event listeners can be removed with removeEventListener(), and you can pass an options object to control behaviour like once: true for single execution or capture: true for event flow control.
50. What is event bubbling and event capturing?
Event propagation occurs in two phases: capturing (event travels from the root down to the target element) and bubbling (event travels from the target back up to the root). By default, event listeners fire during the bubbling phase, meaning child element events trigger parent handlers too. You can stop propagation with event.stopPropagation() or use addEventListener(event, handler, { capture: true }) to listen during the capture phase. Event delegation leverages bubbling by placing a single listener on a parent to handle events from multiple children.
51. What are callback functions in JavaScript?
A callback function is a function passed as an argument to another function, which is then executed at a specific time or after a specific event. They’re fundamental to JavaScript’s asynchronous nature, used in event handlers, timers (setTimeout, setInterval), and array methods (map, forEach). For example, setTimeout(() => console.log('Done'), 1000) passes an arrow function as a callback to execute after one second, enabling non-blocking operations.
52. What are Promises and how do they work?
Promises are objects representing the eventual completion or failure of an asynchronous operation, providing a cleaner alternative to callbacks. A Promise has three states: pending (initial), fulfilled (operation succeeded), or rejected (operation failed). You handle results using .then() for success and .catch() for errors, with .finally() executing regardless of outcome. Promises solve callback hell through chaining and provide better error handling, making asynchronous code more readable and maintainable.
53. What is async/await, and how does it improve asynchronous code?
async/await is syntactic sugar over Promises that makes asynchronous code look and behave more like synchronous code. Functions declared with async automatically return a Promise, and await pause execution until a Promise resolves, returning its value. For example, const data = await fetch(url) waits for the request to complete before continuing. This approach eliminates promise chaining, makes error handling simpler with try/catch blocks, and significantly improves code readability compared to .then() chains.
54. What is the difference between null and undefined?
undefined means a variable has been declared but not assigned a value, or a function returns no explicit value, or an object property doesn’t exist. null is an explicit assignment representing the intentional absence of any value—it’s a programmer’s way of saying “this should be empty.” In terms of types, typeof undefined returns “undefined” while typeof null returns “object” (a historical JavaScript quirk). When comparing, null == undefined is true but null === undefined is false.
55. What is closure in JavaScript?
A closure is a function that retains access to variables from its outer (enclosing) scope even after the outer function has finished executing. This happens because JavaScript maintains the scope chain—when you return a function from another function, the returned function “remembers” variables from its creation environment. Closures are fundamental for data privacy (creating private variables), function factories, and maintaining state in asynchronous operations. They’re created every time a function is created, not just when explicitly returning inner functions.
56. What is the difference between synchronous and asynchronous code?
Synchronous code executes line by line in order, blocking subsequent operations until each completes—if one operation takes time, everything waits. Asynchronous code allows operations to start and complete independently without blocking, using callbacks, Promises, or async/await to handle results when they’re ready. JavaScript is single-threaded but handles asynchronous operations through the event loop, which manages a call stack, callback queue, and Web APIs. This enables operations like network requests to run in the background while other code continues executing.
57. What is the spread operator, and how is it used?
The spread operator (...) expands iterables like arrays or objects into individual elements. For arrays, it’s used for copying (const copy = [...original]), concatenating ([...arr1, ...arr2]), or passing elements as function arguments (Math.max(...numbers)). For objects, it copies properties ({...obj, newProp: value}), which is useful for creating modified copies without mutating originals. Spread creates shallow copies, meaning nested objects or arrays are still referenced, not deeply cloned.
58. What is destructuring in JavaScript?
Destructuring is a syntax that unpacks values from arrays or properties from objects into distinct variables. Array destructuring uses bracket notation: const [first, second] = array. Object destructuring uses curly braces: const {name, age} = person. You can provide default values, rename variables ({name: userName}), skip elements, and nest destructuring patterns. It’s particularly useful in function parameters for extracting values from objects passed as arguments, making code more concise and readable.
59. What are template literals in JavaScript?
Template literals are string literals enclosed by backticks (`) that allow embedded expressions, multi-line strings, and more readable string formatting. Expressions are embedded using ${expression} syntax, like `Hello, ${name}!`. They eliminate the need for string concatenation with +, support line breaks without \n, and can contain any valid JavaScript expression, including function calls and calculations. Tagged template literals provide even more power by allowing custom processing of template strings through functions.
60. What is the difference between map(), filter(), and reduce()?
map() transforms each array element and returns a new array of the same length with transformed values. filter() returns a new array containing only elements that pass a test function, potentially changing the array length. reduce() accumulates array values into a single result by repeatedly applying a reducer function—it can sum numbers, flatten arrays, group objects, or build any derived data structure. All three are pure functions that don’t mutate the original array, embodying functional programming principles and improving code clarity.
Frontend Frameworks & Tools
61. What is React, and what problems does it solve?
React is a JavaScript library for building user interfaces, particularly single-page applications, developed by Facebook. It solves the complexity of managing dynamic UIs by introducing a component-based architecture where UI is broken into reusable, self-contained pieces. React uses a virtual DOM to efficiently update only the parts of the page that changed, rather than re-rendering everything. Its declarative approach makes code more predictable and easier to debug compared to imperative DOM manipulation.
62. What are React components, and what are the different types?
React components are independent, reusable pieces of UI that accept inputs (props) and return React elements describing what should appear on screen. Functional components are JavaScript functions that return JSX, and with Hooks, they can manage state and side effects. Class components are ES6 classes that extend React.Component with their own state and lifecycle methods (now largely superseded by functional components with Hooks). Functional components are simpler, easier to test, and currently the recommended approach for new React code.
63. What is JSX in React?
JSX (JavaScript XML) is a syntax extension that lets you write HTML-like code in JavaScript, making React components more readable. It looks like HTML but gets compiled to React.createElement() function calls by tools like Babel. JSX allows embedding JavaScript expressions inside curly braces, supports component composition, and enforces closing tags. While not required for React, JSX is the standard because it creates a clear, declarative representation of UI structure.
64. What are props in React, and how do they work?
Props (properties) are read-only inputs passed from parent to child components to customise behaviour and appearance, similar to function parameters. They enable component reusability by allowing the same component to render different content based on different props. Props are passed as attributes (<Child name="John" age={25} />) and accessed in functional components as function parameters or in class components via this.props. Props follow one-way data flow (top-down), making data movement predictable and debugging easier.
65. What is state in React, and how is it managed?
State is data that changes over time and affects what a component renders, like form inputs, toggle states, or fetched data. In functional components, state is managed using the useState Hook, which returns a state value and a function to update it: const [count, setCount] = useState(0). When state changes, React re-renders the component and its children to reflect the new state. State should be kept at the appropriate level—only as high in the component tree as necessary—to maintain performance and clarity.
66. What are React Hooks and why were they introduced?
Hooks are functions that let you use state and other React features in functional components without writing classes. Common hooks include useState (manage state), useEffect (side effects), useContext (consume context), useReducer (complex state logic), and useRef (mutable references). They were introduced to solve problems like reusing stateful logic between components, simplifying complex components that mix concerns, and eliminating confusion around this in classes. Hooks have largely replaced class components as the preferred way to write React.
67. What is the useEffect Hook, and how does it work?
useEffect runs side effects in functional components—operations that affect things outside the component, like data fetching, subscriptions, or manual DOM manipulation. It runs after every render by default, but you can control when it runs using a dependency array: an empty array [] runs once on mount, an array with values re-runs when those values change, and no array runs after every render. Returning a cleanup function from useEffect handles unsubscribing or clearing effects when the component unmounts or before the effect runs again.
68. What is the Virtual DOM in React?
The Virtual DOM is a lightweight JavaScript representation of the actual DOM that React maintains in memory. When state changes, React creates a new Virtual DOM tree, compares it with the previous version (diffing), calculates the minimal set of changes needed, and updates only those specific parts of the real DOM (reconciliation). This process is much faster than directly manipulating the DOM because DOM operations are expensive, and React’s efficient diffing algorithm minimises the number of actual updates needed.
69. What is the component lifecycle in React?
Component lifecycle refers to the series of events from a component’s creation to its removal. In class components, lifecycle methods include componentDidMount (after first render), componentDidUpdate (after updates), and componentWillUnmount (before removal). In functional components with Hooks, useEffect handles all lifecycle concerns: running code after render, responding to state/prop changes, and cleanup. Understanding the lifecycle helps you optimise performance, manage side effects properly, and avoid memory leaks.
70. What is the difference between controlled and uncontrolled components in React?
Controlled components store form data in React state, making React the “single source of truth”—you update state via onChange handlers and set input values from state. Uncontrolled components store data in the DOM itself, using refs to access values when needed, similar to traditional HTML forms. Controlled components provide more control and validation capabilities and are recommended for most cases, while uncontrolled components can be simpler for basic forms or when integrating with non-React code.
71. What is Vue.js and how does it differ from React?
Vue.js is a progressive JavaScript framework for building user interfaces with a focus on simplicity and flexibility. Unlike React (which is primarily a UI library), Vue is a more complete framework with official solutions for routing, state management, and CLI tooling. Vue uses template-based syntax (more HTML-like) versus React’s JSX, offers two-way data binding out of the box, and has a gentler learning curve. Both use virtual DOM and component-based architecture, but Vue’s progressive nature lets you adopt it incrementally more easily.
72. What is Angular and what are its key features?
Angular is a comprehensive TypeScript-based framework developed by Google for building large-scale web applications. It’s a complete platform including everything needed—component architecture, routing, forms, HTTP client, testing tools, and more—following the “batteries included” philosophy. Key features include two-way data binding, dependency injection, TypeScript as the primary language, RxJS for reactive programming, and a powerful CLI. Angular is more opinionated and structured than React or Vue, making it popular for enterprise applications where standardisation is valued.
73. What is component-based architecture?
Component-based architecture breaks UIs into independent, reusable, self-contained pieces that manage their own structure, styling, and behaviour. Each component encapsulates its logic and can be composed with other components to build complex interfaces. This approach promotes reusability (same component used in multiple places), maintainability (changes isolated to specific components), and parallel development (team members work on different components). All modern frameworks (React, Vue, Angular) embrace this architecture as it scales better than monolithic approaches.
74. What is state management, and why do you need libraries like Redux or Vuex?
State management involves organising and controlling application data and its flow throughout the component tree. While local component state works for simple apps, complex applications with shared state between many components become difficult to manage. Libraries like Redux (React) or Vuex (Vue) provide a centralised store where all application state lives, with predictable patterns for reading and updating it. They solve prop drilling (passing props through many levels), make state changes traceable and debuggable, and provide time-travel debugging and middleware capabilities.
75. What is npm, and what is it used for?
npm (Node Package Manager) is the default package manager for JavaScript and Node.js, hosting over a million reusable packages. It allows you to install, manage, and share packages (libraries, frameworks, tools) through the command line. The package.json file tracks project dependencies and scripts, while package-lock.json ensures consistent installations. Common commands include npm install (add packages), npm update (update packages), and npm run (execute scripts). npm has made JavaScript development more productive by enabling easy sharing and reuse of code.
76. What is webpack and what problem does it solve?
Webpack is a module bundler that takes modules with dependencies (JavaScript, CSS, images) and bundles them into optimised static assets for the browser. It solves the problem of managing numerous files, dependencies, and asset types by creating a dependency graph and efficiently packaging everything. Webpack enables features like code splitting (loading code on demand), tree shaking (removing unused code), hot module replacement (updating modules without a full refresh), and asset optimisation. While tools like Vite are gaining popularity, Webpack remains widely used for its flexibility and robust ecosystem.
77. What is Babel and why is it important?
Babel is a JavaScript compiler that transforms modern JavaScript (ES6+) into backwards-compatible versions that older browsers can understand. It allows developers to use the latest language features like arrow functions, async/await, and JSX without worrying about browser support. Babel uses plugins and presets to determine which transformations to apply, and it’s essential for React development (compiling JSX) and using modern syntax while maintaining broad compatibility. The ecosystem also includes polyfills to add missing runtime features.
78. What are Single Page Applications (SPAs)?
SPAs are web applications that load a single HTML page and dynamically update content as users interact with the app, without full page reloads. They use JavaScript to handle routing and rendering on the client side, communicating with servers via APIs to fetch data. SPAs provide faster, more fluid user experiences similar to native applications, but face challenges like initial load time, SEO (though modern frameworks address this with server-side rendering), and browser history management. React, Vue, and Angular are commonly used to build SPAs.
79. What is server-side rendering (SSR) and why is it useful?
Server-side rendering generates HTML on the server for each request, sending fully-rendered pages to the client rather than empty HTML with JavaScript that renders content. SSR improves initial load times, enhances SEO (search engines see full content immediately), and ensures content is visible without JavaScript enabled. Frameworks like Next.js (React), Nuxt.js (Vue), and Angular Universal provide SSR capabilities. The tradeoff is increased server complexity and load, but hybrid approaches can render some pages on the server while others run purely client-side.
80. What is the difference between a library and a framework?
A library is a collection of functions and utilities that you call when needed—you’re in control of the application flow and decide when to use the library. A framework is more opinionated, providing a structure where your code fits into predefined places—it calls your code (“inversion of control”). React is technically a library (just for UI), though often called a framework, while Angular is a full framework with strict conventions. The distinction matters for understanding project structure, learning curve, and flexibility—libraries offer more freedom while frameworks provide more guidance.
Backend, APIs & Web Performance
81. What is an API, and what is REST?
An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other, defining how requests and responses should be structured. REST (Representational State Transfer) is an architectural style for designing networked applications, typically using HTTP methods (GET, POST, PUT, DELETE) to perform CRUD operations on resources identified by URLs. RESTful APIs are stateless, use standard HTTP methods, return data in formats like JSON, and are widely adopted for web services due to their simplicity and scalability.
82. What are HTTP methods, and what are they used for?
HTTP methods (or verbs) indicate the desired action on a resource. GET retrieves data without modifying it. POST creates new resources. PUT updates existing resources by replacing them entirely. PATCH partially updates resources. DELETE removes resources. HEAD retrieves headers without the body. These methods follow RESTful conventions, where GET and HEAD are safe (don’t modify data), and GET, HEAD, PUT, and DELETE are idempotent (multiple identical requests produce the same result).
83. What are HTTP status codes, and what do common ones mean?
HTTP status codes indicate the result of an HTTP request. 2xx codes mean success (200 OK, 201 Created, 204 No Content). 3xx codes indicate redirection (301 Moved Permanently, 302 Found, 304 Not Modified). 4xx codes mean client errors (400 Bad Request, 401 Unauthorised, 403 Forbidden, 404 Not Found). 5xx codes indicate server errors (500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable). Understanding these codes helps debug issues and implement proper error handling in applications.
84. What is CORS, and why does it exist?
CORS (Cross-Origin Resource Sharing) is a security mechanism that allows or restricts web pages from making requests to a different domain than the one serving the page. Browsers enforce the Same-Origin Policy by default, blocking requests to different origins to prevent malicious scripts from accessing sensitive data. CORS works through HTTP headers (Access-Control-Allow-Origin, etc.) that servers send to indicate which origins are permitted. APIs must explicitly enable CORS for frontend applications hosted on different domains to access them.
85. What is JSON and why is it commonly used for APIs?
JSON (JavaScript Object Notation) is a lightweight, text-based data format for representing structured data using key-value pairs and arrays. It’s language-independent but uses conventions familiar to JavaScript, making it natural for web APIs. JSON is human-readable, easy to parse, smaller than XML (less bandwidth), and has native browser support with JSON.parse() and JSON.stringify(). These advantages make it the de facto standard for API communication, configuration files, and data exchange between applications.
86. What is authentication and authorisation?
Authentication verifies who a user is—confirming their identity through credentials like username/password, tokens, or biometrics. Authorisation determines what an authenticated user is allowed to do—defining permissions and access levels to resources. Authentication answers “Who are you?” while authorisation answers “What can you do?” Common authentication methods include session-based (cookies), token-based (JWT), and OAuth. Both are critical for security, and they’re often used together: first authenticate the user, then check their authorisation for specific actions.
87. What are JSON Web Tokens (JWT) and how do they work?
JWT is a compact, self-contained token format for securely transmitting information between parties as a JSON object, commonly used for authentication. A JWT consists of three parts: header (token type and algorithm), payload (claims/data), and signature (verifies integrity). After login, the server generates a JWT and sends it to the client, which stores it (usually in localStorage or a cookie) and includes it in subsequent request headers. The server verifies the signature to ensure the token hasn’t been tampered with, enabling stateless authentication.
88. What is a database, and what is the difference between SQL and NoSQL?
A database is an organised collection of structured data stored electronically for easy access, management, and updating. SQL (relational) databases like PostgreSQL and MySQL organise data in tables with predefined schemas, use SQL for queries, support ACID transactions, and enforce relationships between tables. NoSQL databases like MongoDB and Redis use flexible schemas, store data in various formats (documents, key-value, graphs), scale horizontally more easily, and prioritise availability and performance over strict consistency. Choose SQL for structured data with complex relationships, NoSQL for flexible schemas and high scalability.
89. What is Node.js, and why is it popular for backend development?
Node.js is a JavaScript runtime built on Chrome’s V8 engine that allows JavaScript to run on servers, not just browsers. It uses an event-driven, non-blocking I/O model that makes it efficient for handling concurrent connections, perfect for real-time applications like chat or gaming. Node.js enables full-stack JavaScript development (same language frontend and backend), has a massive ecosystem via npm, and excels at I/O-heavy tasks. Its asynchronous nature and single-threaded event loop handle many connections with minimal overhead.
90. What is Express.js, and what is it used for?
Express.js is a minimal and flexible Node.js web application framework that provides features for building web and mobile applications. It simplifies creating server-side applications by providing routing, middleware support, template engines, and HTTP utility methods. Express handles common tasks like parsing request bodies, managing cookies, handling errors, and serving static files with simple, intuitive APIs. Its unopinionated nature and middleware ecosystem make it the most popular Node.js framework for building RESTful APIs and web applications.
91. What is middleware in web development?
Middleware are functions that executes during the request-response cycle, sitting between the client request and the final route handler. They have access to the request object, response object, and the next middleware function in the stack. Middleware can execute code, modify request/response objects, end the request-response cycle, or call the next middleware. Common uses include authentication, logging, parsing request bodies, handling CORS, error handling, and rate limiting. Express.js and similar frameworks are built around the middleware pattern.
92. What is web performance optimization and why does it matter?
Web performance optimisation involves techniques to make websites load faster and run more smoothly, directly impacting user experience, engagement, and search rankings. Slow sites lead to higher bounce rates, lower conversions, and poor SEO. Key metrics include First Contentful Paint, Largest Contentful Paint, Time to Interactive, and Cumulative Layout Shift. Optimisation strategies include minimising HTTP requests, compressing assets, lazy loading, using CDNs, optimising images, code splitting, caching, and reducing JavaScript execution time.
93. What is lazy loading, and when should you use it?
Lazy loading defers loading non-critical resources until they’re needed, typically when they’re about to enter the viewport. Images, videos, and even code chunks can be lazy-loaded to improve initial page load times. Modern browsers support native image lazy loading with loading=”lazy”, while JavaScript libraries handle more complex scenarios. Lazy loading is particularly beneficial for image-heavy sites, long pages, and single-page applications. The tradeoff is potential layout shifts and brief loading states, which can be mitigated with placeholders and proper sizing.
94. What is cachin,g and how does it improve performance?
Caching stores copies of files or data in temporary storage locations for faster subsequent access, avoiding expensive recomputation or network requests. Browser caching stores static assets locally (controlled by HTTP headers like Cache-Control), while CDNs cache content at edge servers worldwide. Server-side caching stores database query results or computed values in memory (using Redis or Memcached). Application-level caching can memoise function results. Effective caching dramatically reduces load times, server load, and bandwidth costs, but requires strategies for cache invalidation when content changes.
95. What is a Content Delivery Network (CDN)?
A CDN is a geographically distributed network of servers that deliver web content to users from the closest physical location, reducing latency and improving load times. CDNs cache static assets (images, CSS, JavaScript) at edge locations worldwide, so users download content from nearby servers rather than the origin server. Popular CDNs include Cloudflare, AWS CloudFront, and Fastly. CDNs also provide additional benefits like DDoS protection, SSL/TLS management, and load balancing, making them essential for global, high-traffic websites.
96. What are minification and bundling?
Minification removes unnecessary characters from code (whitespace, comments, and shortening variable names) without changing functionality, reducing file size for faster downloads. JavaScript, CSS, and HTML can all be minified using tools like Terser, cssnano, or html-minifier. Bundling combines multiple files into fewer files, reducing HTTP requests—modern bundlers like webpack or Vite also optimise code, remove unused code (tree shaking), and split code for optimal loading. Both techniques are standard build steps that significantly improve production performance.
97. What isa Progressive Web App (PWA) and what are its benefits?
A PWA is a web application that uses modern web capabilities to deliver app-like experiences, including offline functionality, push notifications, and home screen installation. PWAs use service workers for caching and background tasks, a web app manifest for installation metadata, and HTTPS for security. Benefits include cross-platform compatibility (one codebase for all devices), no app store approval needed, automatic updates, smaller size than native apps, and improved performance through caching. Companies like Twitter, Pinterest, and Starbucks have successfully adopted PWAs.
98. What is WebSocket, and when would you use it?
WebSocket is a protocol providing full-duplex, bidirectional communication channels over a single TCP connection, enabling real-time data transfer between client and server. Unlike HTTP’s request-response model, WebSocket maintains a persistent connection where both parties can send data anytime. It’s ideal for real-time applications like chat systems, live sports updates, collaborative editing, multiplayer games, and financial tickers. WebSocket reduces overhead compared to polling techniques and provides lower latency, though fallbacks like Server-Sent Events or long polling may be needed for older browser support.
99. What is GraphQL, and how does it differ from REST?
GraphQL is a query language and runtime for APIs that allows clients to request exactly the data they need in a single request, solving REST’s over-fetching and under-fetching problems. Instead of multiple endpoints, GraphQL uses one endpoint where clients send queries describing their data requirements. It provides a strongly-typed schema, real-time capabilities with subscriptions, and introspection for API documentation. While REST is simpler and has better caching, GraphQL offers more flexibility and efficiency, making it popular for complex applications with diverse client needs.
100. What are Web Accessibility (a11y) standards and why are they important?
Web accessibility ensures websites are usable by everyone, including people with disabilities (visual, auditory, motor, and cognitive). WCAG (Web Content Accessibility Guidelines) provides standards organised around four principles: Perceivable (information presentable to all users), Operable (interface navigable by all), Understandable (information and operation clear), and Robust (compatible with assistive technologies). Key practices include semantic HTML, keyboard navigation, ARIA labels, colour contrast, alt text for images, and captions for videos. Accessibility is both a legal requirement in many jurisdictions and an ethical obligation that also improves overall user experience and SEO.