Data Structures and Algorithms

Frontend Interview Guide: HTML, CSS, and JavaScript Questions You Should Expect

Introduction

Preparing for a frontend developer interview can feel overwhelming, given the breadth of technologies and concepts involved. However, focusing on the core trio—HTML, CSS, and JavaScript—can set you up for success. These technologies form the foundation of web development, enabling you to create structured, styled, and interactive web pages. This comprehensive guide provides a curated list of interview questions and detailed answers, categorized by difficulty (basic, intermediate, and advanced), to help you ace your frontend interview.

And if you’re serious about staying ahead, sign up here to get free frontend courses and latest updates—trusted by thousands of devs prepping for interviews.

HTML Interview Questions

HTML (HyperText Markup Language) is the backbone of every web page, defining its structure and content. Interviewers often test your understanding of HTML’s syntax, semantic elements, and modern features.

Basic HTML Questions

  1. What is HTML?
    HTML stands for HyperText Markup Language, the standard language for creating web pages. It uses tags to structure content, such as headings, paragraphs, images, and links, enabling browsers to render web pages correctly.

  2. What are the basic structure elements of an HTML document?
    An HTML document’s structure includes:

    • <!DOCTYPE html>: Declares the document as HTML5.
    • <html>: The root element.
    • <head>: Contains metadata (e.g., title, meta tags).
    • <title>: Sets the page title displayed in the browser.
    • <body>: Holds visible content like text, images, and links.
      Example:
				
					<!DOCTYPE html>
<html>
<head>
  <title>My Page</title>
</head>
<body>
  <h1>Welcome</h1>
</body>
</html>

				
			

3. What are semantic HTML elements?
Semantic elements clearly describe their purpose, improving accessibility, SEO, and code readability. Examples include <header>, <nav>, <main>, <article>, <section>, and <footer>. For instance, <nav> indicates navigation links, unlike a generic <div>.


4. What is the difference between <div> and <span>?

    • <div>: A block-level element that takes the full width and starts on a new line, used for grouping content.
    • <span>: An inline element that only takes the space of its content, used for styling small text segments.
      Example: <div> for a section, <span> for a highlighted word.
  1. How do you create a link in HTML?

Use the <a> tag with the href attribute to specify the URL.

				
					 <a href="https://example.com" target="_blank" rel="noopener">Visit Example</a>

				
			

Intermediate HTML Questions

  1. What is the purpose of the <meta> tag?
    The <meta> tag provides metadata about the document, such as character encoding, viewport settings, or SEO details (e.g., description, keywords).
    Example:
				
					 <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

				
			

2. How do you create a table in HTML?
Use <table>, <tr> (table row), <th> (table header), and <td> (table data).

				
					Example:

 <table>
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>John</td>
    <td>25</td>
  </tr>
</table>



				
			

3. What are HTML5 form elements?
HTML5 introduced form elements like <input type=”email”>, <input type=”date”>, <input type=”number”>, <input type=”range”>, and <input type=”search”>, which enhance user experience and provide built-in validation.
Example: <input type=”email” required> ensures a valid email format.

4. What is the difference between <canvas> and <svg>?

  • <canvas>: A bitmap-based element for drawing graphics via JavaScript, ideal for dynamic visuals but not scalable.
  • <svg>: A vector-based format that scales without quality loss, stylable with CSS, and suitable for static or animated graphics.
What is the difference between _canvas_ and _svg

5. What are void elements in HTML?
Void elements are self-closing and do not require a closing tag. Examples include <br>, <img>, <input>, and <hr>.

				
					 <img decoding="async" src="image.jpg" alt="Description">
				
			

Advanced HTML Questions

  1. What are web workers?

Web workers run scripts in a separate thread, preventing UI blocking during heavy computations. They’re ideal for tasks like data processing.
Example:

				
					 // worker.js
self.onmessage = function(e) {
  self.postMessage(e.data * 2);
};

				
			
  1. What is the purpose of the <template> tag?

The <template> tag holds HTML fragments that can be cloned and inserted via JavaScript, useful for reusable components.
Example:

				
					 <template id="my-template">
  <div>Hello, World!</div>
</template>

				
			
  1. How do you handle cross-origin resource sharing (CORS) in HTML?


CORS is managed server-side with headers like Access-Control-Allow-Origin. In HTML, use the crossorigin attribute on <img>, <script>, or <link> to specify CORS policies.
Example:

				
					<script src="https://api.example.com" crossorigin="anonymous"></script>
				
			
3. How do you handle cross-origin resource sharing (CORS) in HTML
  1. What is the difference between progressive enhancement and graceful degradation?

Progressive Enhancement: Build a basic, functional page and add enhancements for advanced browsers.

Graceful Degradation: Start with a feature-rich page and ensure it works with reduced functionality in older browsers.

  1. What is shadow DOM, and how does it work?


Shadow DOM encapsulates a portion of the DOM, allowing scoped CSS and hidden elements. It’s used in web components for reusable, isolated components.
Example:

const elem = document.querySelector(‘#my-element’);

const shadow = elem.attachShadow({ mode: ‘open’ });

shadow.innerHTML = ‘<p>Shadow Content</p>’;

CSS Interview Questions

CSS (Cascading Style Sheets) controls the visual presentation and layout of web pages. Interviewers test your ability to style elements, create responsive designs, and optimize performance.

Basic CSS Questions

  1. What is CSS?
    CSS is a stylesheet language used to style and layout HTML elements, controlling aspects like colors, fonts, and positioning.

  2. What are the different ways to include CSS in an HTML document?

    • Inline: Using the style attribute (e.g., <p style=”color: blue;”>Text</p>).
    • Internal: Using a <style> tag in the <head>.
    • External: Linking an external .css file via <link>.
      Example: <link rel=”stylesheet” href=”styles.css”>
  3. What is the CSS Box Model?
    The Box Model defines an element’s dimensions: content, padding, border, and margin.

    • Content: The inner content (text, images).
    • Padding: Space between content and border.
    • Border: Surrounds padding.
    • Margin: Space outside the border.
  4. What are CSS selectors?
    Selectors target HTML elements for styling. Types include:

    • Element (e.g., p),
    • Class (e.g., .class),
    • ID (e.g., #id),
    • Attribute (e.g., [type=”text”]).
  5. What is the difference between id and class in CSS?

    • id: Unique identifier for a single element (e.g., #header).
    • class: Reusable identifier for multiple elements (e.g., .button).
What is the difference between id and class in CSS

Intermediate CSS Questions

  1. What is the difference between margin and padding?

    • Margin: External space outside the border.
    • Padding: Internal space between content and border.
      Example: margin: 10px; adds space outside, padding: 10px; adds space inside.
  2. What are CSS pseudo-classes?
    Pseudo-classes define an element’s state, like :hover, :active, :focus, or :first-child.
    Example: a:hover { color: red; } changes link color on hover.

How do you create a responsive design using CSS?
Use media queries to apply styles based on device characteristics (e.g., screen width).
Example:

				
					 @media (max-width: 768px) {
  .container { flex-direction: column; }
}

				
			


3. What is the z-index property?
z-index controls the stacking order of positioned elements. Higher values appear in front.
Example: div { position: absolute; z-index: 10; }

4. What is the difference between display: flex and display: grid?

    • flex: One-dimensional layout for rows or columns.
    • grid: Two-dimensional layout for rows and columns.

Advanced CSS Questions

What are CSS variables?
CSS variables (custom properties) store reusable values.
Example:

				
					 :root { --primary-color: #007bff; }
.button { background-color: var(--primary-color); }

				
			
  1. What is the purpose of the position property?
    The position property defines element positioning:
  • static: Default, follows normal flow.
  • relative: Offset from its normal position.
  • absolute: Positioned relative to the nearest positioned ancestor.
  • fixed: Fixed relative to the viewport.
  • sticky: Toggles between relative and fixed based on scroll.

2. How do you create animations in CSS?
Use @keyframes to define animation steps and apply them with the animation property.

				
					 @keyframes slideIn {
  from { transform: translateX(-100%); }
  to { transform: translateX(0); }
}
.element { animation: slideIn 1s ease-in; }

				
			


3. What is the difference between transform and transition?

transform: Applies 2D/3D transformations (e.g., rotate, scale).

transition: Controls the timing of property changes (e.g., color change on hover).
Example:

				
					transform: scale(1.2); transition: transform 0.3s ease;

				
			


4. What is the flex-wrap property?
flex-wrap determines whether flex items wrap to a new line if they exceed the container’s width. Values: nowrap, wrap, wrap-reverse.
Example:

				
					.container { display: flex; flex-wrap: wrap; }

				
			

JavaScript Interview Questions

JavaScript adds interactivity and dynamic behavior to web pages. Interviewers often test your understanding of its core concepts, asynchronous programming, and advanced features.

Basic JavaScript Questions

  1. What is JavaScript?
    JavaScript is a high-level, interpreted programming language that enables dynamic and interactive web content.

     

  2. What are the different data types in JavaScript?
    • Primitive: String, Number, Boolean, Null, Undefined, Symbol.
    • Non-primitive: Object, Array, Function.
  3. What is the difference between let, const, and var?
    • var: Function-scoped, can be redeclared and reassigned.
    • let: Block-scoped, can be reassigned but not redeclared in the same scope.
    • const: Block-scoped, cannot be reassigned or redeclared.
  4. What is the DOM?
    The Document Object Model (DOM) is a programming interface for HTML/XML documents, representing the page as a tree of objects that JavaScript can manipulate.
  5. What is the difference between == and ===?
    • ==: Checks equality after type coercion (e.g., “5” == 5 is true).
    • ===: Checks equality without type coercion (e.g., “5” === 5 is false).

Intermediate JavaScript Questions

  • What are closures in JavaScript?

A closure is a function that retains access to its outer scope’s variables even after the outer function has returned.
Example:

				
					 function outer() {
  let count = 0;
  return function inner() {
    return count++;
  };
}
const counter = outer();
console.log(counter()); // 0
console.log(counter()); // 1

				
			


2. What is the this keyword in JavaScript?
this refers to the current execution context, determined by how a function is called (e.g., global object, object method, or constructor).

3. What are callbacks in JavaScript?
A callback is a function passed as an argument to another function, executed after a specific task.
Example:

				
					 setTimeout(() => console.log("Delayed"), 1000);

				
			


4. How do you handle asynchronous operations in JavaScript?

Use callbacks, promises, or async/await.
Example (async/await):

				
					 async function fetchData() {
  const response = await fetch('https://api.example.com/data');
  return response.json();
}

				
			

5. What is the difference between forEach and map?

forEach: Executes a function for each array element, no return value.

map: Creates a new array with the results of calling a function on each element.
Example:

				
					const arr = [1, 2, 3];
arr.forEach(x => console.log(x)); // Logs 1, 2, 3
const doubled = arr.map(x => x * 2); // Returns [2, 4, 6]

				
			

Advanced JavaScript Questions

  1. What are promises in JavaScript?
    Promises represent the eventual completion (or failure) of an asynchronous operation, with states: pending, fulfilled, or rejected.
    Example:
				
					 const promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Success"), 1000);
});
promise.then(result => console.log(result)); // Logs "Success"

				
			


2. What is the event loop in JavaScript?

The event loop manages asynchronous operations by processing the call stack and task queue, ensuring non-blocking behavior.

3. What are generators in JavaScript?
Generators are functions that can pause and resume execution, returning an iterator.
Example:

				
					
 function* generator() {
  yield 1;
  yield 2;
}
const gen = generator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

				
			


4. What is the difference between call, apply, and bind?

call: Invokes a function with a specified this and individual arguments.

apply: Invokes a function with a specified this and an array of arguments.

bind: Returns a new function with a specified this and initial arguments.
Example:

				
					const obj = { name: "John" };
function greet(greeting) { console.log(`${greeting}, ${this.name}`); }
greet.call(obj, "Hello"); // Hello, John
greet.apply(obj, ["Hi"]); // Hi, John
const boundGreet = greet.bind(obj, "Hey");
boundGreet(); // Hey, John



				
			


5. What is the purpose of the prototype property in JavaScript?
The prototype property allows adding methods/properties to a constructor’s prototype, shared by all instances.
Example:

				
					const obj = { name: "John" };
function greet(greeting) { console.log(`${greeting}, ${this.name}`); }
greet.call(obj, "Hello"); // Hello, John
greet.apply(obj, ["Hi"]); // Hi, John
const boundGreet = greet.bind(obj, "Hey");
boundGreet(); // Hey, John



				
			
Execution Context in JavaScript
Call Stack

What is the difference between scope and execution context in JavaScript?

Scope defines where variables are accessible. Execution context defines how and when code is run.

Yes, but they live in the Temporal Dead Zone and throw a ReferenceError if accessed before declaration.

How are closures used in real-world applications?

Closures are widely used in React hooks, private state management, and event listeners.

No. Arrow functions are not hoisted like function declarations—they’re treated like expressions.

Why should I avoid using var in modern JavaScript?

var has function scope and allows hoisting with undefined, which often leads to bugs. Prefer let or const.

DSA, High & Low Level System Designs

Buy for 60% OFF
₹25,000.00 ₹9,999.00

Accelerate your Path to a Product based Career

Boost your career or get hired at top product-based companies by joining our expertly crafted courses. Gain practical skills and real-world knowledge to help you succeed.

Reach Out Now

If you have any queries, please fill out this form. We will surely reach out to you.

Contact Email

Reach us at the following email address.

Phone Number

You can reach us by phone as well.

+91-97737 28034

Our Location

Rohini, Sector-3, Delhi-110085

WhatsApp Icon

Master Your Interviews with Our Free Roadmap!

Hi Instagram Fam!
Get a FREE Cheat Sheet on System Design.

Hi LinkedIn Fam!
Get a FREE Cheat Sheet on System Design

Loved Our YouTube Videos? Get a FREE Cheat Sheet on System Design.