Here are 100 web developer interview questions and answers for freshers, covering HTML, CSS, JavaScript, basic backend concepts, version control, responsive design, debugging, and development tools. Each question is in bold, followed by a detailed answer. No dividing lines.
What is the difference between a web designer and a web developer?
Answer: A web designer focuses on the visual look and feel, user interface (UI), and user experience (UX) of a website – they create mockups and prototypes. A web developer takes those designs and implements them into functional websites using code (HTML, CSS, JavaScript, backend languages). Developers are further split into front-end (client-side) and back-end (server-side).
What are the three core technologies of front-end web development?
Answer: HTML (HyperText Markup Language) for structure, CSS (Cascading Style Sheets) for presentation and layout, and JavaScript for interactivity and dynamic behavior.
What is HTML and what does it stand for?
Answer: HTML stands for HyperText Markup Language. It is the standard markup language used to create the structure and content of web pages, using elements represented by tags (e.g., <h1>, <p>, <div>).
What is the difference between HTML elements and tags?
Answer: Tags are the angle-bracketed names (e.g., <p>, </p>). An element includes the opening tag, content, and closing tag (e.g., <p>Hello</p>). Empty elements (like <img>) have only one tag.
What is the purpose of the <!DOCTYPE html> declaration?
Answer: It tells the browser to render the page in standards mode (as opposed to quirks mode). For HTML5, it is simply <!DOCTYPE html>. It must be the first line of an HTML document.
What are semantic HTML elements? Give examples.
Answer: Semantic elements clearly describe their meaning to both browser and developer. Examples: <header>, <footer>, <article>, <section>, <nav>, <aside>, <main>. They improve accessibility and SEO.
What is the difference between a <div> and a <span>?
Answer: <div> is a block-level element used to group larger sections of content; it starts on a new line and takes full width. <span> is an inline element used to group small pieces of text or elements within a line; it does not break to a new line.
What is the purpose of the alt attribute in images?
Answer: The alt attribute provides alternative text for an image if it cannot be displayed. It improves accessibility for screen readers and helps SEO. It is required for valid HTML.
What are the different heading tags in HTML?
Answer: <h1> to <h6>, where <h1> is the highest (most important) level and <h6> the lowest. Usually only one <h1> per page for the main title.
What is an anchor tag and what attribute makes it clickable?
Answer: The <a> (anchor) tag creates a hyperlink. The href attribute specifies the destination URL. Example: <a href=”https://example.com”>Link text</a>.
What is the difference between absolute and relative URLs?
Answer: Absolute URLs contain the full address (protocol, domain, path) – e.g., https://example.com/images/logo.png. Relative URLs are relative to the current page’s location – e.g., images/logo.png. Relative URLs are shorter and work better when moving a site.
What is the difference between id and class attributes in HTML?
Answer: An id must be unique within a page and is used to target a single element. A class can be used on multiple elements to apply the same styling or behavior. JavaScript and CSS can select by both.
What is the <meta> tag used for? Give an example.
Answer: The <meta> tag provides metadata about the HTML document, such as character set, viewport settings, description, and keywords. Example: <meta charset="UTF-8"> and <meta name="viewport" content="width=device-width, initial-scale=1.0">.
What is the difference between localStorage and sessionStorage?
Answer: Both are web storage APIs. localStorage stores data with no expiration time; data persists even after the browser is closed. sessionStorage stores data only for the current session (tab/window); data is cleared when the tab is closed.
What is the purpose of the <script> tag?
Answer: The <script> tag is used to embed or reference JavaScript code in an HTML page. It can be placed in <head> or <body>. For external scripts, use the src attribute.
Name five common HTTP methods.
Answer: GET (retrieve data), POST (submit data), PUT (update/replace resource), PATCH (partial update), DELETE (remove resource). Also HEAD and OPTIONS.
What is the difference between GET and POST?
Answer: GET requests data from a server; parameters are appended to the URL (visible, bookmarked, limited length). POST sends data to the server in the request body (no size limit, not cached, not visible in URL), used for forms and sensitive data.
What is CSS and what does it stand for?
Answer: CSS stands for Cascading Style Sheets. It is used to control the presentation (colors, fonts, layout) of HTML elements on a web page.
What are the three ways to add CSS to an HTML document?
Answer: 1) Inline CSS – using the style attribute on an element. 2) Internal CSS – using a <style> tag in the <head>. 3) External CSS – linking an external .css file using <link rel="stylesheet" href="style.css">.
What is the difference between margin and padding?
Answer: Margin is the space outside an element’s border, affecting distance from other elements. Padding is the space inside an element’s border, between border and content. Padding increases the element’s total size.
What is the box model in CSS?
Answer: The box model describes each element as a rectangular box consisting of: content (width/height), padding (space inside border), border, and margin (space outside). The total width = width + left/right padding + left/right border + left/right margin.
What is the difference between display: none and visibility: hidden?
Answer: display: none removes the element from the document layout – it takes no space and is not rendered. visibility: hidden hides the element but retains its occupied space, so layout does not shift.
What is the difference between inline, block, and inline-block display?
Answer: block elements start on a new line and take full width. inline elements do not start a new line and only take necessary width; width/height ignored. inline-block elements sit inline but can have width/height and margins.
What is CSS specificity and how is it calculated?
Answer: Specificity determines which CSS rule applies when multiple rules target the same element. Calculation: inline styles (1000), IDs (100), classes/attributes/pseudo-classes (10), element/pseudo-element (1). Higher score wins. !important overrides, but should be used sparingly.
What are CSS pseudo-classes and pseudo-elements? Give examples.
Answer: Pseudo-classes (single colon) target a state of an element: :hover, :focus, :first-child. Pseudo-elements (double colon) style part of an element: ::before, ::after, ::first-line. Both enhance styling without extra HTML.
What are media queries and why are they used?
Answer: Media queries apply CSS rules based on device characteristics (screen width, orientation, resolution). They are essential for responsive design. Example: @media (max-width: 768px) { body { font-size: 14px; } }.
What is responsive web design?
Answer: Responsive web design ensures that a website looks and functions well on all devices (desktops, tablets, mobiles). Techniques include fluid grids (percentages), flexible images (max-width: 100%), media queries, and relative units (rem, vw, vh).
What are CSS preprocessors (Sass, Less)?
Answer: CSS preprocessors extend CSS with variables, nesting, mixins, functions, and modular files. They produce standard CSS after compilation. Sass is the most popular. They help write maintainable, DRY code.
What is the z-index property?
Answer: z-index controls the stacking order of positioned elements (non-static). Higher z-index appears in front. It only works on elements with position set to relative, absolute, fixed, or sticky.
What is Flexbox and when would you use it?
Answer: Flexbox (CSS Flexible Box Layout) is a one-dimensional layout model for distributing space along a row or column. Use it for aligning items, centering content, building navigation bars, and creating equal-height columns.
What is CSS Grid and how does it differ from Flexbox?
Answer: CSS Grid is a two-dimensional layout system for rows and columns simultaneously. Flexbox is one-dimensional (row or column). Use Grid for overall page structure, Flexbox for components or alignment along a single axis.
How do you center a <div> horizontally in CSS?
Answer: For block elements with a width, use margin: 0 auto. For flex parent, use justify-content: center. For text/inline content, use text-align: center on parent.
How do you center a <div> vertically and horizontally?
Answer: Flexbox: display: flex; justify-content: center; align-items: center; on parent. Grid: display: grid; place-items: center;. Absolute positioning + transform: position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); on the element.
What is the difference between rem and em units?
Answer: rem (root em) is relative to the root (<html>) font-size. em is relative to the parent element’s font-size. rem is preferred for global consistency to avoid compounding size issues.
What is JavaScript and what is it used for?
Answer: JavaScript is a high-level, interpreted programming language used to add interactivity and dynamic behavior to web pages: handling events, manipulating DOM, fetching data (AJAX), animating elements, and much more.
What is the difference between var, let, and const?
Answer: var is function-scoped, can be redeclared, and is hoisted. let and const are block-scoped, cannot be redeclared in same scope, and have temporal dead zone. const cannot be reassigned (but its properties can be mutated). Use let and const instead of var.
What is hoisting in JavaScript?
Answer: Hoisting moves declarations (not initializations) to the top of their scope during compilation. var variables are hoisted with undefined; function declarations are hoisted fully. let and const are hoisted but not initialized (temporal dead zone).
What is the difference between == and ===?
Answer: == compares values after type coercion (e.g., 0 == false is true). === compares both value and type without coercion (strict equality). Always use === to avoid unexpected bugs.
What is a function? How do you declare it?
Answer: A function is a reusable block of code that performs a specific task. Declarations: function name(parameters) { } (function declaration), const name = function(parameters) { } (function expression), or arrow function const name = (parameters) => { }.
What is an arrow function and how is it different?
Answer: Arrow functions (() => {}) have a shorter syntax, do not have their own this, arguments, or super; they inherit this from the outer scope. They cannot be used as constructors (no new).
What is the DOM (Document Object Model)?
Answer: The DOM is a tree-like representation of an HTML document, allowing programs (JavaScript) to change document structure, style, and content. It consists of nodes (elements, attributes, text). The global document object provides access.
How do you select elements from the DOM using JavaScript?
Answer: Methods: getElementById(), getElementsByClassName(), getElementsByTagName(), querySelector() (returns first match), querySelectorAll() (returns all matches). Modern choice: querySelector and querySelectorAll using CSS selectors.
What is an event in JavaScript? Give examples.
Answer: An event is an action that occurs in the browser, triggered by the user or the browser itself. Examples: click, mouseover, keydown, load, submit, scroll. You can attach event listeners using addEventListener().
What is event bubbling?
Answer: Event bubbling is propagation of an event from the target element up through its ancestors. If you click a button inside a div, the button’s click event fires first, then the div’s, then the body’s. You can stop propagation with stopPropagation().
What is event delegation?
Answer: Event delegation attaches a single event listener to a parent element instead of individual child elements. The listener uses event targeting to handle events for current and future children. Improves performance and handles dynamic content.
What is a callback function?
Answer: A callback is a function passed as an argument to another function, executed later (after an asynchronous operation or event). Callbacks are used for asynchronous tasks like timers, event handlers, and AJAX requests.
What is setTimeout and setInterval?
Answer: setTimeout(callback, delay) executes the callback once after the specified delay (in milliseconds). setInterval(callback, interval) repeatedly executes the callback every interval milliseconds. Use clearTimeout and clearInterval to cancel.
What is a Promise in JavaScript?
Answer: A Promise represents the eventual completion (or failure) of an asynchronous operation. It has three states: pending, fulfilled (resolved), rejected. Use .then() (success), .catch() (error), and .finally().
What is async/await?
Answer: async/await is syntactic sugar over Promises, making asynchronous code look synchronous. An async function returns a promise. await pauses the function until the promise resolves. Always use try/catch for error handling.
What is the difference between null and undefined?
Answer: undefined means a variable has been declared but not assigned a value. null is an intentional assignment representing “no value” or “empty”. typeof null returns “object” (JavaScript quirk), typeof undefined returns “undefined”.
What are data types in JavaScript?
Answer: Primitive types: string, number, boolean, null, undefined, symbol, bigint. Reference type: object (including arrays, functions, dates). Primitives are immutable and stored by value; objects stored by reference.
What is an array and how do you create one?
Answer: An array is an ordered collection of values (of any type). Create using let arr = [1, 2, 3] (array literal) or let arr = new Array(5). Access elements by index (0-based). Common methods: push, pop, shift, unshift, map, filter, reduce.
What is the map() method?
Answer: map() creates a new array by applying a callback function to each element of the original array. It does not mutate the original array. Example: [1,2,3].map(x => x*2) returns [2,4,6].
What is the filter() method?
Answer: filter() creates a new array with all elements that pass a test implemented by the callback function. Example: [1,2,3,4].filter(x => x > 2) returns [3,4].
What is the reduce() method?
Answer: reduce() executes a reducer function on each element, resulting in a single output value. It accumulates from left to right. Example: [1,2,3].reduce((sum, curr) => sum + curr, 0) returns 6.
What is the difference between forEach and map?
Answer: forEach iterates through array elements, returns undefined, and is used for side effects. map returns a new array of the same length, used for transformation. forEach cannot be chained like map.
What is an object in JavaScript? How do you access properties?
Answer: An object is a collection of key-value pairs (properties). Create using {}. Access properties using dot notation (obj.key) or bracket notation (obj[“key”]). Use bracket for dynamic keys or keys with spaces.
What is JSON?
Answer: JSON (JavaScript Object Notation) is a lightweight data interchange format, derived from object syntax. Keys and strings must be double-quoted. Used for APIs and configuration. Convert with JSON.stringify() (object to JSON) and JSON.parse() (JSON to object).
What is the difference between == and ===?
Answer: (Already covered earlier) Strict equality (===) is preferred.
What is the difference between undefined and not defined?
Answer: undefined is a value assigned to a declared but uninitialized variable. “not defined” (reference error) occurs when you try to access a variable that has not been declared at all.
What are cookies in web development?
Answer: Cookies are small pieces of data stored on the user’s browser by websites. They are sent with every HTTP request to the same domain. Used for session management, user preferences, and tracking. Limited to 4KB.
What is the difference between alert, confirm, and prompt?
Answer: alert() shows a message with an OK button. confirm() shows a message with OK and Cancel, returning a boolean. prompt() asks for text input, returning the input string or null. These are blocking and not recommended for modern UI.
What is the this keyword in JavaScript?
Answer: this refers to the context in which a function is executed. In a method, this is the object. In a regular function (non-strict), this is the global object (window). In arrow functions, this is lexically inherited from the outer scope. In event handlers, this is the element.
What is the difference between null and undefined?
Answer: (Already covered earlier)
What is strict mode in JavaScript?
Answer: Strict mode ('use strict';) enforces stricter parsing and error handling: eliminates silent errors, prevents accidental globals, forbids with, changes this behavior, and improves performance. Use at the top of a script or function.
What is the purpose of the console object?
Answer: The console object provides methods for debugging: console.log(), console.error(), console.warn(), console.table(), console.time()/timeEnd(). It is used to output messages to the browser’s developer tools.
What does the debugger keyword do?
Answer: The debugger statement stops the execution of JavaScript and invokes the debugging interface (if available), allowing you to inspect variables and step through code in the browser dev tools.
What is Git and why is it used?
Answer: Git is a distributed version control system used to track changes in source code, collaborate with teams, and manage different versions (branches). It allows reverting changes, branching, merging, and working offline.
What is the difference between git pull and git fetch?
Answer: git fetch downloads changes from the remote repository without merging them into your local branch. git pull downloads changes and immediately merges them (equivalent to fetch + merge). Use fetch to review changes before merging.
What is a branch in Git?
Answer: A branch is a separate line of development that diverges from the main codebase. Branches allow developers to work on features, bug fixes, or experiments without affecting the stable code. The default branch is often main or master.
What is a commit in Git?
Answer: A commit is a snapshot of changes at a specific point in time, with a unique hash, author information, timestamp, and a descriptive message. Commits form the history of a repository.
What is the purpose of git status?
Answer: git status shows the current state of the working directory and staging area: which files are tracked, modified, staged, or untracked.
What is the difference between git merge and git rebase?
Answer: git merge combines branches by creating a merge commit, preserving history. git rebase reapplies commits from one branch onto the tip of another, creating a linear history. Rebasing rewrites history; do not rebase shared branches.
What is responsive web design?
Answer: (Already covered earlier) Use media queries, flexible grids, and images.
What is progressive enhancement?
Answer: Progressive enhancement starts with a baseline of basic functionality (HTML) that works on all browsers, then layers on CSS for presentation and JavaScript for interactivity for capable browsers. It ensures accessibility and backward compatibility.
What is graceful degradation?
Answer: Graceful degradation builds for modern browsers first, then ensures that the site still works (with reduced functionality) on older browsers. Progressive enhancement is generally preferred.
What are some browser developer tools features?
Answer: Elements panel (inspect DOM and CSS), Console (execute JS and view logs), Network tab (monitor requests), Performance tab (profile load times), Application tab (storage, cookies), Sources (debug JS with breakpoints).
What is cross-browser compatibility?
Answer: Cross-browser compatibility ensures that a website works consistently across different browsers (Chrome, Firefox, Safari, Edge) and their versions. Use feature detection (not browser detection), CSS resets/normalize, vendor prefixes, and polyfills for missing features.
What is a polyfill?
Answer: A polyfill is a piece of code (usually JavaScript) that provides modern functionality on older browsers that do not natively support it. Examples: fetch polyfill, Intersection Observer polyfill.
What is the viewport meta tag?
Answer: <meta name="viewport" content="width=device-width, initial-scale=1"> tells the browser to set the viewport width equal to the device screen width and initial zoom level. Essential for responsive design on mobile devices.
What is the difference between a web server and an application server?
Answer: A web server (e.g., Nginx, Apache) handles HTTP requests and serves static content (HTML, CSS, JS). An application server (e.g., Tomcat, Node.js, JBoss) runs business logic, interacts with databases, and generates dynamic content. Often they work together.
What is HTTP and HTTPS?
Answer: HTTP (HyperText Transfer Protocol) is the protocol for transferring web pages. HTTPS (HTTP Secure) uses SSL/TLS encryption to secure data between browser and server, protecting against eavesdropping and tampering. HTTPS is mandatory for modern websites.
What are HTTP status codes? Give examples.
Answer: 1xx (Informational), 2xx (Success – 200 OK), 3xx (Redirection – 301 Moved Permanently, 302 Found), 4xx (Client Error – 404 Not Found, 403 Forbidden), 5xx (Server Error – 500 Internal Server Error).
What is the difference between a URL and a URI?
Answer: A URI (Uniform Resource Identifier) identifies a resource. A URL (Uniform Resource Locator) is a type of URI that also specifies how to locate (access) the resource (protocol, domain, path). Every URL is a URI, but not every URI is a URL.
What is AJAX?
Answer: AJAX (Asynchronous JavaScript and XML) is a technique for sending and receiving data from a server asynchronously without reloading the page. Modern implementation uses fetch() or XMLHttpRequest with JSON instead of XML.
What is the fetch API?
Answer: fetch() is a modern, promise-based API for making HTTP requests. Example: fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)). It supports options like method, headers, body.
What is the difference between localStorage and sessionStorage?
Answer: (Already covered earlier)
What is a CDN (Content Delivery Network)?
Answer: A CDN is a distributed network of servers that deliver static assets (images, CSS, JS) to users from the closest geographic location, reducing latency and server load.
What is the purpose of a package.json file?
Answer: The package.json file is used in Node.js projects to manage dependencies, scripts, project metadata, and versioning. It allows installing packages via npm or yarn. Example: npm install express adds express to dependencies.
What are npm and npx?
Answer: npm (Node Package Manager) is the default package manager for Node.js – installs, updates, and manages dependencies. npx (Node Package Runner) executes Node packages without installing them globally (e.g., npx create-react-app).
What is a build tool (e.g., Webpack, Vite)?
Answer: Build tools bundle, minify, transpile (e.g., TypeScript to JS, Sass to CSS), and optimize code for production. They also support development features like hot module replacement. Vite is faster for development due to native ES modules.
What is the difference between deploying on GitHub Pages vs Netlify?
Answer: GitHub Pages hosts static sites directly from a GitHub repository for free, with limited features. Netlify offers continuous deployment from Git, serverless functions, form handling, and more advanced features for static sites, with a generous free tier.
What is a responsive image? How do you implement it?
Answer: Responsive images adapt to different screen sizes and resolutions. Techniques: srcset and sizes attributes on <img>, <picture> element with multiple <source> media queries, max-width: 100% in CSS, and object-fit property.
What is lazy loading of images?
Answer: Lazy loading defers loading images until they are about to enter the viewport, improving initial page load time. Use the loading="lazy" attribute on <img> or <iframe>, or implement using Intersection Observer.
What is the role of a front-end framework (React, Vue, Angular)?
Answer: These frameworks help build complex, interactive user interfaces by providing component-based architecture, state management, data binding, and efficient DOM updates (virtual DOM, etc.). They increase productivity and maintainability.
What is the difference between a library and a framework?
Answer: A library (e.g., jQuery, React) is a collection of functions you call; you control the flow. A framework (e.g., Angular) provides an inversion of control – it calls your code following its own patterns. Libraries are easier to integrate, frameworks impose more structure.
What is the difference between client-side and server-side rendering?
Answer: Client-side rendering (CSR) generates HTML in the browser using JavaScript after loading an empty shell. Server-side rendering (SSR) generates full HTML on the server for each request, improving SEO and initial load time. Frameworks like Next.js support SSR.
How do you debug a website that works on your local machine but breaks in production?
Answer: Check differences: environment variables, file paths, server configuration, minification errors, cross-origin issues, caching, or newer browser version differences. Replicate production environment locally (e.g., use same Node version). Use remote debugging tools and check browser console for errors.
What are some best practices for web performance?
Answer: Minify CSS/JS, compress images (WebP, lazy loading), use CDN, enable caching, reduce render-blocking resources, defer or async scripts, code splitting, and use performance audits (Lighthouse).
What is the difference between innerHTML and textContent?
Answer: innerHTML gets or sets HTML markup inside an element, which can cause XSS if used with unsanitized user input. textContent gets or sets plain text only, ignoring HTML tags, and is safer. Use textContent for text, innerHTML with caution.
What is a variable scope in JavaScript?
Answer: Scope determines where variables are accessible. Global scope (outside any function), function scope (inside a function with var), block scope (inside {} with let, const). Lexical scope means inner functions can access variables of outer functions.
What is a closure?
Answer: A closure is a function that remembers and accesses its lexical scope even after the outer function has returned. Example: inner function accessing a variable from its parent that persists. Closures enable data privacy and functional programming patterns.
What is the difference between slice and splice?
Answer: slice(start, end) returns a shallow copy of a portion of an array without modifying the original. splice(start, deleteCount, items) changes the original array by removing/replacing elements. splice returns the removed items.
What is the difference between event.preventDefault() and stopPropagation()?
Answer: preventDefault() stops the browser’s default action for an event (e.g., form submission, link navigation). stopPropagation() stops the event from bubbling up or capturing down the DOM tree. They are independent.
What is the purpose of the typeof operator?
Answer: typeof returns a string indicating the type of an unoperand: typeof 42 → “number”, typeof “hello” → “string”, typeof true → “boolean”, typeof undefined → “undefined”, typeof null → “object” (quirk), typeof {} → “object”, typeof function(){} → “function”.
What is the for...of loop?
Answer: for...of iterates over iterable objects (arrays, strings, maps, sets). It returns values, not indexes. Example: for (let value of [1,2,3]) { console.log(value); }. Contrast with for...in which iterates over enumerable property keys.
What is the difference between for...in and for...of?
Answer: for...in iterates over enumerable property keys (including inherited) of an object. It should not be used for arrays. for...of iterates over iterable values (arrays, strings, etc.) and is safe for arrays.
How do you handle errors in JavaScript?
Answer: Use try...catch block to handle synchronous errors. For promises, use .catch() or try/catch with async/await. For global errors, use window.onerror or unhandledrejection event.
What is the difference between a deep copy and a shallow copy?
Answer: Shallow copy copies only the top-level properties; nested objects are still referenced. Deep copy copies all levels (new independent objects). Shallow: Object.assign() or spread {...obj}. Deep: JSON.parse(JSON.stringify(obj)) (limited), or libraries like Lodash’s _.cloneDeep().
What is the purpose of the new keyword?
Answer: The new keyword creates an instance of a user-defined object type or built-in constructor. It creates a new object, sets its prototype, executes the constructor function with this bound to the new object, and returns the object.
What is NaN in JavaScript?
Answer: NaN (Not a Number) is a value representing an invalid or unrepresentable number (e.g., 0/0, parseInt(“abc”)). NaN is not equal to itself; use isNaN() or Number.isNaN() to check.
What are template literals?
Answer: Template literals use backticks (`) and allow embedded expressions with ${expression}. They support multi-line strings without escaping. Example: `Hello ${name}!`.
What is the difference between static and instance methods in JavaScript classes?
Answer: Static methods are called on the class itself (e.g., Math.random()) and cannot be called on instances. Instance methods are called on objects created from the class (e.g., myArray.map()). Static methods are often utility functions.
What is the purpose of the use strict directive?
Answer: (Already covered earlier) Enforces stricter parsing and error handling.
Why is it important to use semantic HTML?
Answer: Semantic HTML (e.g., <header>, <nav>, <article>) improves accessibility for screen readers, enhances SEO (search engines understand structure better), improves code readability, and provides a consistent document outline.
What are some common accessibility (a11y) best practices?
Answer: Use semantic HTML, provide alt text for images, proper heading hierarchy, sufficient color contrast, keyboard navigation (focus indicators), ARIA labels where needed, and test with screen readers.
How do you optimize a website for search engines (SEO) as a developer?
Answer: Use semantic HTML, descriptive title and meta description, proper heading structure, alt attributes for images, fast page speed, mobile-friendly design, clean URLs, structured data (schema), and ensure crawlers can access pages (no blocking in robots.txt).
What is the difference between git merge and git rebase?
Answer: (Already covered earlier) merge preserves history, rebase creates linear history.
What is a pull request in Git?
Answer: A pull request (PR) is a request to merge changes from one branch into another (often feature branch into main). It allows code review, discussion, and automated testing before merging. Used on platforms like GitHub, GitLab, Bitbucket.
What is the purpose of the .gitignore file?
Answer: .gitignore specifies files and directories that Git should ignore (not track) – e.g., node_modules, environment files, build outputs, logs.
What is DOM manipulation?
Answer: DOM manipulation refers to using JavaScript to add, remove, modify, or interact with elements in the DOM. Examples: createElement, appendChild, removeChild, setAttribute, innerHTML, classList.
What is the difference between textContent and innerText?
Answer: textContent gets the text content of all nodes (including hidden elements), returns raw text. innerText gets only visible text, respects CSS styling (e.g., displays line breaks), and triggers reflow. textContent is generally faster and more consistent.
How do you make an HTTP request in JavaScript?
Answer: Using fetch() (modern) or XMLHttpRequest (older). Example: fetch(url).then(res => res.json()).then(data => console.log(data)). Include error handling with .catch().
What are WebSockets?
Answer: WebSockets provide a persistent, full-duplex communication channel between browser and server, ideal for real-time applications (chat, live updates, gaming). Unlike HTTP, the connection stays open.
What is a cookie?
Answer: (Covered earlier)
What is the localStorage maximum size?
Answer: Typically around 5-10MB per origin, varying by browser. sessionStorage similar.
What is a Promise chaining?
Answer: Returning a promise from a .then() handler creates a chain, allowing sequential asynchronous operations. The next .then() receives the resolved value of the returned promise. This avoids callback nesting.
What is the difference between Promise.all and Promise.race?
Answer: Promise.all waits for all promises to resolve (or any one to reject), returns array of results. Promise.race resolves or rejects as soon as the first promise settles (returns its value). Also Promise.allSettled waits for all to settle (ignore rejection). Promise.any returns first fulfilled.
What is a static website?
Answer: A static website serves fixed content (HTML, CSS, JS) without server-side processing. It is fast, cheap to host (CDN), but content updates require rebuilding. Examples: portfolios, documentation.
What is a dynamic website?
Answer: A dynamic website generates content on the server (or client) based on user interaction, database queries, or other variables. It uses server-side languages (PHP, Node.js, Python) and often a database.
What is a web framework (Express, Django, Rails, Laravel)?
Answer: Web frameworks provide a structured way to build web applications. They handle routing, request/response, sessions, templating, and database abstraction, accelerating development and enforcing best practices.
What is the difference between front-end and back-end development?
Answer: Front-end (client-side) deals with what users see and interact with in the browser (HTML, CSS, JS, frameworks). Back-end (server-side) handles server logic, databases, authentication, APIs, and business logic. Both communicate over HTTP.
What is an API?
Answer: API (Application Programming Interface) defines how different software components interact. In web development, RESTful APIs expose endpoints (URLs) that accept HTTP requests and return structured data (JSON/XML).
What is the difference between REST and GraphQL?
Answer: REST is an architectural style with fixed endpoints for resources; often overfetches or underfetches. GraphQL is a query language where clients specify exactly what data they need, fetching it in one request. GraphQL reduces network requests but adds complexity.
What is a package manager?
Answer: A package manager (npm, yarn, pnpm) automates installing, upgrading, configuring, and removing dependencies. It resolves version conflicts and maintains a lock file for consistent installations.
What is the purpose of a .map file?
Answer: A source map (.map) maps minified/transpiled code back to original source code for debugging. It allows browsers to show original source lines in dev tools.
What is a CSS reset?
Answer: A CSS reset removes default browser styling (margins, paddings, font sizes) to provide a consistent baseline across browsers. Examples: Normalize.css, reset.css.
What are vendor prefixes in CSS?
Answer: Vendor prefixes (-webkit-, -moz-, -ms-, -o-) are used to apply experimental or non-standard CSS properties for specific browsers. Modern CSS tools (autoprefixer) add them automatically based on browser support.
What is the difference between a class and an ID selector in CSS?
Answer: ID selector (#myId) targets a unique element; class selector (.myClass) can target multiple elements. ID has higher specificity. Use classes for styling, IDs for JavaScript hooks or page anchors.
What is the difference between relative, absolute, fixed and sticky positioning?
Answer: relative positions element relative to its normal position. absolute positions relative to nearest positioned ancestor. fixed positions relative to viewport (stays on scroll). sticky toggles between relative and fixed based on scroll threshold.
What is the difference between <section> and <div>?
Answer: <section> is semantic; it represents a thematic grouping of content, typically with a heading. <div> is non-semantic; used for layout or styling containers. Use <section> when the content has a natural meaning.
What is the :root pseudo-class?
Answer: :root targets the highest-level parent (html). It is used to define global CSS custom properties (variables) with higher specificity than html.
What is :nth-child()?
Answer: :nth-child() selects elements based on their position among siblings. Example: li:nth-child(odd) selects every odd list item. It can use formulas like 2n+1.
What is the difference between :first-child and :first-of-type?
Answer: :first-child selects the first element among all children of a parent. :first-of-type selects the first occurrence of its element type among siblings (e.g., first paragraph).
What is the transform property?
Answer: transform applies visual effects (rotate, scale, translate, skew, or matrix) to an element without affecting layout flow. It is hardware-accelerated and used for animations.
What is the transition property?
Answer: transition animates changes of CSS properties over a specified duration, easing, and delay. Example: transition: all 0.3s ease. It requires a change in property value (e.g., hover).
What is the animation property?
Answer: animation makes keyframe-based animations. First define keyframes with @keyframes, then apply with animation: name duration iteration-count. More complex than transition.
What is the purpose of preconnect and preload link tags?
Answer: <link rel="preconnect" href="https://api.example.com"> tells the browser to set up early connection to that origin. <link rel="preload" href="style.css" as="style"> downloads a resource early, improving performance.
What is the difference between localStorage and Cookies?
Answer: Cookies are sent with every HTTP request (4KB limit, can be set to expire). localStorage is not sent to server, persists until cleared, larger size (5-10MB). Use localStorage for client-only data, cookies for authentication tokens.
What is the difference between innerHTML and outerHTML?
Answer: innerHTML sets or gets HTML content inside an element. outerHTML includes the element itself and its content, replacing the element when set.
What is event capturing?
Answer: Event capturing is the first phase of event propagation (from window down to target). By default, event listeners use bubbling. Add true as third parameter to addEventListener to capture.
What is the arguments object?
Answer: arguments is an array-like object available inside non-arrow functions, containing the arguments passed to the function. It has length and can be indexed but not array methods. Use rest parameters (...args) in modern code.
What is the difference between function declaration and function expression?
Answer: Function declaration: function foo() {} – hoisted (can be called before declaration). Function expression: const foo = function() {} – not hoisted; variable is hoisted but not the assignment. Arrow functions are expressions.
What is recursion?
Answer: Recursion is a technique where a function calls itself to solve a problem that can be broken into smaller sub-problems (e.g., tree traversal, factorial). Must have a base case to avoid infinite recursion.
What are higher-order functions?
Answer: A higher-order function is a function that takes another function as an argument or returns a function. Examples: map, filter, reduce, setTimeout, addEventListener.
What is a callback hell and how can you avoid it?
Answer: Callback hell is deeply nested callbacks making code unreadable. Avoid by using Promises, async/await, modularization, or using libraries like async.js.
What is JSONP?
Answer: JSONP (JSON with Padding) was a workaround to bypass same-origin policy before CORS. It used <script> tags to load JSON from another domain. Obsolescent; use CORS or proxy.
What is CORS?
Answer: Cross-Origin Resource Sharing (CORS) is a security mechanism that allows or restricts web pages from making requests to a different domain than the one that served the page. Browsers send preflight OPTIONS request. The server must include Access-Control-Allow-Origin header.
What is the difference between GET and DELETE idempotency?
Answer: Both are idempotent. Multiple identical GET requests return same result (if no changes). Multiple DELETE requests: first deletes, subsequent ones return 404 or 204, but server state remains deleted – still idempotent.
What is a REST API?
Answer: REST (Representational State Transfer) API is an architectural style using HTTP methods (GET, POST, PUT, DELETE) to perform CRUD operations on resources. Stateless, uses URLs to identify resources, returns JSON/XML.
What is Postman used for?
Answer: Postman is a tool for testing, developing, and documenting APIs. It allows making HTTP requests, saving collections, automating tests, and generating client code.
What are some common HTTP headers?
Answer: Content-Type, Authorization, Accept, User-Agent, Cache-Control, Set-Cookie, Location, CORS headers (Access-Control-Allow-Origin).
What is the difference between null and undefined in JavaScript?
Answer: (Already covered earlier)
What is a simple way to make a website responsive?
Answer: Use viewport meta tag, set images to max-width: 100%, use media queries, and build with relative units (%, vw, rem). Start with a mobile-first approach – styles for small screens, then add min-width queries.
Why should we hire you as a web developer fresher?
Answer: I have strong fundamentals in HTML, CSS, JavaScript, and version control. I am a fast learner, attentive to detail, and passionate about building clean, functional, and accessible websites. I have built personal projects (e.g., a responsive portfolio, a to-do app) that demonstrate my skills. I am eager to contribute to your team and grow professionally.