Published on

Frontend Interview

Authors
  • avatar
    Name
    Loc Truong
    Twitter

Beginner

What is the difference between an id and a class in HTML/CSS?

An id is a unique identifier for a single HTML element. A class is a reusable identifier that can be applied to multiple elements. id identifier You'd want to use an id when you need to addresss a single element either through CSS or JavaScript. And you'll want to use a class when you need to address a group of DOM elements.

In CSS:

  • #id selects a specific element with that id.
  • .class selects all elements with that class.

Một id là một định danh duy nhất cho một phần tủ HTML. Một class là một định danh có thể tái sủ dụng và có thể được áp dụng cho nhiều phần tử. Bạn nên sủ dụng id khi cần nhắm đến một phần tử duy nhất bằng CSS hoặc JavaScript. Còn class d9uoc5 dùng khi bạn cần nhắm đến một phóm phần tủ trong DOM.

Trong CSS:

  • #id chọn một phần tủ cụ thể có id đó.
  • .class chọn tất cả các phần tử có class đó.

Can you explain the box model in CSS?

The CSS box model describes the rectangular boxes generated for elements in DOM. The box model is composed of the following layers:

  1. Content: The innermost part, where text and images appear.
  2. Padding: The space between the content and the border.
  3. Border: The outer edge of the padding, surrounding the element.
  4. Margin: The space outside the border, separating the lement from others. By controlling each layer indivilually, you can define the look of each element in the user interface.

Mô hình hộp (CSS Box Model) mô tả các hộp hình chữ nhật được tạo ra cho các phần tử trong DOM. Mô hình này bao gồm các lớp sau:

  1. Content (Nội dung): Phần bên trong cùng, nơi hiển thị văn bản và hình ảnh.
  2. Padding (Lề trong): Khoảng cách giũa nội dung và viền.
  3. Border (Viền): Rìa ngoài của phần padding, bao quanh phần tử.
  4. Margin (Lề ngoài): Khoảng cách bên ngoài viền, tách phần tử ra khỏi các phần tử khác. Bằng cách điều chỉnh từng lớp riêng lẻ, bạn có thể định dạng giao diện của từng phần tử trong giao diện người dùng.

What is the difference between inline, inline-block, and block elements?

In CSS, the difference between inline, inline-block, and block elements is on the way they're rendered in the web page:

  • inline: Inline elements don't have a width or height. Instead, they don't start on a new line and take up only the width that's required (based on their content). Examples: <span>, <a>.
  • inline-block: Just like inline elements, here the DOM elements do not start on a new line, however, they do allow you to set a hieight and width on them. Example: <img>.
  • block: Elements start on a new line, taking up the full width available by default. Their width and height can be set by you. Examples: <div>, <p>.

What are some SEO best practices when structuring an HTML document?

Purely from the HTML side:

  • Use Semantic HTML: Use tags like <header>, <nav>, <main>, <article>, <section> and <footer> to provide meaningful structure.
  • Proper Heading Hierarchy: Use headings (<h1> to <h6>) correctly, making sure <h1> is used once per page for the main title, followed by <h2>, <h3>, etc.
  • Meta Tags: include relevant <meta> tags, such as description, keywords and viewport, to provide metadata about the website.
  • Alt Attributes on images: use alt attributes for images to describe the content, improving accessibility and search engine understanding. On top of that:
  • Internal Linking: make sure to use internal links to connect content within your web site, helping search engines crawl and understand the site structure.
  • Mobile-Friendly Design: Code your site and CSS with a mobile-first mindset. Ensuring the site is responsive and mobile-friendly to improve user experience and ranking on search engines.
  • Fast loading times: Tryo to optimize images, use efficient code, and leverage caching to improve page load speeds. The faster the page loads, the bigger the advantage it'klll have against other similar results on the SERP.

What is the Document Object Model (DOM)?

The DOM is an API for web documents. It represents the structure of an HTML web page as a tree of nodes, where each node corresponds to a part of the document (i.e. an element, an attribute, or text).

How do you add an event listener to an element?

To add an event listener to an element, you have to first "get" that element through one of the many methods of the doucment object (i.e. getElementById, etc) and then use the addEAventListener method of the obtained object. The method wil lreceive the event name (i.e . 'click', 'keyup', 'mouseup', etc), the event handler function and , optionally, a boolean indicating whether the event should be captured during the capturing phase.

What is the difference between null and undefined?

In JavaScript, "undefined" is the default value new variables take, and it means the variable has been defined but it hasn't been assigned any value just yet. And "null" is actually a value that signals "no value" or "no object", it is specifically assigned to the variable by the developer.

What is the difference between cookies, sessionStorage, and LocalStorage?

Cookies are small pieces of data stored in web browsers. They are mainly used for keeping information between HTTP requests, such as user authentication, session management, and tracking user behavior. On the other hand, sessionStorage is designed for temporary storage and is accessible only with in the same session (i.e.., while the browser window or tab is open). Data Stored in sessionStorage is lost when the browser window is closed. Finally, localStorage is similar to sessionStorage but persists even when the browser window or tab is closed and reoipened. It provides long-term storage for web applications. They are very similar to cookies, however, the size limitations on localStorage are quite big compared to cookies, making it a much better alternative when storing large datasets.

How does the browser render a website?

THe process of rendering a web page in the browser involves several steps:

  1. Parsing the HTML.
  2. Parsing the CSS and applying styles.
  3. Calculating the position of each element in the layout of the page.
  4. Painting the actual pixels in the screen, while at the same time sorting them into layers. 5, Composing all layers together, to render the website on screen. This step is taking into account z-index values, opacity values and more.
  5. Running JavaScript code.
  6. Loading the asynchronous resources.

What are media queries?

Media queries are a feature in CSS that allow Frontend developers to apply different styles to a doccument based on various characteristics of the device or viewport. For example, you can set different styles based on the device's width, height, orientation, or type. Through media queries we can achieve responsive design allowing styles to adapt to different screen sizes and devie capabilities.

Intermediate

What is the difference between the em and rem units?

They're both relative units of measurement, however, they're relative to different things:

  1. "em" units are relative to the font size of their parent element. So if the parent element has a font size of 20px, then setting a "2em" font size, would qequal to 40px.
  2. "rem" units are "root em", which means they're relative to the web page's root element (the <html> element).

How do you create a flexbox layout?

To create a flexbox layout, you have to take care of 2 main steps:

  1. Set up the container element by applying the "display: flexbox;" CSS property to it.
  2. Set up the flexbox properties for each element inside the container (something like "flex:1" would suffice).

Can you explain CSS specificity and how it works?

CSS specificity is used to determine which set of styles to apply on any given element when there are overlapping styles (like several rules setting the font-size of the same element).

The way it works is by applying the following order of precedence:

  1. First, any inline style will override any other style.
  2. Second, Any ID-based sstyle will override anything but inline styles.
  3. Thrid, class-based selectors will override anything but inline and ID-based styles.
  4. Finally, type selectors can be overriden by any other type of selectors.

How can you create a CSS grid layout?

To create a grid layout, you have to first specify the "display:grid;" property on the containing element, and then define the structure of the grid, by using the "grid-template-rows" and "grid-template-columns" properties.

Now simply place the elements inside the grid container and specify the "grid-column" or "grid-row" properties.

What are closures, and how/why would you use them?

When a function dis defnined within another function, it retains access to the variables and parameters of the outer function, even after the outer function has finished executing. That link, between the inner function and its scope inside the outer function is known as "closure".

You can use them to create private variables that can only be accessed hby the inner function, you can even use them to create complex objects with acccess to a rich context that is only available globally to them.

Can you explain what event delegation is in JavaScript?

Event delegation is a technique where you define an event handler for a particular event as part of the parent element that contains the elements that will actually trigger the event. event delegation When the event is triggered, it'll bubble up in the DOM hierarchy until it reaches the parent's event handler.

What are promises, and how do they work?

Promises are JavaScript objects that represent the eventual completion of an asynchronous call. Through promises you're able to handle the successful or failed execution of the asynchronous call.

How do you optimizse website assets for better loading times?

There are different techniques to improve loading times, depending on the asset type, for example:

  • CSS & JavaScript files should be minimized and compressed.
  • Images can be compressed when you're saving them or through the use of specialized software, like JPEGOptim or ImageOptim. Just make sure you don't lose any quality during the process.

What are service workers, and what are they used for?

Service workers are scripts that runn in the background of a web application, separate from the web page's main thread, and provide features like offline caching, push nontifications, and background synchronization.

What is the same-origin policy in web development

The same-origin policy is a security feature in browsers designed to prevent a website from accessing data (like importing a script, or sending a request to an API) from another site.

This policy helps protect users from malicious scripts that try to steal sensitive data from other websites, such as cookies, local storage, or content

A way to overcome this limitation is through CORS (Cross-Origin Resource Sharing). As long as the server specifies which domain it can receive requests from, and the client app sends the right headers, they will be able to interact with each other, evne if they're not in the same domain.

AAdvanced

What are CSS variables, and when would you use them?

Just like variables in frontend programming language, CSS variables can be set by developers and reused across the entire CSS stylesheets. They're greate for centralizing lgobal values that are used throughout the website's code.

They're also heavily used by CSS frameworks to set constants such as the value of colors (i.e. "black" being "#222" isntead of "000".)

How would you implement critical CSS to improve the perceived load time of your web pages?

Remove the CSS rules from the CSS and inline them into the main <head> element of your website.

By doing it like this, you remove the loading time of that code, as it loads immediately once the main file loads. The rest, the non-critical rules, can be loaded once the main resource loads (the mainn CSS file).

How does the event loop work in JavaScript?

The event loop is a core concept in JavaScript, and it allows for the execution of asynchronous code. event loop javascript The way it works, is as follows:

  1. Call Stack: JavaScript executes your code on a single thread using a call stack, where function calls are added and executed one by one. When a function ends, it's removed from the stack.
  2. AAsync calls: For asynchronous operaiotns, JavaScript uses Web Apis provided by the browser. These operaitons are offloaded from the call stack and handled separately. #. Tasks Queue: Once an asynchronous call is done, its call back is placed in the task queue.
  3. Event Loop: The event loop constantly checks the call stack and the task queue. If the call stack is empty, it takes the first task from the queue and pushes it onoto the call stack for execution. This cycle repeats indefinitely.

What are the different ways to handle asynchronous operations in JavaScript?

There are 4 main ways in which JavaScript allows developers to handle asynchronous calls. in the end, the result is always the same, but the final structure of the code and the way to reason about it is considerably different.

  • Callback: They allow you to set up a function to be called directly once the asynchronous operation is done.
  • Promises: Promises represent the eventual completion of an asynchronous operaiton, and they provide a simpler and more intuitive syntax to specify callbacks to be called on success and failure of the operation.
  • Async/Await: The final evolution of the promises syntax. It's mainly syntactic sugar, but it makes asynchronous code look synchronous, which in turn makes it a lot easier to read and reason about.
  • Event listeners: Event listenres are callbacks that get triggered when specific events are fired (usually due to user interactions).

How do you handle state management in single-page applications?

Without a full framework or library like React or Vue.js, properly handling state management is not a trivial task.

Some options available through the language itself are:

  • Global Variables: You can use global variables, or perhaps a global object tocentralize state. The problem with this approach is that it can become quite unmanageable for large applications. It's also a lot harder to maintain local state inside single components.
  • Module Pattern: You can use this pattern to encapsulate state and provide a clear API to manage it. You would have to instantiate local instances of these modules for individual components.
  • Pub/Sub Pattern: this option is more sophisticated, and it decouples state changes using event-driven architecture. It's a more comples solution, but it provides a bigger flexibility.
  • State Management Libraries: You can always use something like Redux or similar libraries without frameworks.

How does virutal DOM work, and what are its advantages?

The way the virtual DOM works is the following:

  1. The entire user interface is copied into an in-memory structure called "virutla DOM", which is a lightweight version of the actual DOM.
  2. When state chantges and the UI Needs to be updasted, a new virtual DOM is created with the updasted state.
  3. Then a diff is made between the new virtual DOM and the previous version. 4, The system will then calculate the leaset amount of changes required to achieve the new state, and it'll aply those changes. Only the nodes that need to be updated are touched, which minimizes direct manipulation of the real DOM.

As for advantages:

  • Performance optimization: By only updateing specific nodes withi nthe real DOM, this technique reduces the number of updates, reflows and repaints on the UI. Directly affecting hte performance of the app.
  • Cross-playform: the virtual DOM provides a layer of abstraction between the application and the actual API that renders the UI. This means the app can be ported into other platforms as long as there is a virtual DOM implementation for that plat fomr.
  • Consistency: this technique keeps the ui in sync with the internal state, reducing bugs and incosistencies.

What is sever-side rendering, ant when might you use it?

Server-side rendering (SSR) is a technique inwhich a web server generates the HTML content of a web page and sends it to the client (usually a web browser) as a fully rendered document. This it the opposite of what naturally happens with client-side rendering (CSR), where the browser downloads a minimal HTML page and then uses JavaScript to render the content dynamically.

There are several ideal use cases for SSR:

  • Content-rich websites: For example, news sites, blogs, etc.
  • SEO-heavy applicaitons: When the success of the web app relies on SEO, this approach can greatly improve the performance of the site (and because of that, the SEO performance)
  • Progressive web applications: When the application need s to render fast to provide a fast and performance user experience, the application can initially be rendered on the server, and then hydrated on the client for subsequent integrations.

How do you analyze and improve the performance of a web application?

The main set of metrics to monitor for web apps are:

  1. First Contentful Paint (FCP): Time until the first piece of content is rendered.
  2. Largest Contentful Paint (LCP): Time until the largest content element is rendered.
  3. Tiem to Interactive (TTI): Time until the page is fully interactive.
  4. Total blocking time (tbt): total time during which the main thread is blocked.
  5. Cumulative Layout Shift (cls): measures visual stability.

What is content security Policy (csp), and how does it improve the security of web applications?

Content Security Policy (CSP) is a security standard that helps to avoid cross-site scripting (XSS) attacks and other code injection attacks by defining and enforcing a whitelist of approved souruces, such as scripts, stylesheets, images and other resources.

The main benefits are:

  • Better Security: CSP helps protect websites and web apps against various types of attacks, including XSS and data injection.
  • More control: developers can define fine-grained policies to control the sources from which content can be loaded.
  • Improved Compliance: Helps meet security compliance requirements, such as those outlined in OWASP Top 10.

What is tree shaking, and how does it help with the performance of a web application?

Three shaking is a technique used in JavaScript module bundlers, like Webpack or Vite, to remove unsued code from the final bundled output.

Main benefits innclude:

  1. Reduced Bundle size: removing unused code reduces the size of the JavaScript bundle sent to the client, improving load times and reducing bandwidth usage.
  2. Improved Performance: smaller bundle sizes can lead to faster parsing and execution times, resulting in improved performance and responsivenness of the web application.
  3. Better Resource Utilization: Developers can write modular code without worrying about unused dependencies bloating hte final bundle size.