Top Front-End Interview Questions (HTML, CSS, JS)

Moizna Zaheer
16 min readApr 2, 2024

--

Are you ready to embark on a journey toward front-end excellence? Dive into our collection of 30 essential interview questions designed to test your knowledge, spark your curiosity, and boost your confidence.

Q1 What is HTML?

HTML, which stands for Hypertext Markup Language, is the standard language used to create and design web pages and web applications. It’s not a programming language in the traditional sense because it doesn’t contain logic or algorithms to manipulate data. Instead, it’s a markup language that tells web browsers how to structure and present content on web pages. HTML does this by wrapping content within various tags, each serving a different purpose. For example, there are tags for headings, paragraphs, links, images, and many other elements.

Q2 Why do we use HTML?

We use HTML for several key reasons:

  1. Structure and Organization: HTML allows developers to structure and organize web content. By using different tags, you can define various content types like headings, paragraphs, lists, links, and more, making the content more accessible and easier to understand for users.
  2. Web Browser Compatibility: HTML is the universal language understood by all web browsers. Whether you’re using Chrome, Firefox, Safari, or any other browser, HTML ensures your web content can be displayed correctly.
  3. Foundation of Web Development: HTML forms the backbone of web development alongside CSS (Cascading Style Sheets) and JavaScript. While HTML structures the content, CSS is used for styling (e.g., colours, fonts, layout), and JavaScript adds interactivity. Together, these technologies allow for the creation of complex, dynamic, and aesthetically pleasing web pages.
  4. Accessibility: Proper use of HTML can make websites more accessible to people with disabilities. Using the correct tags and attributes, developers can ensure that screen readers and other assistive technologies can effectively interpret and navigate through the content.
  5. SEO Friendly: Search engines like Google use web crawlers to index the content of web pages. Well-structured HTML helps these crawlers understand the content of your pages better, which can improve your site’s search engine ranking. For instance, using the correct heading tags (h1, h2, etc.) helps indicate the hierarchy and importance of content.
  6. Ease of Learning: Compared to other web technologies, HTML is relatively easy to learn and understand, making it a great starting point for anyone interested in web development. Its straightforward syntax and wide range of resources for learning contribute to its accessibility for beginners.

Q3 What is HTTP?

HTTP, or Hypertext Transfer Protocol, is the foundation of data communication on the World Wide Web. It’s an application layer protocol that enables the transfer of hypertext documents, typically in the form of web pages, between clients (such as web browsers) and servers. Overall, HTTP facilitates the retrieval and presentation of web content, forming the backbone of communication on the internet.

Q4 What is HTTPS?

HTTPS (Hypertext Transfer Protocol Secure) is a secure version of HTTP, that encrypts data exchanged between a client and server. It employs SSL/TLS protocols to ensure the confidentiality and integrity of transmitted information. Websites using HTTPS display a padlock icon, assuring users of a secure connection. HTTPS is crucial for protecting sensitive data, like login credentials and payment information, from interception by malicious parties. Its use is widespread in e-commerce, online banking, and other secure web applications.

Q5 What is the difference between HTTP and HTTPS?

The main difference between HTTP (Hypertext Transfer Protocol) and HTTPS (Hypertext Transfer Protocol Secure) lies in security. HTTP operates over plain text, transmitting data without encryption, making it vulnerable to interception. On the other hand, HTTPS encrypts data using SSL/TLS protocols, ensuring secure communication between clients and servers. Websites using HTTPS display a padlock icon, while HTTP sites lack this indicator. HTTPS is essential for protecting sensitive information, such as login credentials and payment details, from unauthorized access, making it the preferred choice for secure web browsing, particularly in e-commerce and online banking.

Q6 When a website is loaded what is the order of content to load?

When a website loads, the browser follows a sequence: it resolves the domain name via DNS, sends an HTTP/HTTPS request to the server, retrieves and processes HTML, CSS, and JavaScript files, renders the webpage based on these resources, and finally loads additional assets like images and videos, completing the display of the webpage.

Q7 What is the difference between an element and a tag in HTML?

In HTML, a tag is the markup syntax used to define the structure and elements within a document, enclosed within angle brackets, such as `<p>` for a paragraph or `<img>` for an image. An element consists of both the opening tag, content, and closing tag together, defining a complete unit within the document, like `<p>Hello</p>` for a paragraph element containing the text “Hello.” In essence, tags are the building blocks used to create elements within an HTML document.

Q8 What are semantic tags?

Semantic tags in HTML are elements that provide meaning or context to the content they enclose, beyond just formatting or styling. They describe the purpose or role of the content, making it more accessible to users and search engines. Some common semantic tags in HTML5 include:

  • `<header>`: Defines a header section of a document or a section within a document.
  • `<nav>`: Indicates a navigation section, typically containing links to other pages or sections of the website.
  • `<main>`: Specifies the main content of the document, excluding headers, footers, and navigation.
  • `<article>`: Represents an independent, self-contained piece of content, such as a blog post, article, or news story.
  • `<section>`: Defines a thematic grouping of content within a document, often used to divide content into chapters, topics, or related sections.
  • `<aside>`: Indicates content that is tangentially related to the main content, such as sidebars, pull quotes, or advertisements.
  • `<footer>`: Specifies a footer section of a document or a section within a document, typically containing copyright information, contact details, or related links.

Using semantic tags not only improves the structure and readability of HTML documents but also enhances accessibility and search engine optimization (SEO) by providing clearer context for content.

Q9 What is the difference between section and div?

`<section>` is a semantic HTML element used for grouping related content thematically, aiding accessibility and SEO. `<div>` is a generic container for grouping elements, primarily for styling purposes, lacking specific semantic meaning. While both help organize content, `<section>` provides clearer context and meaning to the enclosed content, making it preferable for structuring web documents. `<section>` is best suited for defining distinct sections of a webpage, while `<div>` is more flexible and can be used for various layout and design needs. Using `<section>` enhances the structure and semantics of HTML documents, contributing to better organization and understanding of content.

Q10 What are self-closing tags?

Self-closing tags, also known as void or empty elements, are HTML elements that don’t require a closing tag because they don’t contain any content. Instead, they represent standalone elements. These tags are terminated with a slash before the closing angle bracket. Examples include `<img>`, `<br>`, and `<input>`. They are used to insert images, line breaks, and input fields, respectively, into the HTML document without needing additional closing tags.

Q11 Why do we use <!DOCTYPE> at the top of the HTML file?

The `<!DOCTYPE>` declaration specifies the version and type of HTML used in a document. It ensures consistent rendering across different browsers by triggering standards mode. This declaration assists browsers in parsing the HTML correctly, preventing rendering inconsistencies. Validators use it to check the document’s compliance with HTML standards, identifying syntax errors. Including the `<!DOCTYPE>` declaration at the top of an HTML file ensures compatibility and future-proofing with evolving web standards.

Q12 What are attributes in HTML and why do we use attributes?

Attributes in HTML provide additional information or functionality to HTML elements. For instance, the “class” attribute allows styling elements with CSS: `<div class=”container”>`. Attributes like “src” define the source of media elements: `<img src=”image.jpg” alt=”Description”>`. Accessibility is improved with attributes like “alt” for alternative text: `<img src=”image.jpg” alt=”Description”>`. Interactivity is achieved using attributes like “href” for hyperlinks: `<a href=”https://example.com">Link</a>`. Form validation utilizes attributes like “required”: `<input type=”text” name=”username” required>`. Attributes enhance HTML elements’ functionality, accessibility, and customization in web development.

Q13 What are meta tags? why do we use them?

Meta tags are HTML elements that provide metadata about a webpage, offering information to browsers, search engines, and other web services. They are placed within the head section of an HTML document and are not displayed on the webpage itself. Meta tags serve various purposes, including:

  • SEO (Search Engine Optimization): Meta tags provide information such as page titles, descriptions, and keywords, which help search engines understand the content and relevance of the webpage. This can impact the web page’s visibility and ranking in search engine results.
  • Social Media Sharing: Meta tags like “og: title “ and “og: image” are used to control how the webpage appears when shared on social media platforms like Facebook, Twitter, and LinkedIn. They specify the title, description, and image to be displayed in social media previews.
  • Viewport Configuration: The “viewport” meta tag enables developers to control the layout and scaling of the webpage on mobile devices, ensuring a consistent and optimized user experience across different screen sizes.
  • Character Encoding: The “charset” meta tag specifies the character encoding used in the webpage, ensuring the proper display of special characters and symbols.
  • Browser Compatibility: Certain meta tags provide instructions to web browsers regarding compatibility modes, caching behaviour, and refresh intervals, ensuring consistent rendering and performance across different browsers.

Overall, meta tags play a crucial role in providing essential information about webpages to browsers, search engines, and other web services, enhancing their visibility, accessibility, and user experience.

Q14 What is difference in inline and block element?

1. Inline Elements:

  • Inline elements do not start on a new line and only take up as much width as necessary.
  • They allow other elements to sit beside them on the same line.
  • Examples include `<span>`, `<a>`, `<strong>`, `<em>`, `<img>`, and `<input>`.
  • They are typically used for small chunks of content within a larger block of text.

2. Block Elements:

  • Block elements always start on a new line and occupy the full width available.
  • They create a block-level box that separates it from adjacent content.
  • Examples include `<div>`, `<p>`, `<h1>` to `<h6>`, `<ul>`, `<ol>`, `<li>`, `<table>`, and `<form>`.
  • They are commonly used for larger structures and to group related content together.

In summary, inline elements flow within the text, allowing other elements to be alongside them, while block elements create distinct blocks of content, starting on a new line and spanning the full width available.

Q15 What is the width of the block element?

A block-level element by default occupies the full width available within its containing parent element. It starts on a new line and creates a block-level box that separates it from adjacent content. The width of a block element can be adjusted using CSS properties like `width`, `max-width`, or `min-width`. These properties allow developers to specify the width in pixels, percentages, or other units.

Q16 What is difference between SVG and Canvas?

  1. Graphics Type:
    — SVG: Uses vector graphics, ideal for scalable designs like logos.
    — Canvas: Uses pixels (bitmap), great for detailed and dynamic images.
  2. Manipulation:
    — SVG: Easily manipulated with CSS and JavaScript because it’s part of the HTML DOM.
    — Canvas: Requires redrawing for changes; less straightforward to manipulate once drawn.
  3. Performance:
    — SVG: Can slow down with many elements since each is part of the DOM.
    — Canvas: Handles dynamic, complex animations well, as it doesn’t rely on the DOM.
  4. Use Cases:
    — SVG: Perfect for scalable graphics, icons, and simple animations.
    — Canvas: Better for intensive graphics work like games and complex animations.
  5. Interactivity:
    — SVG: Naturally interactive, easy to attach events and modify.
    — Canvas: Interactivity is possible but requires more work to manage and track.
  6. Scaling:
    — SVG: Scales without losing quality.
    — Canvas: Scaling affects quality, as it’s pixel-based.

Q17 What is CSS and what is meant by cascading?

In CSS, “CSS” stands for “Cascading Style Sheets.”Cascading” refers to the way styles are applied to elements. Styles can come from different sources and can overlap. When styles conflict, the browser resolves them based on rules.

Q18 What are cascade rules?

The cascade rule in CSS determines how conflicting styles are resolved when multiple styles are applied to an HTML element. It’s a fundamental concept that ensures styles are blended or “cascaded” together in a predictable manner. The cascade rule operates on three main factors:

  • Specificity: A scoring system that determines which style rule has precedence based on the specificity of its selector. Inline styles have the highest specificity, followed by IDs, classes and pseudo-classes, and finally, element and pseudo-element selectors. A higher specificity score means the style rule takes precedence.
  • Inheritance: Certain CSS properties are inherited from parent elements unless overridden. If a property is not set on an element, but is set on its parent, the child element can inherit this property.
  • Source Order: If two style rules have the same specificity, the one that comes last in the CSS code takes precedence. This means that the order of CSS rules matters, and the last rule defined or loaded is applied.

The cascade combines these factors to ensure that the most specific and recently declared style is applied to an element, allowing for detailed and nuanced styling of web pages.

Q19 What is a selector in CSS?

A selector in CSS is a pattern used to select the HTML elements you want to style. Selectors enable you to target specific elements on a webpage to apply styles to them. There are several types of CSS selectors, each serving different purposes:

  • Type Selector (Element Selector): Targets HTML elements by their type, such as `p`, `div`, `h1`, etc. For example, `p {colour: blue; }` changes the text colour of all `<p>` elements to blue.
  • Class Selector: Targets elements by their class attribute. It’s denoted by a period (`.`) followed by the class name. For instance, `.menu { font-size: 14px; }` applies a font size to all elements with a class of “menu”.
  • ID Selector: Targets an element based on its unique ID attribute. It’s denoted by a hash (`#`) followed by the ID value. For example, `#header {background-colour: yellow; }` applies a background colour to the element with an ID of “header”.
  • Attribute Selector: Targets elements based on the presence or value of a given attribute. For instance, `input[type=”text”] {border-colour: red; }` targets all text input fields.
  • Pseudo-class Selector: Targets elements in a specific state, such as `: hover` or `: focus`. For example, `a: hover {colour: red; }` changes the colour of links when the mouse hovers over them.
  • Pseudo-element Selector Targets specific parts of an element, such as `:: before` or `:: after`. For example, `p::first-line { font-weight: bold; }` makes the first line of every paragraph bold.
  • Universal Selector (`*`): Targets all elements on a webpage.
  • Combinators: Combine simple selectors in various ways (like descendants, children, adjacent siblings) to target specific elements. For example, `div > p` selects all `<p>` elements that are direct children of `<div>` elements.

Selectors are fundamental to CSS, as they define which elements are affected by the declared styles. The usage of CSS selectors often depends on the specific needs of a project, the complexity of the webpage, and the practices of the developer.

Q20 What is the order of priority among CSS selectors?

The order of priority among CSS selectors is determined by specificity. Specificity is a way of calculating which CSS rule has precedence over others if multiple rules could apply to the same element. The specificity hierarchy from highest to lowest priority is as follows:

  • Inline Styles: An inline style applied directly within an HTML element using the `style` attribute has the highest specificity. For example, `<div style=”colour: red;”>`.
  • IDs: An ID selector has the next highest specificity. Each element can have only one ID, and each page can have only one element with that ID. The ID selector is denoted by a hash (`#`) prefix.
  • Classes, Attributes, and Pseudo-classes: These selectors have equal specificity and are next in the hierarchy. Classes are denoted by a dot (`.`), attributes by square brackets (`[]`), and pseudo-classes with a colon (`:`) prefix.
  • Elements and Pseudo-elements: The lowest specificity is for element (type) selectors and pseudo-elements. Pseudo-elements are prefixed with two colons (`::`).

When calculating specificity:

  • If two selectors apply to the same element, the one with higher specificity wins.
  • When selectors have equal specificity, the latest rule in the CSS is applied.
  • Specificity is calculated on a per-selector basis, not on the entire rule. The specificity scores are not added across selectors but are compared for each selector individually.

Understanding specificity is crucial for effectively writing CSS and troubleshooting style conflicts.

Q21 Why do we use ‘!improtant’ keyword in CSS?

The `!important` keyword in CSS is used to give a style declaration higher precedence over conflicting styles for an element. When applied to a CSS property, it ensures that the specified value will override other declarations, except for those also marked as `!important`. This can be useful for overriding styles from external sources or when dealing with specificity conflicts. However, overuse of `!important` can lead to code that is difficult to maintain and debug, as it can disrupt the natural cascading nature of CSS. Therefore, it’s generally recommended to use `!important` sparingly and only as a last resort when other methods of specificity control are insufficient.

selector {

property: value !important;

}

Q22 What is the default value of the position property in CSS?

The default value of the `position` property in CSS is `static`. When an element’s position is set to `static`, it follows the normal document flow. It is not affected by positioning properties like `top`, `right`, `bottom`, or `left`, nor can it be transformed or layered using `z-index`. If no `position` value is explicitly specified, elements default to `static` positioning.

Q23 What is the difference between absolute and relative position?

1. Relative Positioning (`position: relative;`):

  • Positioned relative to its normal position in the document flow.
  • Adjusting `top`, `right`, `bottom`, or `left` offsets shifts the element from its original position without affecting other elements.
  • Does not remove the element from the document flow, so it can affect surrounding elements’ layout.
  • Positioned relative to its nearest positioned ancestor, or the initial containing block if none exists.

2. Absolute Positioning (`position: absolute;`):

  • Positioned relative to its nearest positioned ancestor or to the initial containing block if no ancestor is positioned.
  • Adjusting `top`, `right`, `bottom`, or `left` offsets shifts the element from its initial position, disregarding surrounding elements.
  • Removes the element from the document flow, so it doesn’t affect the surrounding elements’ layout.
  • The positioned ancestor element must have a `position` value other than `static` for absolute positioning to work relative to it.

In summary, `relative` positioning adjusts an element’s position relative to its normal flow, while `absolute` positioning places an element relative to its nearest positioned ancestor or the initial containing block, removing it from the document flow.

Q23 What is Flexbox in CSS?

Flexbox is a CSS layout model designed for the efficient distribution of space among items in a container. It allows for flexible alignment, order, and sizing of elements along a single axis, making it ideal for responsive and dynamic layouts without relying on floats or positioning. Flexbox introduces properties like `display: flex`, `flex-direction`, `justify-content`, and `align-items` to control the layout and alignment of flex items within a container, simplifying the creation of complex web layouts.

Q24 Is JS single-threaded or multi-threaded?

JavaScript is single-threaded, meaning it executes tasks one at a time in a single call stack. Though it’s single-threaded, modern web browsers use features like Web Workers and asynchronous programming to handle concurrent tasks without blocking the main thread, ensuring smoother user experiences and better performance for web applications.

Q25 What are different datatypes in JS?

In JavaScript, there are seven primitive data types and one complex data type:

1. Primitive Data Types:

  1. Number: Represents numeric values, including integers and floating-point numbers.
  2. String: Represents text data enclosed in single or double quotes.
  3. Boolean: Represents a logical value, either `true` or `false`.
  4. Undefined: Represents a variable that has been declared but not assigned a value.
  5. Null: Represents an intentional absence of any value.
  6. Symbol (ES6): Represents unique identifiers.
  7. BigInt (ES10): Represents arbitrary precision integers.

2. Complex Data Type:

  1. Object: Represents a collection of key-value pairs, where keys are strings (or Symbols) and values can be of any data type, including other objects.

These data types provide the building blocks for storing and manipulating data in JavaScript. Understanding them is fundamental to working with variables, functions, and data structures in JavaScript programs.

Q26 What are variables and how many ways to declare them in JS?

Variables in JavaScript are containers for storing data values. They allow developers to store and manipulate data within a program. In JavaScript, variables can hold various types of data, such as numbers, strings, objects, functions, and more. Variables in JavaScript store data values. There are three ways to declare variables:

  • `var`: Used for function-scoped variables.
  • `let`: Used for block-scoped variables that can be reassigned.
  • `const`: Used for block-scoped variables that cannot be reassigned.

Each method has its own characteristics:

  • `var`: Variables declared with `var` are function-scoped, meaning they are accessible anywhere within the function in which they are declared, or globally if declared outside of any function. However, they do not have block scope.
  • `let`:Variables declared with `let` are block-scoped, meaning they are accessible only within the block (e.g., `{ … }`) in which they are declared. They can be reassigned a new value, but cannot be redeclared in the same scope.
  • `const`: Variables declared with `const` are also block-scoped, like `let`, but they cannot be reassigned a new value once initialized. However, for complex data types like objects or arrays, the contents of the variable (i.e., properties or elements) can still be modified.

Q27 What is scope in JS?

In JavaScript, scope refers to the context in which variables are declared and can be accessed. It defines the visibility and lifetime of variables and functions within a program. There are two main types of scope in JavaScript:

  • Global Scope Variables declared outside of any function or block have global scope, meaning they can be accessed from anywhere within the program. Global variables are accessible by all functions and blocks, including nested ones.
  • Local Scope: Variables declared within a function or block have local scope, meaning they are accessible only within that function or block and any nested functions or blocks. Local variables are not accessible from outside their containing function or block.

JavaScript follows lexical scoping, which means that the scope of a variable is determined by its location within the source code. This hierarchical structure of scope allows for encapsulation and helps prevent unintended variable modification or conflicts between different parts of a program. Understanding scope is crucial for writing maintainable and bug-free JavaScript code.

Q28 What are functions in JS?

In JavaScript, functions are reusable blocks of code that perform specific tasks when called. They can take inputs, execute operations, and produce outputs. Functions are declared using the `function` keyword or as function expressions. They can also be defined using arrow functions, introduced in ES6. Functions facilitate code organization, encapsulation, and reusability, playing a fundamental role in JavaScript programming for implementing logic, event handling, and asynchronous operations.

Q29 What is the difference between the parameter and argument?

In JavaScript (and in programming in general), “parameters” and “arguments” are related concepts but have different meanings:

1. Parameters:

  • Parameters are variables listed as part of a function’s declaration.
  • They act as placeholders for the values that will be passed (as arguments) to the function when it is called.
  • Parameters define the function’s interface, specifying what kind of values the function expects to receive.

2. Arguments:

  • Arguments are the actual values that are passed to a function when it is called.
  • They are provided within the parentheses of the function call and match the parameters listed in the function’s declaration.
  • The number of arguments passed must match the number of parameters declared in the function, unless the function allows for variable-length argument lists or has default parameter values.

In summary, parameters are defined within the function declaration and act as placeholders for values to be passed, while arguments are the actual values passed to the function when it is called. Parameters are used inside the function to refer to the passed arguments and perform operations.

Q30 What is DOM?

The DOM, or Document Object Model, is like a map of a webpage that lets programs like JavaScript change the page’s content, structure, and style. Think of it as a tree with branches for each part of the page, such as text, images, and headings. When you interact with the page (like clicking a button), you’re actually interacting with the DOM. It’s a standard way browsers organize and control web pages, making it possible for web pages to change dynamically without needing to reload.

--

--