HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
HTML, CSS & JavaScript
Interview Questions and Answers
Fresher-focused preparation guide for web development interviews
Candidate Mohan Krishna Reddy Ponnala
Focus Only HTML, CSS, JavaScript
Level Fresher / entry-level interview
Technical rounds, web fundamentals, resume-based
Best for
questioning
Read the short answer first, then practice explaining
How to use
with one example
Note: This PDF intentionally excludes React, [Link], Express, databases, AEM, Python, and ML because you asked for only
HTML, CSS, and JavaScript.
Prepared for Mohan Krishna Reddy | Page 1
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
How to Prepare
For each question, do not memorize word-by-word. Understand the meaning and speak naturally.
In fresher interviews, the interviewer checks clarity, basics, honesty, and whether you can connect theory to a small
example.
When answering, use this pattern: Definition -> Simple example -> Real use case.
Topic Coverage
Topic Questions Main areas
HTML 50 Document structure, semantic HTML,
forms, tables, accessibility, meta tags
CSS 55 Selectors, cascade, box model, layout,
Flexbox, Grid, responsive design
JavaScript 103 Variables, functions, arrays, objects,
DOM, events, async, APIs, coding
questions
Prepared for Mohan Krishna Reddy | Page 2
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
HTML Interview Questions and Answers
Q1. What is HTML?
Answer: HTML stands for HyperText Markup Language. It is used to structure web page content such as headings,
paragraphs, links, images, forms, and tables.
Q2. Is HTML a programming language?
Answer: No. HTML is a markup language, not a programming language. It describes the structure of content; it does not
contain logic like loops or conditions.
Q3. What is the basic structure of an HTML document?
Answer: A basic page has <!DOCTYPE html>, <html>, <head>, and <body>. The head contains metadata; the body
contains visible page content.
Q4. Why do we use <!DOCTYPE html>?
Answer: It tells the browser to render the page in modern standards mode instead of old quirks mode.
Q5. What is the difference between <head> and <body>?
Answer: The <head> stores metadata, title, links to CSS, scripts, and SEO information. The <body> contains visible
content shown to the user.
Q6. What are HTML elements and tags?
Answer: A tag is the markup like <p> or </p>. An element includes the opening tag, content, and closing tag, for example
<p>Hello</p>.
Q7. What is an attribute in HTML?
Answer: An attribute gives extra information about an element. Example: href in <a
href='[Link]
Q8. What are block-level elements?
Answer: Block elements normally start on a new line and take full available width. Examples: <div>, <p>, <h1>,
<section>, <table>.
Q9. What are inline elements?
Answer: Inline elements take only the space needed and do not start on a new line. Examples: <span>, <a>, <strong>,
<img>.
Q10. Difference between <div> and <span>?
Answer: <div> is a block-level container used for larger layout sections. <span> is an inline container used for small
text-level styling or grouping.
Q11. What are semantic HTML elements?
Answer: Semantic elements clearly describe their meaning, such as <header>, <nav>, <main>, <section>, <article>,
<aside>, and <footer>.
Q12. Why is semantic HTML important?
Answer: It improves readability, accessibility, SEO, and helps browsers/screen readers understand page structure.
Q13. Difference between <section> and <article>?
Answer: <section> groups related content under a theme. <article> represents independent content that can stand
alone, like a blog post or news item.
Q14. Difference between <header> and <head>?
Answer: <head> contains metadata not shown directly. <header> is a visible page or section header, usually containing
logo, title, or navigation.
Q15. What is the use of <main>?
Answer: <main> contains the primary content of the page. A page should usually have only one main element.
Q16. What is the difference between <b> and <strong>?
Answer: <b> only makes text visually bold. <strong> means the text is important and is usually displayed bold.
Q17. What is the difference between <i> and <em>?
Prepared for Mohan Krishna Reddy | Page 3
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
Answer: <i> gives italic styling. <em> gives emphasized meaning and is usually displayed italic.
Q18. How do you create a hyperlink?
Answer: Use the <a> tag with href. Example: <a href='[Link]
Q19. What is target='_blank'?
Answer: It opens the link in a new browser tab or window. For security, use rel='noopener noreferrer' with it.
Q20. Why use rel='noopener noreferrer'?
Answer: It prevents the newly opened page from controlling the original page and avoids leaking referral information
in some cases.
Q21. How do you add an image in HTML?
Answer: Use <img src='[Link]' alt='Description'>. The src gives image path and alt gives text description.
Q22. Why is the alt attribute important?
Answer: It helps screen reader users understand images and appears when an image fails to load. It also supports SEO.
Q23. What is the difference between absolute and relative URL?
Answer: An absolute URL has the full path including domain. A relative URL points to a file based on the current page
location.
Q24. What are lists in HTML?
Answer: HTML supports ordered lists <ol>, unordered lists <ul>, and description lists <dl>. List items use <li>.
Q25. How do you create a table?
Answer: Use <table>, <tr> for rows, <th> for header cells, and <td> for data cells.
Q26. What is the use of <thead>, <tbody>, and <tfoot>?
Answer: They group table header, body, and footer rows. This improves structure, styling, and accessibility.
Q27. What is colspan and rowspan?
Answer: colspan makes a cell span multiple columns. rowspan makes a cell span multiple rows.
Q28. How do you create a form in HTML?
Answer: Use <form> with input controls such as <input>, <textarea>, <select>, and <button>.
Q29. What are common input types?
Answer: Common types include text, email, password, number, date, radio, checkbox, file, submit, and hidden.
Q30. Difference between GET and POST in form method?
Answer: GET sends data in the URL and is used for searches. POST sends data in the request body and is used for
creating or submitting sensitive data.
Q31. What is the action attribute in a form?
Answer: action defines the URL where form data will be submitted.
Q32. What is the name attribute in form fields?
Answer: name is the key used when form data is submitted to the server. Without name, the field value may not be sent.
Q33. Difference between placeholder and value?
Answer: placeholder is hint text shown when input is empty. value is the actual current input value.
Q34. Difference between disabled and readonly?
Answer: disabled fields cannot be edited and are not submitted. readonly fields cannot be edited but are usually
submitted.
Q35. How do you make a field required?
Answer: Add the required attribute, for example <input type='email' required>.
Q36. What is HTML5 validation?
Answer: HTML5 provides built-in validation using attributes like required, type='email', min, max, minlength,
maxlength, and pattern.
Q37. What is the label tag?
Prepared for Mohan Krishna Reddy | Page 4
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
Answer: <label> describes a form field. Connecting label with input improves usability and accessibility.
Q38. How do you connect a label to input?
Answer: Use <label for='email'>Email</label> and <input id='email'>. The for value should match the input id.
Q39. What is an iframe?
Answer: <iframe> embeds another HTML page inside the current page, such as a map, video, or external widget.
Q40. What are meta tags?
Answer: Meta tags provide page metadata such as character set, viewport, description, and SEO/social sharing
information.
Q41. What is the viewport meta tag?
Answer: <meta name='viewport' content='width=device-width, initial-scale=1.0'> helps pages render properly on mobile
screens.
Q42. What is accessibility in HTML?
Answer: Accessibility means making web content usable for people with disabilities, including keyboard users and
screen reader users.
Q43. What are ARIA attributes?
Answer: ARIA attributes add accessibility information when native HTML is not enough. Prefer semantic HTML first,
then ARIA only when needed.
Q44. What is the difference between id and class in HTML?
Answer: id should be unique on a page. class can be reused on many elements for styling or selection.
Q45. Can multiple elements have the same id?
Answer: Technically browsers may still render it, but it is invalid HTML and can break CSS, JavaScript, and accessibility
behavior.
Q46. What is HTML entity?
Answer: An entity is used to display reserved/special characters. Example: < displays < and & displays &.
Q47. How do you include CSS in HTML?
Answer: CSS can be added inline with style, internally using <style>, or externally using <link rel='stylesheet'
href='[Link]'>.
Q48. How do you include JavaScript in HTML?
Answer: Use <script src='[Link]'></script> for external JS or write code inside <script>. Prefer external JS for
maintainability.
Q49. Difference between async and defer in script tag?
Answer: async downloads and executes as soon as ready, possibly before HTML parsing finishes. defer downloads
during parsing but runs after HTML is parsed, in order.
Q50. What is progressive enhancement?
Answer: It means building a working basic experience with HTML first, then enhancing with CSS and JavaScript.
Prepared for Mohan Krishna Reddy | Page 5
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
CSS Interview Questions and Answers
Q51. What is CSS?
Answer: CSS stands for Cascading Style Sheets. It controls the visual design of HTML pages, including colors, spacing,
layout, fonts, and responsiveness.
Q52. What are the ways to apply CSS?
Answer: Inline CSS, internal CSS using <style>, and external CSS using a .css file. External CSS is best for maintainability.
Q53. What is a CSS selector?
Answer: A selector targets HTML elements for styling. Examples: p, .card, #header, input[type='text'].
Q54. Difference between class selector and id selector?
Answer: Class selector starts with . and can be reused. ID selector starts with # and should target one unique element.
Q55. What is the cascade in CSS?
Answer: Cascade decides which style wins when multiple rules apply. It depends on importance, specificity, source
order, and inheritance.
Q56. What is CSS specificity?
Answer: Specificity is the priority of a selector. Inline styles have high priority, then IDs, then classes/attributes/pseudo-
classes, then elements.
Q57. What is !important?
Answer: !important forces a declaration to override normal rules. It should be avoided unless necessary because it
makes CSS harder to maintain.
Q58. What is inheritance in CSS?
Answer: Some properties like color and font-family are inherited from parent elements. Properties like margin and
border are usually not inherited.
Q59. What is the box model?
Answer: Every element is treated as a box with content, padding, border, and margin.
Q60. Difference between margin and padding?
Answer: Padding is space inside the element between content and border. Margin is space outside the element between
it and other elements.
Q61. What is box-sizing: border-box?
Answer: It makes width and height include content, padding, and border, which makes layouts easier to control.
Q62. Difference between inline, block, and inline-block?
Answer: Block starts on a new line and takes full width. Inline stays in line and ignores width/height. Inline-block stays
inline but allows width and height.
Q63. What is display: none?
Answer: It removes the element from layout and makes it invisible. The space is not reserved.
Q64. Difference between display:none and visibility:hidden?
Answer: display:none removes the element from layout. visibility:hidden hides it but keeps its space.
Q65. What is opacity?
Answer: opacity controls transparency from 0 to 1. opacity:0 hides visually but the element still occupies space and may
receive events.
Q66. What are CSS units?
Answer: Common units include px, %, em, rem, vh, vw. Use rem for scalable typography and %/vw/vh for responsive
layouts.
Q67. Difference between em and rem?
Answer: em is relative to the parent/current font size. rem is relative to the root html font size.
Q68. What is position: static?
Prepared for Mohan Krishna Reddy | Page 6
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
Answer: static is the default positioning. The element appears in normal document flow.
Q69. What is position: relative?
Answer: The element stays in normal flow but can be shifted using top/right/bottom/left relative to its original position.
Q70. What is position: absolute?
Answer: The element is removed from normal flow and positioned relative to the nearest positioned ancestor.
Q71. What is position: fixed?
Answer: The element is positioned relative to the viewport and stays in place while scrolling.
Q72. What is position: sticky?
Answer: The element behaves normally until a scroll threshold, then sticks to a position like top: 0.
Q73. What is z-index?
Answer: z-index controls stacking order of positioned elements. Higher z-index appears above lower z-index.
Q74. What is Flexbox?
Answer: Flexbox is a one-dimensional layout system used to arrange items in a row or column with flexible spacing and
alignment.
Q75. What is the difference between justify-content and align-items?
Answer: justify-content aligns items along the main axis. align-items aligns items along the cross axis.
Q76. How do you center a div using Flexbox?
Answer: Use display:flex; justify-content:center; align-items:center; on the parent container.
Q77. What is flex-direction?
Answer: It defines the main axis direction: row, row-reverse, column, or column-reverse.
Q78. What is flex-wrap?
Answer: flex-wrap allows flex items to move to the next line when there is not enough space.
Q79. What is CSS Grid?
Answer: CSS Grid is a two-dimensional layout system for rows and columns.
Q80. Difference between Flexbox and Grid?
Answer: Flexbox is best for one-dimensional layouts. Grid is best for two-dimensional page layouts with rows and
columns.
Q81. What is grid-template-columns?
Answer: It defines the column structure of a grid. Example: grid-template-columns: 1fr 2fr creates two columns.
Q82. What does fr mean in CSS Grid?
Answer: fr means fraction of available space. 1fr 1fr creates two equal columns.
Q83. What is responsive design?
Answer: Responsive design makes websites adapt to different screen sizes like mobile, tablet, and desktop.
Q84. What are media queries?
Answer: Media queries apply CSS rules only under certain conditions, like screen width. Example: @media (max-width:
768px) { ... }.
Q85. What is mobile-first design?
Answer: Mobile-first means writing base CSS for mobile screens first, then adding larger-screen styles using min-width
media queries.
Q86. How do you make images responsive?
Answer: Use max-width:100%; height:auto; so images shrink within their container without distortion.
Q87. What is object-fit?
Answer: object-fit controls how replaced elements like images/videos fit inside their box. cover fills the box while
preserving aspect ratio.
Q88. What are pseudo-classes?
Prepared for Mohan Krishna Reddy | Page 7
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
Answer: Pseudo-classes style elements in a special state, such as :hover, :focus, :first-child, and :nth-child().
Q89. What are pseudo-elements?
Answer: Pseudo-elements style specific parts of an element, such as ::before, ::after, ::first-letter, and ::placeholder.
Q90. Difference between :hover and :focus?
Answer: :hover applies when mouse is over an element. :focus applies when an element is selected by keyboard, mouse,
or script.
Q91. What is transition in CSS?
Answer: transition creates smooth changes between property values, such as color or transform.
Q92. What is animation in CSS?
Answer: CSS animation uses @keyframes and animation properties to create repeated or timed visual changes.
Q93. Difference between transform and position movement?
Answer: transform visually moves/scales/rotates an element without affecting document flow. Position changes can
affect layout depending on type.
Q94. What is transform: translate()?
Answer: It moves an element visually on X/Y axes. It is often smoother for animations than changing top/left.
Q95. What is CSS variable?
Answer: CSS variables store reusable values. Example: :root { --main-color: blue; } then use color: var(--main-color).
Q96. What is the use of calc()?
Answer: calc() performs calculations in CSS, like width: calc(100% - 20px).
Q97. What is min(), max(), and clamp()?
Answer: They help create responsive values. clamp(min, preferred, max) keeps a value within a range.
Q98. What is overflow?
Answer: overflow controls what happens when content is bigger than its container: visible, hidden, scroll, or auto.
Q99. What is float?
Answer: float moves an element left or right, traditionally used for text wrapping. Modern layouts prefer Flexbox/Grid.
Q100. What is clear?
Answer: clear prevents an element from wrapping beside floated elements.
Q101. What is BEM naming?
Answer: BEM is a CSS naming convention: Block__Element--Modifier, helping keep class names organized.
Q102. What are CSS preprocessors?
Answer: Preprocessors like Sass add features such as variables, nesting, mixins, and functions, then compile to CSS.
Q103. What is a CSS reset or normalize?
Answer: It reduces browser default style differences so pages look more consistent across browsers.
Q104. How do you improve CSS performance?
Answer: Avoid overly complex selectors, reduce unused CSS, use external files, minify CSS, and prefer
transform/opacity for animations.
Q105. How do you make a button accessible with CSS?
Answer: Do not remove focus outline without replacement. Ensure good contrast, visible hover/focus states, and enough
clickable size.
Prepared for Mohan Krishna Reddy | Page 8
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
JavaScript Interview Questions and Answers
Q106. What is JavaScript?
Answer: JavaScript is a programming language used to make web pages interactive, handle logic, manipulate the DOM,
call APIs, and build frontend/backend apps.
Q107. Is JavaScript the same as Java?
Answer: No. JavaScript and Java are different languages with different syntax, runtime, and use cases.
Q108. Where can JavaScript run?
Answer: It runs in browsers and also on servers using [Link].
Q109. How do you add JavaScript to HTML?
Answer: Use <script src='[Link]'></script> for external JavaScript or write code inside a <script> tag.
Q110. What is the difference between var, let, and const?
Answer: var is function-scoped and can be redeclared. let is block-scoped and can be reassigned. const is block-scoped
and cannot be reassigned.
Q111. What is hoisting?
Answer: Hoisting means declarations are moved to the top of their scope during compilation. var is hoisted with
undefined; let/const are hoisted but not usable before declaration.
Q112. What are JavaScript data types?
Answer: Primitive types: string, number, boolean, null, undefined, bigint, symbol. Non-primitive type: object.
Q113. Difference between null and undefined?
Answer: undefined means a variable has been declared but not assigned. null is an intentional empty value.
Q114. Difference between == and ===?
Answer: == compares after type conversion. === compares value and type, so it is safer and preferred.
Q115. What is type coercion?
Answer: Type coercion is automatic conversion from one type to another, like '5' + 1 becoming '51'.
Q116. What is truthy and falsy?
Answer: Falsy values include false, 0, '', null, undefined, NaN. Most other values are truthy.
Q117. What is NaN?
Answer: NaN means Not-a-Number. It represents an invalid numeric result. Use [Link]() to check it safely.
Q118. What is a function?
Answer: A function is a reusable block of code that performs a task and can accept inputs and return output.
Q119. What is a function declaration?
Answer: A named function defined with function keyword, for example function add(a,b){ return a+b; }. It is hoisted.
Q120. What is a function expression?
Answer: A function stored in a variable, for example const add = function(a,b){ return a+b; }. It is not fully hoisted like
declaration.
Q121. What is an arrow function?
Answer: A shorter function syntax: const add = (a,b) => a+b. Arrow functions do not have their own this binding.
Q122. Difference between parameters and arguments?
Answer: Parameters are variable names in function definition. Arguments are actual values passed when calling the
function.
Q123. What is return in a function?
Answer: return sends a value back to the caller and stops function execution.
Q124. What is scope?
Answer: Scope defines where variables can be accessed. Common scopes are global, function, and block scope.
Prepared for Mohan Krishna Reddy | Page 9
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
Q125. What is closure?
Answer: A closure is when an inner function remembers variables from its outer function even after the outer function
has finished.
Q126. Give a simple closure example.
Answer: function counter(){ let count=0; return function(){ count++; return count; }; } The returned function remembers
count.
Q127. What is this keyword?
Answer: this refers to the object that is calling the function. Its value depends on how the function is called.
Q128. What is an object?
Answer: An object stores data as key-value pairs. Example: const user = { name: 'Mohan', age: 22 }.
Q129. How do you access object properties?
Answer: Use dot notation [Link] or bracket notation user['name']. Bracket notation is useful for dynamic keys.
Q130. What is an array?
Answer: An array stores multiple values in ordered positions. Example: const nums = [1,2,3].
Q131. Difference between push and pop?
Answer: push adds an item to the end of an array. pop removes the last item.
Q132. Difference between shift and unshift?
Answer: shift removes the first item. unshift adds an item to the beginning.
Q133. What is map()?
Answer: map() creates a new array by applying a function to each element.
Q134. What is filter()?
Answer: filter() creates a new array containing only elements that pass a condition.
Q135. What is reduce()?
Answer: reduce() combines array values into a single result such as sum, object, or grouped data.
Q136. Difference between map and forEach?
Answer: map returns a new array. forEach only runs a function for each item and returns undefined.
Q137. What is find()?
Answer: find() returns the first element that matches a condition, or undefined if none match.
Q138. What is includes()?
Answer: includes() checks whether an array or string contains a value and returns true or false.
Q139. What is destructuring?
Answer: Destructuring extracts values from arrays or objects into variables. Example: const {name} = user.
Q140. What is spread operator?
Answer: The spread operator ... expands arrays or objects. Example: const copy = [...arr].
Q141. What is rest parameter?
Answer: Rest parameter collects remaining function arguments into an array. Example: function sum(...nums) {}.
Q142. What is template literal?
Answer: Template literals use backticks and allow variables with ${}. Example: `Hello ${name}`.
Q143. What are default parameters?
Answer: Default parameters set default values when no argument is passed. Example: function greet(name='User') {}.
Q144. What is DOM?
Answer: DOM stands for Document Object Model. It represents the HTML page as a tree of objects that JavaScript can
read and change.
Q145. How do you select an element by id?
Answer: Use [Link]('id') or [Link]('#id').
Prepared for Mohan Krishna Reddy | Page 10
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
Q146. Difference between querySelector and querySelectorAll?
Answer: querySelector returns the first matching element. querySelectorAll returns all matching elements as a
NodeList.
Q147. How do you change text content?
Answer: Use [Link] = 'New text'. Use innerHTML only when you need HTML and can trust the content.
Q148. Difference between textContent and innerHTML?
Answer: textContent treats content as plain text. innerHTML parses content as HTML, which can cause XSS risk if
unsafe data is used.
Q149. How do you add a CSS class using JS?
Answer: Use [Link]('active'). You can also remove, toggle, or check classes with classList.
Q150. How do you create an element using JS?
Answer: Use [Link]('div'), set its content or attributes, then append it to the page.
Q151. What is an event?
Answer: An event is an action such as click, submit, keydown, input, or page load that JavaScript can respond to.
Q152. How do you add an event listener?
Answer: Use [Link]('click', function(){ ... });.
Q153. What is event bubbling?
Answer: Event bubbling means an event starts at the target element and moves upward through its parent elements.
Q154. What is event delegation?
Answer: Event delegation attaches one listener to a parent and handles events from child elements using [Link].
Q155. What is preventDefault()?
Answer: preventDefault() stops the browser's default action, such as form submission or link navigation.
Q156. What is stopPropagation()?
Answer: stopPropagation() stops an event from bubbling up to parent elements.
Q157. What is synchronous JavaScript?
Answer: Synchronous code runs line by line, and each line waits for the previous one to finish.
Q158. What is asynchronous JavaScript?
Answer: Asynchronous code allows tasks like API calls or timers to run without blocking the rest of the program.
Q159. What is callback?
Answer: A callback is a function passed as an argument to another function and executed later.
Q160. What is callback hell?
Answer: Callback hell happens when many nested callbacks make code hard to read and maintain.
Q161. What is a Promise?
Answer: A Promise represents a future result. It can be pending, fulfilled, or rejected.
Q162. What are then, catch, and finally?
Answer: then handles success, catch handles errors, and finally runs after success or failure.
Q163. What is async/await?
Answer: async/await is syntax for writing Promise-based asynchronous code in a cleaner, more readable way.
Q164. What is fetch()?
Answer: fetch() is a browser API used to make HTTP requests and get data from APIs.
Q165. How do you handle API errors with fetch?
Answer: Check [Link] before parsing JSON and use try/catch around await fetch().
Q166. What is JSON?
Answer: JSON is a text format for data exchange. It uses key-value pairs and arrays, commonly used in APIs.
Prepared for Mohan Krishna Reddy | Page 11
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
Q167. Difference between [Link] and [Link]?
Answer: [Link] converts JavaScript object to JSON string. [Link] converts JSON string to JavaScript object.
Q168. What is localStorage?
Answer: localStorage stores key-value data in the browser with no automatic expiry. Data remains after closing the
browser.
Q169. What is sessionStorage?
Answer: sessionStorage stores key-value data only for the current tab/session. It is cleared when the tab closes.
Q170. Difference between localStorage and cookies?
Answer: localStorage is mainly for client-side storage. Cookies are sent with HTTP requests and can have expiry/security
flags.
Q171. What is try/catch?
Answer: try/catch handles runtime errors. Code inside try runs, and catch handles errors if they occur.
Q172. What is throw?
Answer: throw creates a custom error. Example: throw new Error('Invalid input').
Q173. What is strict mode?
Answer: 'use strict' enables stricter JavaScript rules and helps catch common mistakes.
Q174. What is event loop?
Answer: The event loop manages execution of synchronous code, callbacks, microtasks, and asynchronous tasks in
JavaScript.
Q175. Difference between setTimeout and setInterval?
Answer: setTimeout runs once after a delay. setInterval runs repeatedly after every delay until cleared.
Q176. What is debouncing?
Answer: Debouncing delays function execution until the user stops triggering an event for a specified time, useful in
search inputs.
Q177. What is throttling?
Answer: Throttling limits a function to run at most once in a specified time interval, useful for scroll or resize events.
Q178. What is shallow copy?
Answer: A shallow copy copies top-level values but nested objects still share references.
Q179. What is deep copy?
Answer: A deep copy copies all nested values so changes do not affect the original object.
Q180. What is optional chaining?
Answer: Optional chaining ?. safely accesses nested properties without throwing errors if a value is null or undefined.
Q181. What is nullish coalescing?
Answer: ?? returns the right-side value only when the left-side value is null or undefined.
Q182. Difference between && and ||?
Answer: && returns the first falsy value or last value. || returns the first truthy value or last value.
Q183. What are modules in JavaScript?
Answer: Modules allow code to be split into files using export and import.
Q184. What is the difference between named export and default export?
Answer: Named exports are imported by exact name. Default export can be imported with any name.
Q185. What is XSS?
Answer: XSS is Cross-Site Scripting, where attackers inject malicious scripts into a page. Avoid using unsafe innerHTML
and sanitize input.
Q186. How do you validate a form using JavaScript?
Prepared for Mohan Krishna Reddy | Page 12
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
Answer: Read input values, check conditions like empty/email/password length, show errors, and prevent form
submission if invalid.
Q187. How do you reverse a string in JavaScript?
Answer: Use [Link]('').reverse().join(''). For interviews, explain that this works for simple strings.
Q188. How do you check if a number is even?
Answer: Use number % 2 === 0. The % operator gives the remainder.
Q189. How do you remove duplicates from an array?
Answer: Use [...new Set(arr)] for primitive values like numbers or strings.
Q190. How do you find the maximum number in an array?
Answer: Use [Link](...arr), or loop through the array and track the largest value.
Q191. How do you count characters in a string?
Answer: Loop through the string and store counts in an object, or use reduce on split characters.
Q192. How do you check a palindrome?
Answer: Convert to lowercase, remove spaces if needed, reverse the string, and compare with the original.
Q193. How do you sort an array of numbers?
Answer: Use [Link]((a,b) => a-b) for ascending order. Without compare function, sort treats values as strings.
Q194. How do you merge two arrays?
Answer: Use [...arr1, ...arr2] or [Link](arr2).
Q195. How do you clone an object?
Answer: For shallow clone, use {...obj} or [Link]({}, obj). For nested objects, use structuredClone(obj) if supported.
Q196. What is a memory leak in JavaScript?
Answer: A memory leak happens when unused objects are still referenced, preventing garbage collection.
Q197. What is garbage collection?
Answer: Garbage collection automatically frees memory used by objects that are no longer reachable.
Q198. What is the difference between frontend and backend JavaScript?
Answer: Frontend JS runs in the browser and handles UI. Backend JS runs in [Link] and handles server logic, APIs,
files, and databases.
JavaScript Coding Questions
Q199. Write a function to check whether a string is palindrome.
Answer:
function isPalindrome(str) { const clean = [Link]().replace(/\s+/g, ''); return clean ===
[Link]('').reverse().join(''); }
Q200. Write a function to remove duplicates from an array.
Answer:
function removeDuplicates(arr) { return [...new Set(arr)]; }
Q201. Write a function to find factorial of a number.
Answer:
function factorial(n) { if (n < 0) return null; let result = 1; for (let i = 2; i <= n; i++) result *= i; return result; }
Q202. Write a function to find the largest number in an array.
Answer:
function largest(arr) { return [Link](...arr); }
Q203. Write a function to count vowels in a string.
Prepared for Mohan Krishna Reddy | Page 13
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
Answer:
function countVowels(str) { return ([Link](/[aeiou]/gi) || []).length; }
Q204. Write a function to check prime number.
Answer:
function isPrime(n) { if (n <= 1) return false; for (let i = 2; i <= [Link](n); i++) { if (n % i === 0) return false; } return true; }
Q205. Write a function to reverse words in a sentence.
Answer:
function reverseWords(sentence) { return [Link](' ').reverse().join(' '); }
Q206. Write a function to sum array values.
Answer:
function sumArray(arr) { return [Link]((sum, num) => sum + num, 0); }
Q207. Write a function to find frequency of array items.
Answer:
function frequency(arr) { return [Link]((acc, item) => { acc[item] = (acc[item] || 0) + 1; return acc; }, {}); }
Q208. Write a simple debounce function.
Answer:
function debounce(fn, delay) { let timer; return function(...args) { clearTimeout(timer); timer = setTimeout(() =>
[Link](this, args), delay); }; }
Prepared for Mohan Krishna Reddy | Page 14
HTML, CSS & JavaScript Interview Q&A - Fresher Preparation
Rapid Revision Before Interview
HTML interview focus: Structure, semantic tags, forms, tables, accessibility, meta tags, script/css linking.
CSS interview focus: Box model, specificity, Flexbox, Grid, responsive design, positioning, pseudo-classes, transitions.
JavaScript interview focus: Variables, data types, functions, arrays, objects, DOM, events, async/await, fetch, storage,
common coding tasks.
Best fresher answer style: Define the concept, give one small example, then explain where you used it or where it is
useful.
When you do not know: Say: I have basic understanding, but I have not used it deeply. I can explain what I know and I
am ready to learn it.
30-Minute Last-Minute Plan
First 10 minutes: Revise HTML document structure, semantic tags, forms, and accessibility basics.
Next 10 minutes: Revise CSS box model, specificity, Flexbox, Grid, responsive design, and positioning.
Last 10 minutes: Revise JavaScript variables, functions, arrays, DOM, events, async/await, fetch, and 5 coding
questions.
Safe Fresher Closing Answer
Use this if you get a difficult question: "I understand the basic concept, but I have not used it deeply in a real project yet.
I can explain the foundation and I am ready to learn and apply it practically."
Prepared for Mohan Krishna Reddy | Page 15