Top 20 Frontend Interview Questions With Answers
Tags: frontend, interview, programming, javascript
Published: 2024-02-03 14:13:13

Frontend represents the presentation layer of something, and the term is generally used to refer to frontend web development, which is creating the part of the website that users see and interact with. This involves coding in HTML, CSS, and JavaScript to build a website or web application that will be executed by browsers so that users can interact with it.

Like most tech positions, applications for frontend developers often involve extensive skills testing. This means that you have to not just be able to demonstrate your skills and experience during the interview, but also explain the underlying reasoning. It's not always enough to know how to do something; you have to know why you're doing it, too.

In this article, you will learn how to answer some of the most common—and crucial—frontend questions asked during an interview so you won't be caught unprepared.

## 1\. What's the Difference Between `var`, `let`, and `const` in JavaScript?

Originally, you could only declare a variable in JavaScript with the [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) keyword. Then, [ES6](https://en.wikipedia.org/wiki/ECMAScript) introduced [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) and [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const).

These are the most important differences you should be aware of:

<table><tbody><tr><td></td><td><code>var</code></td><td><code>let</code></td><td><code>const</code></td></tr><tr><td><strong>Scope</strong></td><td>Global scoped or function scoped</td><td>Block scoped</td><td>Block scoped</td></tr><tr><td><strong>Declaration</strong></td><td>You can declare it without initialization</td><td>You can declare it without initialization</td><td>You can declare it without initialization</td></tr><tr><td><strong>Assignment and update</strong></td><td>You can update it and re-declare it into the scope</td><td>You can update it into the scope, but you cannot re-declare i</td><td>You cannot update it or re-declare it into the scope</td></tr><tr><td><strong>Access</strong></td><td>You can access it even without initializing. Its default value is&nbsp;<code>undefined</code>.</td><td>You cannot access it without initialization</td><td>You can access it only after initializing it, since it requires you to define it</td></tr></tbody></table>

## 2\. How Should You Log Errors?

The most common approach to logging errors is to print them in the browser console with the [`console.error()`](https://developer.mozilla.org/en-US/docs/Web/API/console/error) JavaScript function. This is useful for noticing errors while developing and addressing them immediately. However, `console.log()` prints only the final output, and may not be sufficient to understand the causes of an error.

Additionally, `console.error()` doesn't offer a way to discover errors encountered by your users. This is why you should integrate your frontend application or website with more advanced error and exception reporting platforms, such as [Sentry](https://docs.sentry.io/platforms/javascript/). Thanks to the SDKs offered by this type of platform, you can track user interaction that led to an error and store all this information in the cloud, which provides more insight when you need to debug.

## 3\. What Is the `<meta>` Tag in HTML? What Is It Used For?

The [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) HTML tag can be used to define metadata about the HTML page that can't be represented by other HTML elements. A single HTML document can contain several `<meta>` tags, each of which must be placed inside the `<head>` HTML element. These tags are generally used to specify keywords, character set, page description, author information, and viewport settings.

Examples of some `<meta>` tags in action:

```html
<meta name="keywords" content="HTML, CSS, JavaScript, Frontend, Interview, Questions">
<meta name="description" content="Top 20 Frontend Interview Questions With Answers">
<meta name="author" content="Antonello Zanini">
```

## 4\. What Is a CSS Rule?

A CSS rule is a group of one or more CSS properties that are applied to one or more target HTML elements. A CSS rule consists of a selector and a declaration block. The CSS selector specifies what HTML elements the rule targets, while the destination block includes the set of CSS properties that define how the targeted elements should be styled.

Example of a CSS rule:

```css
.container {
  background-color: red;
  font-size : 15px;
}
```

This CSS rule targets all HTML elements having the class "container", and defines its background color and text font size.

## 5\. How Can You Implement Internationalization?

The best way to implement internationalization is to use an internationalization framework library, such as [i18next](https://www.npmjs.com/package/i18next). With this kind of library, you can easily handle translations and automatically display your frontend labels in the user's language. The frontend application also needs to be flexible and easily configurable so that its layout can change accordingly, reading from left to right or right to left. CSS allows this with the `rtl` and `ltr` [CSS `direction` property](https://developer.mozilla.org/en-US/docs/Web/CSS/direction).

Designing a frontend application or website with a layout that can be changed effortlessly isn't always practical, so sometimes you may need to look for a different solution. One option is designing and building specific pages for a particular area or language. This gives you more control over the way the page is presented and laid out, which can give better and more cohesive results than simply translating labels.

Additionally, you should organize your website so that it's easy to navigate, regardless of the selected language or version for a target country. This is why frameworks such as Next.js natively offer [internationalization routing](https://nextjs.org/docs/advanced-features/i18n-routing) capabilities.

## 6\. What Is the Bootstrap Grid System?

The [Bootstrap grid system](https://getbootstrap.com/docs/5.2/layout/grid/) uses containers, rows, and columns to layout and align content in an HTML document.

Bootstrap supports [six responsive breakpoints](https://getbootstrap.com/docs/5.0/layout/breakpoints/) at which the layout will automatically reflow the content, ranging from `xs` to `xxl`. Containers, which are used to center your content on the page and pad it horizontally, hold rows. The rows are used to hold columns, which hold your content.

Bootstrap is incredibly flexible, and makes creating a customized, responsive layout a simple task.

## 7\. What Is Semantic HTML? What Is It Based On?

Semantic HTML aims to introduce meaning to a web page rather than just defining its presentation. Semantic HTML is based on [semantic HTML elements](https://www.w3schools.com/html/html5_semantic_elements.asp), which describe their meaning to both the browser and the developer. For example, the [`<h1>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements) tag is a semantic element, because in addition to the layout-related information it gives to the browser, it gives the text it wraps around the human-readable meaning of "a top-level heading." In contrast, `<span>` and `<div>` are generic elements with no inherent semantics.

## 8\. What Is a Promise in JavaScript?

A [promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) is a proxy for a value that is unknown when the promise is created. In other words, a promise represents the eventual value of an asynchronous operation. If the operation succeeds, the resultant value will be returned; if the operation fails, an error will be returned.

Promises allow asynchronous methods to return values like synchronous methods. What they return immediately is a promise, which will supply the appropriate value at some point in the future.

## 9\. What Are Higher-Order Functions? Does JavaScript Support Them?

A higher-order function is a function that either accepts functions as parameters, or returns a function. JavaScript fully supports them, as shown in the example below:

```javascript
// returning a function from function
function getFunction() {
  return () => { console.log("Hello, World!") }
}
 
const myFunc = getFunction()
myFunc()
```

This would print:

```
Hello, World!
```

## 10\. How Can You Make a Frontend Application or Website Load Faster?

If you are using webpack, you should use a library like [`webpack-bundle-analyzer`](https://www.npmjs.com/package/webpack-bundle-analyzer) to study what the build bundle of the frontend application consists of. This will help you understand what components affect the size of the build bundle the most, as well as provide insight into how to reduce the bundle weight. The lighter the build bundle, the faster the browser will download and render it.

One of the best ways to reduce the build bundle size is to [minify the scripting and style files](https://en.wikipedia.org/wiki/Minification_(programming)). You should also consider removing unused CSS, which you can accomplish automatically with the [`purgecss`](https://www.npmjs.com/package/purgecss) npm library, although you will likely need custom configurations to get the maximum benefit out of this sort of tool.

Other size-reduction techniques include removing unused JavaScript libraries, replacing heavier dependencies with lighter-weight alternatives, and avoiding external embeds and widgets. In extreme circumstances, you can also configure webpack to ignore libraries that are required by your dependencies, but only support features that you don't use.

It's also important to ensure that you're importing libraries correctly, so webpack can perform [tree shaking](https://webpack.js.org/guides/tree-shaking/) effectively. For example, let's import [`lodash`](https://www.npmjs.com/package/lodash), as follows:

```javascript
 import _ from "lodash"
```

This will bring the entire library into the build bundle. It's unlikely that your application needs the entire library, though, so this makes the bundle unnecessarily heavier.

An alternative is importing specific `lodash` utilities, as follows:

```javascript
 import { sortBy, debounce, reduce } from "lodash"
```

Doing this ensures that webpack will insert only the `lodash` utilities that are actually used into the build bundle.

Finally, you may want to avoid PNG and JPEG images, and replace them with images in lighter-weight formats, such as [`WebP`](https://en.wikipedia.org/wiki/WebP). This will reduce both the time it takes to download them and the time it takes to render them.

## 11\. What Is Cross-Site Scripting (XSS)?

[Cross-site scripting](https://en.wikipedia.org/wiki/Cross-site_scripting) (XSS) is a common type of security exploit, which allows an attacker to inject client-side scripts into a website. When someone visits the page, their browser will automatically execute the script, thinking that it came from a secure source. An XSS attack succeeds when the web page does not use enough validation, and the user's browser cannot detect that the malicious script injected by the attacker is untrustworthy. This allows the attacker to access all frontend resources and functionality that the user has access to, including the user's data, privileges on the site, and session tokens.

## 12\. What Is the BEM Approach to CSS?

[BEM](http://getbem.com/introduction/) stands for Block, Element, Modifier, and is a frontend naming methodology for organizing and naming CSS classes to avoid overlapping. The BEM approach to CSS is one of the most popular naming conventions for CSS class names.

BEM consists of:

- **Block:** This holds several elements.

- **Element:** This is a specific part of the component.

- **Modifier:** This acts as an additional style to a specific element.

Example of an HTML snippet using BEM:

```html
<div class="body">
  <div class="body__arm body__arm--left">left</div>
  <div class="body__arm body__arm--right">right</div>
</div>
```

The block `body` contains two elements named `arm`, which are characterized by the `left` and `right` modifiers, respectively.

According to the BEM convention, these should build on each other's names, so that the modifier name is ultimately constructed in the format of `block__element--modifier name`.

## 13\. How Can You Deal With Full Screen Programmatically?

In order to deal with full-screen mode programmatically, you first have to make sure that it is enabled. This can be achieved by setting the "fullscreen" JavaScript [feature policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Feature_Policy). By default, full-screen mode is allowed in top-level documents, as well as in nested browser elements with the same point of origin as the top-level document. In other words, you have to manually enable the full-screen feature policy for external iframes, widgets, and embeds.

Once it's been enabled, you can handle full screen in JavaScript natively via the [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API). Using the Fullscreen API, you can enter and exit the full-screen mode programmatically, making either the entire web page or single DOM element full screen.

When dealing with frontend libraries or frameworks such as [React](https://reactjs.org/), using the Fullscreen API directly may be difficult because of the way the framework handles the DOM. In scenarios like this, you can opt for an external library, such as [`react-full-screen`](https://www.npmjs.com/package/react-full-screen), to handle full-screen logic. This enables you to elegantly implement full-screen functionality on a React component.

## 14\. What is the Difference Between `<span>` and `<div>`?

A [`<div>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div) element is a block element, typically used to divide page content into blocks. A [`<span>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span) element is an inline element, generally used to separate inline content or apply styling to the same.

## 15\. What Is a Mixin?

A [mixin](https://en.wikipedia.org/wiki/Mixin) is a class containing one or more methods that can be used by other classes without the need for them to inherit it. In other words, a mixin provides methods that can't be used alone, but can be used to add a behavior to other classes.

Example of a mixin in action in JavaScript:

```javascript
// mixin definition
const greetingMixin = {
  introduceYourself() {
    console.log(`Hi, my name is ${this.name}`)
  },
  sayBye() {
    console.log(`Bye!`)
  }
}
 
class User {
  constructor(name) {
    this.name = name
  }
}

// coping the mixin method into the User class
Object.assign(User.prototype, greetingMixin)

// now, a User instance can, say, introduce themselves
new User("Maria").introduceYourself()
```

This will print:

```
Hi, my name is Maria!
```

## 16\. What Is the Document Object Model (DOM)?

The [Document Object Model (DOM)](https://blog.hubspot.com/website/dom-web-design) represents the structure of an HTML document with a logical tree, where each branch of the tree is a node containing one or more objects.

By using the DOM, programming languages can interact with the page by accessing its nodes through the tree. Thanks to the DOM, it is possible to change the content, structure, and style of an HTML page document through a scripting language such as JavaScript.

## 17\. What Is Webpack?

[Webpack](https://webpack.js.org/) is a module bundler, the main purpose of which is to bundle JavaScript files to make them usable in a browser.

Webpack can transform, bundle, and package any resource or asset and comes with several features, such as module merging, code minimization, TypeScript transpiling into JavaScript, npm integration, and more. Simply put, webpack bundles your frontend application and its resources into something that a web browser can understand.

## 18\. What Is npm?

[npm](https://www.npmjs.com/) is the default package manager for the JavaScript runtime environment [Node.js](https://nodejs.org/en/).

npm comes with a command line client called npm, and it relies on an online database of public, open source, and purchasable private packages. This registry is called the npm registry and allows you to retrieve, browse, and search for any npm available packages.

## 19\. What is the difference between CSS and SCSS?

CSS stands for [Cascading Style Sheets](https://www.w3schools.com/css/), and is a scripting language used to style web pages. [SCSS](https://sass-lang.com/) stands for Syntactically Awesome Style Sheet, and is a superset of CSS. You can think of SCSS as the more advanced version of CSS, which comes with several features that CSS does not support, such as the SCSS nested syntax, as shown below.

CSS example:

```css
.container .header {
  display: flex;
}

.container .header span {
  color: red;
}
```

The SCSS equivalent is much more compact, and easier to read:

```css
.container {
  .header {
    display: flex;
    
    span {
      color: red;
    }
  }
}
```

## 20\. How Can You Improve Technical SEO Performance?

[Google Core Vitals](https://web.dev/vitals/) now represent the most important metrics to focus on when it comes to technical SEO. Google Core Vitals are a set of standardized metrics that Google uses to evaluate the user experience offered by a web page and assign it a technical SEO grade. Several tools exist to measure and report technical SEO performance, but the most reliable is [Google Lighthouse](https://github.com/GoogleChrome/lighthouse).

Google Lighthouse comes built-in to Google Chrome, and you can launch an SEO analysis directly from the DevTools window. When the analysis is complete, the tool will produce a report that looks like this:

![The results of a Google Lighthouse test](https://writech.run/wp-content/uploads/2023/12/image-24.png)

Further down in the report, Google Lighthouse also provides you with feedback, hints, and advice for improving the Google Core Vitals metrics. By addressing them all, you will improve the web page quality and your technical SEO performance as a result. This will help Google rank your website higher.

It is important to note that single page applications (SPA) are not good for SEO, and you cannot apply standard SEO practices to them. Because the web pages of a SPA are built by the browser via JavaScript, search engines have a hard time crawling them, and may even fail to do so entirely. Therefore, optimizing technical SEO in a SPA isn't likely to yield any benefits.
  
***
_The post "[Top 20 Frontend Interview Questions With Answers](https://writech.run/blog/top-20-frontend-interview-questions-with-answers/)" appeared first on [Writech](https://writech.run)._