Preparing for a frontend development interview questions is both difficult and interesting, regardless of whether you are a seasoned developer or a newcomer to the field. Knowing a few pertinent interview questions will prepare you to stand out in an interview.
In this blog, we run through some basic yet comprehensive frontend development interview questions touching on various subjects, such as HTML, CSS, and JavaScript, as well as general web development principles.
Knowing this material beforehand will hopefully set you up to market your skills to win your next front-end developer position!
Fresher Level Questions
1. Are tags and elements the same thing?
Tags are keywords or phrases that are begun and ended by angle brackets such as <p>, defining an HTML instruction. Tags tell the browser what type of content or behavior to display.
An element is a unit that includes an opening tag, some content, and a closing tag. It describes the whole structure of the HTML construct.
Example: In <p>Hello World</p>, <p> is the tag, while <p>Hello World</p> represents the element.
2. What are tags and attributes in HTML?
Tags: Mark the beginning and end of elements, e.g. <img>, <p>, or <div>.
Attributes: Give extra information about an element within the opening tag.
Example: <img src=”image.jpg” alt=”description”>. Here, source and alt are the attributes that describe the image source and description, respectively.
3. What are void elements in HTML?
Void elements are tags that don’t need to be closed because they won’t pull up any content.
Examples: <img>, <br>, <hr>, and <input>.
4. What are the different kinds of lists in HTML? Explain each and all their differences.
Ordered list (<ol>): Displays items in number order.
Unordered lists (<ul>): Displays items using bullet points.
5. What is the ‘class’ attribute in HTML? What is the difference between the ‘id’ and the ‘class’ attributes in HTML?
The class attribute in HTML lets you group similar elements together in order to style or manipulate them altogether. Suppose you have five buttons, for instance, that you want displayed one way; therefore, all five might belong to the same class.
The id attribute, however. This is only used within elements that have unique features. Each id may be used only once throughout the page.
Therefore, if you have a specific heading or one unique section that you want to apply style to or access, you might give it an id.
6. How do you optimize loading of website assets?
Techniques
Minimize CSS, JavaScript, and HTML to reduce their sizes.
Compress image formats appropriately; for instance, use WebP.
Use lazy-loading for images and videos.
Give use of a content delivery network, i.e., a CDN.
Enable browser caching. Store resources to be reused later.
7. In HTML, the <strong> and <b> tags, as well as the <em> and <i> tags, are used for text formatting, but they have different meanings and semantic implications.
<strong>: The tag indicates that the enclosed text is of strong importance. Search engines can recognize this semantic meaning and may very well prioritize content marked as <strong> in their determination of page relevance. In essence, it conveys that the enclosed text is important to understanding the content.
<b>: This tag simply renders bold formatting, implying no semantic weight; it’s purely for visual presentation and doesn’t affect SEO.
<em>: The tag emphasizes the enclosed text and suggests this emphasis should occur. Search engines take this as a subtext for importance, which lets them emphasize important ideas within the content.
<i>: The tag only serves to affect visual style, converting the text into italics. It has no connotations and thus has no impact on SEO.
8. Describe the meaning of the <head> and <body> tags in HTML.
<head>: This contains meta-information (such as the title, CSS links, and scripts) that does not appear on the page but helps define the document.
<body>: This contains the visible page content, which includes text, images, links, etc.
9. Can we show a web page within a web page, or is it possible to nest web pages?
Yes, with the <iframe> tag one can include a webpage in the current page.
10. Defining inline and block-level elements. What is their distinction?
Inline Elements
Definition: Inline elements are ones that do not start from a new line. They take up as much width as they need and flow along with the text around them.
Examples: Regular examples of inline elements include <span>, <a>, <strong>, and <img>.
Uses: They are most commonly used for small pieces of content like links or for formatting certain words within a paragraph.
Block-Level Elements
Definition: Block-level elements start on a new line and take up their entire width. They create a block-like structure on a webpage.
Examples: Examples include <div>, <p>, <h1>, and <ul>.
Uses: They are used to create paragraphs, headers, or lists all throughout a webpage.
11. Differences between Inline and Block-Level Elements
Inline elements can sit next to one another while block-level elements stack one under the other.
While inline elements take only as much width as the required amount of space, block-level elements spread themselves and occupy the width of their parent container.
Use the inline elements when dealing with small segregation and the block-level elements for organizing the entire layout structure of a web page.
12. In how many forms can we position an HTML element? What are the acceptable values for the position attribute? Enunciate the very difference between each one of them in your own words.
1. static
- Description: This is the default positioning given to all the elements. Elements in static engross the basic normal flow of the document, meaning, they tack up on the order that they are written in the HTML.
- Behavior: Margins, padding, and other properties would function normally
- together: elements do not overlap.
2. relative
Description: Elements are positioned relative to where they were in normal document flow.
Behavior: Use the top, right, bottom, and left properties to shift the element from where it would have normally been. Other elements continue to act as if the element were still located at its original position.
3. absolute
Description: Elements are positioned relative to the nearest positioned ancestor (an ancestor that has a position value other than static). If there isn’t one, it will be positioned relative to the initial containing block (usually the viewport).
Behavior: The element is taken out of normal document flow, meaning it won’t affect the positioning of other, sibling elements. Use the top, right, bottom, and left properties to precisely place it.
4. fixed
Description: Similar to absolute positioning, the element is positioned against the viewport which allows it to stay at its position while the page is scrolling.
Behavior: It remains fixed in that position regardless of scrolling; this is especially useful for creating headers or menus that remain always on view.
5. sticky
Description: This is a mix of relative and fixed really. The element will behave as if it were relative until a specific scroll position reaches, at which time it becomes fixed.
Behavior: It’s nearly always used for elements you want to stick to the top of the viewport when they’re scrolled past
13. In how many ways can you display HTML elements?
There are common ways in which HTML elements may appear.
Block: It means that an element takes the whole width, starting on a new line (e.g., <div>).
Inline: It is usually of the width that is necessary, sitting next to other elements (e.g., <span>).
Inline-Block: Like inline, but can be given a width and height.
None: The element will be invisible in the layout.
14. What is the difference between display: none and visibility: hidden?
In the case of display:none, the element is removed completely from the page layout and thus does not take any space. In the case of visibility:hidden, the element occupies space but becomes invisible.
15. How to specify the link in an HTML <a> tag and explain the target attribute?
The link in an HTML element is specified using the href tag.
Target attribute
_self: Opens link in the same tab(default).
_blank: Opens link in a new tab.
_parent: Opens a new window in the parent frame.
_top: Displays in the whole window for pages that are framed.
16. How many different ways are there for us to specify CSS styles for HTML elements?
Using the style attribute directly within the element is known as inline CSS.
- Internal CSS: In the <head> section’s <style> tag.
- External CSS: In a different.css file that is connected to the <head> by a <link>.
17. What distinguishes the <link> and <a> tags?
<link> does not render visible elements; it is used to link external resources, such as CSS files.
The anchor tag <a> makes links on the page that can be clicked.
18. Describe forms and learn how to make them in HTML. What are some of a form’s default actions?
Forms are used to gather user input. Add fields such as <input>, <textarea>, and <button> using the <form> tag.
By default, the action URL is submitted, and the page is reloaded.
19. How should HTML handle events?
To enable dynamic interaction with elements, use event attributes (such as onclick and onchange) directly in HTML or attach events in JavaScript.
20. What benefits does HTML5 offer over earlier iterations?
Better mobile compatibility, multimedia capability (<audio>, <video>), and semantic elements (<header>, <footer>, <article>, etc.) were all brought forth by HTML5.
21. How can a webpage incorporate audio or video?
By using the <audio> and <video> elements, you can embed content directly without the need for third-party plugins. Controls and file sources can be specified.
22. what are Semantic elements?
By outlining the goal of the text, semantic components (such as <header>, <section>, and <article>) enhance readability and SEO. For instance:
<header>: For headers on pages.
To divide content into sections, use <section>.
<article>: For separate blocks of content, such as blog post
Intermediate Level Questions
23. What important objectives does the HTML5 specification have?
The goal of HTML5 is to: Enhance document structure through semantics.
Improve the support for multimedia (video, audio).
Boost compatibility with browsers.
Encourage application development and mobile friendliness.
24. Describe the HTML5 web storage concept. Which storage kinds are appropriate for certain situations?
Data can be stored in the browser using Web Storage without compromising server performance. Local Storage and Session Storage were introduced in HTML5.
Local Storage: Keeps information that never expires, even when the browser is closed. Use it for data that ought to endure, such as theme preferences.
Session Storage: Deletes information when the tab or browser is closed. Perfect for short-term data, such as an ongoing form.
25. What is new in HTML5 regarding the connection between the <header> and <h1> tags?
The <header> tag was added to HTML5 as a structural element to specify the header section. In order to improve semantic organization without using <div> tags.
It can include logos, navigation, or other introductory text in addition to a <h1> tag (which allows you to have more than one <header> section on a page, but only one <h1> per page is necessary for good semantic structure).
26. Which HTML5 components constitute new media?
The introduction of HTML5
<audio>: Directly embeds audio files.
<video>: Incorporates playback controls into video files.
<track>: Gives videos text tracks, such as subtitles.
27. Why is it crucial that HTML5 include drag-and-drop functionality? In HTML5, how can an image be made draggable?
A more interactive and user-friendly experience is made possible via drag-and-drop. It’s useful for uploading files or rearranging lists. To enable draggable images:
<img src=”image.jpg” draggable=”true”> configures the draggable attribute to true.
28. What Are Web Workers?
The user interface remains responsive throughout complex operations thanks to Web Workers, which enable JavaScript to function in the background without interfering with the main thread.
For instance, data processing could be done by a web worker while the user is interacting with the page.
29. What are the Various methods for creating a responsive image?
CSS: To scale images according to the container size, use max-width: 100%.
HTML srcset: To load different pictures according to screen size, use <img srcset=”small.jpg 300w, large.jpg 800w” sizes=”(max-width: 600px) 100vw, 50vw” src=”default.jpg”>.
Media Queries for CSS: Establish picture styles that change at predetermined intervals.
30. In HTML5, what is a manifest file?
Through the listing of cache resources, a manifest file makes offline access possible. Web apps with offline capability benefit from the ability for users to access particular files even when they are not connected to the internet.
31. What are the main distinctions between SessionStorage and LocalStorage?
LocalStorage: Lasts throughout sessions and never expires.
SessionStorage: Deletes at the conclusion of the session. Both use JavaScript to access data stored as key-value pairs.
32. When are cookies appropriate to use?
Cookies are used for server-based tracking and session management, including site settings and user registration. Although cookies are smaller than local storage, they provide secure, HTTP-only access.
33. What does CSS specificity mean?
When more than one CSS rule targets the same element, specificity decides which rule applies. It is computed according to the kind of selectors:
The most specific styles are inline.
The following are ID selectors.
This is followed by classes, attributes, and pseudo-classes.
The least specific are element selectors and pseudo-elements.
34. what is a stylesheet?
In order to provide a unified appearance, a stylesheet is a CSS file that specifies styles for HTML elements. It controls layout, colors, fonts, and overall presentation.
35. Describe HTML’s layout: Where are the footer, header, and navigation?
The semantic structure of HTML layout is as follows:
<header>: Located at the top for navigation or introduction content.
<nav>: Contains the main navigation links, either in the header or somewhere else.
<main>: The page’s primary content.
<footer>: At the bottom, usually for copyright info, contact links, etc.
36. What is CSS’s Box Model? What attributes of CSS are included in it?
One layout model that specifies the visual organization of items is the CSS Box Model. In CSS, each element is viewed as a rectangular box and includes:
Content: The box’s actual contents, such as text and pictures.
Padding: The distance from the border to the content.
Border: The line encircling the cushioning.
The outermost area separating an element from its neighbors is called its margin.
37. What is Shadow DOM?
A web standard called Shadow DOM makes it possible for web components to have enclosed DOM and styling. Components can have distinct styles and markup since it generates a distinct, isolated DOM tree that doesn’t conflict with the DOM of the main content.
You must use the attachShadow() method on an element in order to build a Shadow DOM. This process creates a shadow root for that element, which can subsequently have its own styling and markup.
38. What are aspects that are not real?
In CSS, pseudo-elements are used to style particular portions of an element, such as the first letter or line of a paragraph.
Examples include: ::first-line: Styles the first line of a text block; ::first-letter: Styles the first letter of a text block; and ::before and ::after: Inserts content before or after an element’s main content.
39. What are Data attributes?
Additional data can be directly stored on an HTML element using data attributes, which are custom attributes in HTML. They are usually accessed through JavaScript and begin with data-.
40. What is Z-index?
An element’s stacking order on a web page along the z-axis—the axis perpendicular to the screen—is determined by the Z-index, a CSS attribute. When elements overlap, those with a higher z-index value show up before those with a lower value.
41. Where Will You Use Z-index and Why Is It Necessary?
Z-index is crucial for layouts where elements must appear in front of or behind one another since it helps handle overlapping elements. Z-index is used, for instance, when text or graphics overlap.
Drop-down menus that ought to be visible above other items.
Pop-ups, modals, or any other element that needs to be layered on top of other elements.
42. Best Practices for Using Z-index
Limit Use: Steer clear of overusing the z-index because it might cause confusion and complexity due to high stacking orders.
Maintain Low Values: Begin with modest values (1, 2, 3) then raise them as needed. Don’t use high values unless absolutely necessary.
Set Positioning: Since z-index only functions on positioned elements, make sure each element has a position value (either fixed, relative, or absolute).
Steer clear of arbitrary numbers: Large values, such as 9999, are difficult to debug and maintain in programming, therefore try to avoid using them. Use small, properly ordered increments instead.
43. What does VH/VW mean in CSS?
Viewport Height and Viewport Width are units of relative size in the CSS system. The base reference for the unit for calculating view height is taken as 1% of the overall view height.
One VH is equivalent to 1% of view height, and one VW is equivalent to 1% of view width. For example, if the height of the viewport is 1000 pixels, then 10 VH will become 100 pixels.
44. When to Use Float in CSS?
It is an older CSS principle defining the use of the float property to wrap text around an element or to create old-style column layouts.
However, more modern layouts now used for layout positioning now use Flexbox or Grid instead of float, since they are more flexible and easier to maintain.
45. Explain CSS Selectors?
div,p: Selects all <div> and <p> elements.
div p: Selects all <p> elements inside <div> elements (descendant selector).
div ~ p: Selects all <p> siblings of <div> elements.
div + p: Selects the first <p> element that immediately follows a <div> (adjacent sibling selector).
div > p: Selects the child <p> elements of <div>.
Advance Level Questions
46. What Does !important Mean in CSS?
The keyword !important in CSS sets a style rule to correct any other style rules, regardless of specificity.
47. Explain Function Ascription?
Functions are variable-like code segments created to carry out a certain task. A function normally comprises the function keyword, name, parameters, and code block. Here is an illustration of one such function
function greet(name) {
return `Hello, ${name}!`;
}
1
48. Difference Between let, var, and const?
Var
A variable that can be redeclared within its function scope. Variables defined using var are hoisted at the top of their function or global scope, thus being accessed before their declaration, although their value remains undefined.
Let
Block-scoped, can’t be redeclared within the same block. Let keyword is also hoisted, but it’s not initialized when hoisted, which means you cannot access it until its declaration point without getting ReferenceError.
Const
Block-scoped variable and must be initialized at the time of declaration-the value cannot be reassigned later. However, it doesn’t make the variable immutable; if an object is its value, properties of the object can still be changed.
49. What are Hoisting, Callbacks, and ES6 Features?
Hoisting
This refers to a characteristic of JavaScript whereby variable and function declarations are moved or lifted to the top of their scope before execution of the code.
In essence, this means that functions and variables may be called or invoked even before being defined in your code.
For var variables and function declarations, full hoisting applies, so a declaration may be accessed before its actual place in the source code, with an initialization time of undifferentiated values until the assignment line is walked on.
Variables defined using let and const create a wildcard hoisting; however, this will not initialize them. Using them before their declarations will throw an error.
Callbacks
The function to which another function is going to pass as an argument and is then executed after some operation has been completed. This enables control over program flow whenever some events or results are ready in asynchronous code.
ES6 Features
Includes let and const, arrow functions, template literals, destructuring, Promise, and such. These features provide clarity and thereby better control over JavaScript programming.
50. Difference between array.map and array.filter?
array.map()
Purpose: To transform each item in the array.
How it works: Goes through each item in the array applying a function you provide to it and returns a new array with transformed items.
array.filter()
Purpose: To find those items from an array that fulfill certain conditions.
How it works: The array is traversed and if an item does not fulfill the predetermined condition, it is filtered out thereof. A new array will be outputted containing items that meet the specified condition.
51. How to find the length of an object
Length refers to the number of properties of an object, which does not have the built-in function .length as is the case with arrays.
One most common way of getting this count is to make use of Object.keys(), which returns an array of an object’s keys. The length of this array will equal the number of properties in the object.
52. When Is This Async/Await To Be Used?
Async/await is used to manage asynchronous operations in a manner that renders code more readable and maintainable. Instead of having to chain .then() methods or deeply nesting callback functions, async/await allows you to write code that resembles the synchronous but handles asynchronous tasks like fetching data, reading files, or waiting for user input.
This becomes notably useful when
A sequence of asynchronous actions is to be executed in a specific order.
One prefers to get the asynchronous code done without so many .then() chains or nested callbacks, as this can make the code difficult to read through (call it “callback hell”).
You want to wait for several asynchronous tasks to complete and then execute the code only when they’ve completed.
53. Why Do We Make Use of Await Inside of An Async Function?
await can be used only in an async function since an await will pause the flow of a function execution until the awaited Promise is resolved.
Without an async function, JavaScript’s engine just will not be able to manage pauses in execution properly because await doesn’t work outside of async.
The async keyword tells JavaScript that the function is asynchronous and allows the JavaScript engine to manage waiting and resuming in the background.
54. What Are Callbacks? What Is Callback Hell?
A callback is a function that is passed into another function as an argument and is called after the function finishes executing its statements.
With callbacks, asynchronous operations can take place as it is common to wait for some time during operations such as fetching data from a server.
While some operation is executed, JavaScript does not sit idle waiting; it moves along to other executions and will execute the callback when the operation is complete.
An example could be logging a message after a successful data-fetch operation from a server.
Callback Hell is when many callbacks that are closely nested within each other create code that is difficult to read or maintain. As the stacking goes one level down, it becomes incredibly hard to digest and debug; hence the phrase “callback hell” forms.
In practice, this will often occur due to chaining of multiple dependent asynchronous operations that require nested callbacks.
55. Call, Apply, Bind. When to use what? Can you give an example?
call()
What it does: call() is actually used to call a function immediately, giving the value of this the object you pass as its first argument. After that, you can provide further arguments to the function one by one.
When to use call(): call() should be used when you want to immediately invoke a function with a specific this value. It also helps to “borrow” a function from one object to use with another.
Example
let person1 = {
name: "Alice"
}
let person2 = {
name: "Bob",
introduce: function(greeting) {
// Here "this" refers to person1
console.log(`${greeting}, my name is ${this.name}`);
}
}
// By using call, we invoke the introduce method with person1 as this
person2.introduce.call(person1, "Hello");
// Output: "Hello, my name is Alice"
apply()
What it does: The same as call, except that it accepts an array of arguments rather than individual parameters. apply() is very useful when you have an array of values that you let into the function as parameters.
When to use apply(): apply() should be used when you want to apply an array of arguments to the function.
Example
let person1 = {
name: "Charlie"
}
let person2 = {
name: "Diana",
introduce: function(greeting, punctuation) {
// Here, "this" refers to person1
console.log(`${greeting}, my name is ${this.name}${punctuation}`);
}
}
// Using apply to invoke introduce with person1 as this, and the arguments as an array
person2.introduce.apply(person1, ["Hi", "!"]);
// Output: "Hi, my name is Charlie!"
bind()
Use bind(): Use bind() when you want to create a new function, with an explicit value assigned to this, and you want to postpone calling it. Particularly useful in event handlers or callbacks where it is necessary to keep this context constant.
Example
let person1 = {
name: "Eve"
}
let person2 = {
name: "Frank",
introduce: function (greeting) {
// Here, "this" refers to person1
console.log(greeting + ", my name is " + this.name);
}
}
// Passing the context of person1 to introduce and saving in a new function
let greetEve = person2.introduce.bind(person1);
// Now call the bound function
greetEve("Hey");
// Should output: "Hey, my name is Eve"
56. What does a generator function mean in javascript?
A generator function is a function that is defined with the special function syntax. Upon having been called, it will not have executed the body of the function immediately, but will return a generator object, which is then used to control the execution of the function, allowing iteration over its results.
Characteristics
Pause and Resume: A generator function can yield a value at any point allowing its execution to be halted and resumed later on from the same point of suspension just by calling the function.
Iterator Protocol: The generator object says to conform to the iterator protocol, which means it has a next() method, which returns an object in the form of properties containing two features:
value: Value yielded by the generator.
done: A boolean object that indicates whether the generator has completed.
Example
// Define a generator function
function* countUpTo(max) {
let count = 1;
while (count <= max) {
yield count; // Pause and return the current count
count++; // Increment the count
}
}
// Create a generator object
const counter = countUpTo(3);
// Use the generator object to get values
console.log(counter.next()); // Output: { value: 1, done: false }
console.log(counter.next()); // Output: { value: 2, done: false }
console.log(counter.next()); // Output: { value: 3, done: false }
console.log(counter.next()); // Output: { value: undefined, done: true }
57. What is arr.reduce used for?
The arr.reduce() method in JavaScript reduces the array to a single value by executing a provided function for each element in the array where the function takes as its arguments an accumulator and the current element returns a new accumulator value.
Example
const numbers = [1, 2, 3, 4, 5];
// Using reduce to sum the numbers
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue; Add current value to the accumulator
}, 0); Initial value is 0
console.log(sum); Output: 15
58. What are the differences between == and ===?
The first one is the equality operator, which does type coercion.
When you use ==, JavaScript will convert the values to the same type before comparison.
The second operator is strict equality, which does not perform type coercion.
With ===, JavaScript does not convert and checks both the value and the type.
59. What is the difference between null and undefined?
Null
- It is a deliberate absence of any object value. This refers to a value which was actually set to nothing.
- It belongs to type object.
- This is mostly used to indicate that a variable is supposed to be empty or that a value is not known.
Undefined
- Default value of uninitialized variables. It refers to a variable declared but without an assigned value.
- Of type – undefined.
- It can also happen when a function does not have a return statement.
60. What output will it produce (true or false)? Justify.
console.log(null === undefined); // Output: false
console.log(null == undefined); // Output: true
null===undefined
- Output: false
- Reason: The strict equality operator (‘===’) compares both the value and the type of the operands. Since “null” is an object and “undefined” is an undefined type, both are not equal.
null==undefined:
- Output: true.
- Reason: The loose equality operator (‘==’) allows type coercion. JavaScript treats null and undefined as equal when used in equality checks, so they are equal.
61. what will be the printout of the following true or false?Why will that be?
console.log(null===undefined)
console.log(null==undefined)
Output
- console.log(null===undefined) will print false.
- console.log(null==undefined) will print true.
Explanation
=== is the equality operator that checks for both value and types. Since null is an object and undefined has its own type, they do not have the same type, and therefore, the evaluation is false.
== is the equality operator that does type coercion. When null and undefined are compared with ==, they are considered equal; therefore, true is returned.
62. What is Event Propagation and Event Bubbling?
Imagine that the button you click is inside a box, and that box is inside another larger box. When you click the button, the browser needs to decide if only the button should respond, or if the outer boxes should respond too.
Event Propagation is how the browser decides in which order to handle these events, from the most outer element down to the innermost, or vice versa.
Two Types of Propagation
- Capturing (Event Capturing): The event starts from the outermost element (like the largest box) and goes inward to the target element (like the button).
- Bubbling (Event Bubbling): The event starts from the target element (button) and goes outward to the outer elements (like the boxes it’s inside).
63. What is function currying? How Can you create a curried function and explain?
Currying is a technique where a function, instead of taking all arguments at once, takes the first argument and returns a new function that takes the next argument, and so on, until all arguments have been provided.
function curryFunction(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
}
// Usage:
const curried = curryFunction(1)(2)(3);
console.log(curried); // Outputs 6