avatarVitalii Shevchuk

Summary

This context provides a cheatsheet for frontend interviews, covering topics such as web knowledge, web performance, DOM, HTML, JavaScript, and design patterns.

Abstract

The article is a comprehensive cheatsheet for frontend interviews, focusing on various topics that a frontend engineer should be familiar with. It begins with an introduction to the purpose of the cheatsheet and then dives into different sections, including web knowledge, web performance, DOM, HTML, JavaScript, and design patterns. Each section provides concise explanations and examples of key concepts, such as caching, HTTP/2, security, critical rendering path, event delegation, mixins, factories, singletons, and MVC/MVVM patterns. The cheatsheet aims to help frontend engineers prepare for interviews and improve their understanding of frontend concepts.

Bullet points

  • The cheatsheet covers essential frontend topics for interviews, including web knowledge, web performance, DOM, HTML, JavaScript, and design patterns.
  • Web knowledge section includes caching, HTTP/2, and security concepts.
  • Web performance section discusses critical rendering path, reflow, preload/preconnect/prefetch/prerender, rendering performance, workers, and image optimization.
  • DOM section covers elements, manipulation, document fragment, and event delegation and bubbling.
  • HTML section includes semantic elements, accessibility, and responsive web concepts.
  • JavaScript section covers this, closure, inheritance, asynchronous JavaScript, hoisting, currying, and higher-order functions.
  • Design patterns section covers mixins, factories, singletons, facades, MVC/MVVM, and server vs. client-side rendering.

🔥 Frontend Interview Cheatsheet That Helped Me Get Offers From Amazon & LinkedIn

If you are preparing for a frontend interview and want to quickly refresh your frontend domain knowledge, this cheatsheet will save you a lot of time.

Content

Intro

Web Knowledge

Web Performance

DOM

HTML

Javascript

Design patterns

Conclusion

You are Awesome ❤️

Learn More

Intro

Of course, there is not enough space to fit all the frontend knowledge into one article. And this is not what this cheatsheet wants to achieve. This is just a shortcut of frontend topic, that each sr frontend engineer has to be familiar with. They are frequently raised in interviews and helped me to get an offer on Amazon and LinkedIn. Enjoy reading, and feel free to dive deeper by clicking on the topic link 🙌

Web Knowledge

1. Caching

  • Cache-Control: instruction of request and response cache;
  • Etag: <cache_id>check if the resource was updated by comparing <cache_id>, if not — update the cached version;

2. HTTP/2

Pros:

  • Multiple HTTP connection calls (HTTP/1 supports only 6);
  • A server can push an event to a client;
  • Compress headers;
  • More secure

Cons:

  • Server push can be abused;
  • Can be slower if LB (Load Balancer) supports HTTP/1 and server HTTP/2

3. Security

  • Transfer-Encoding — defines how to encrypt body: chunked, gzip;
  • Access-Control-Allow-Origin (Cross-Origin Resource Sharing — CORS) Defines a list of domains that can access the API of the origin domain;
  • JSONP — run script to access cross-domain data (old browser);
  • X-Frame-Options — Prevent clickjacking from iframe;
  • Cross-Site Request Forgery (CSRF). Attack: user has a session (logged in), attacker creates link, user clicks on the link and performs the request, attacker steals user session. Prevent: captcha, log out from visited site;
  • Content-Security-Policy — prevent from execution harmful code;
  • X-XSS-Protection — Enable XSS protection for old sites;
  • Feature-PolicyDisable not needed Browser features;
  • Referrer-Policy — when there is a link to another website from your site, by clicking it will send the URL of origin which can contain some sensitive data (user id, session);
  • Don't allow the user to input any HTML innerHtml ;
  • Use UI frameworks, keep node_modules updated, and limit of usage 3rd party services;

Web Performance

1. Critical Rendering Path — steps browser makes to paint the page. The steps are:

  • DOM — browser compiles the Document Object Model;
  • CSSOM — browser compiles the CSS Object Model;
  • Render Tree — browser combines DOM and CSSOM to render the tree;
  • Layout — browser computes the size and position of each of the objects;
  • Paint — browser converts the tree into the pixels in the screen;

Optimize CRP:

  • Optimize the order of sources — load critical resources as soon as possible;
  • Minimize the number of sources — reduce the number, load async;

2. ReflowBrowser recalculates the position and geometries of the elements after rerender.

Optimize Reflow:

  • reduce DOM depths;
  • avoid long CSS selectors, minimize rules;

3. preload, preconnect, prefetch, prerender

  • preloadloads high prior sources that need to be loaded faster<link rel="preload"> ;
  • preconnect If some resources are required to accelerate handshake, use<link rel="preconnect">to reduce latency;
  • prefetch — loads low prior resources and cache <link rel="prefetch">;
  • dns-prefetch—reduce latency of resolving domain names before resources get requested <link rel="dns-prefetch">;
  • prerender — similar to prefetch + caches whole the page <link rel="prerender"> ;

4. Rendering Performance

JS:

Style:

  • reduce the complexity of selectors;
  • Reduce the number of elements on which style calculation must be applied;

Layout: (how an element is positioned and sized)

Paint: (draw pixels: color, shadows; layout changes trigger repaint)

5. Workers

6. Image optimization

Format:

  • if animation — use <video>instead gif
  • if high details and resolution — PNG
  • if geometry shapes — SVG
  • if text logo — use font text
  • if photo — JPEG

Compression:

  • SVG — use optimizer (like SVGO), use gzip;
  • WebP — use optimized image format for Web;
  • Remove metadata attributes from SVG tag;
  • Use Sprites;

Cache and Lazy Load:

  • Use CDN for distributing static data;
  • Lazy Load images and videos — Use <img loading="lazy"/> or libraries like lazysizes;

DOM

1. Elements

  • selector: getElementById, getElementByTagName, querySelector, querySelectorAll;
  • navigation: children (elements): childNodes (nodes) , firstElementChild, lastElementChild, parentElement, previousElementSibling, nextElementSibling;
  • attributes: classList, clientHeight, clientWidth, childElementCount, setAttribute(attrName, value) removeAttribute(attrName) removeAttribute(attrName) ;

2. Manipulation

createElement(‘div’), append, prepend, el.cloneNode(true), remove(), insertBefore(newNode, beforeNode), insertAfter(newNode, afterNode);

3. Document Fragmentcreates a virtual copy of a document, that can store multiple elements. By inserting document fragment into DOM, it becomes empty, and cause only one reflow;

4. Event delegation and bubbling

  • When we emit an Event, ex. click, the event is bubbling up to <html> element through the parentElement link:
-html (bubble click)
   -body (bubble click)
        -div (bubble click)
            -p 
            -p (click)
  • Delegation is used to improve performance. Let’s say we have a structure:
-div.parent
    -p.child 
    -p.child
    -p.child

And we want to assign an addEventListener to .child , in this case, we have to attach an event to 3 elements. Instead, we can attach events only to .parent and resolve the logic.

document.querySelector(".parent").addEventListener("click", function(event) {
    if (event.target.classList.contains("child")) {
      // you logic is here
    };
});

HTML

1. Semantic Elements — clearly describes its meaning with its name to developer and browser: <article>, <aside>, <details>, <figcaption>, <figure>, <footer>, <header>, <main>, <mark>, <nav>, <section>, <summary>, <time> ;

2. Accessibility

  • Use headers <h1>,<h2>,<h3>… ;
  • Use <img alt=””;
  • Use attributetabindex=”index_position” to navigate the focus using Tab key;
  • Use roles like <ul role=”list”><li role=”listitem”>, <dialog role=”dialog”. Find the whole list here;
  • Use accesskey=”key” for creating keyboard shortcuts;
  • use attributes to describe the element:aria-label=”label_text”or aria-labelledby=”text_id”, aria-describedby=”text_id” and <label id="text_id">label_text</label> ;
  • Use color contrasts, textures;
  • Use text size;
  • Use captions in a video;

3. Responsive web

  • Add <meta viewport name=”viewport” content=”width=device-width, initial-scale=1.0" to give browser direction to scale;
  • Use <img max-width=”100%” and the image will not scale more than its size;
  • Use <picture> <source srcset=”” media=”” > to specify images for different screen sizes;
  • Responsive font sizes: em and rem ;
  • Use media queries;

Javascript

1. this

  • this is a reference to the object where a function is called;
  • default this context is window;
  • context which function will get from the place it called;
  • arrow function -> takes context which function is defined;
  • this loses context when we call one function inside another function
function Foo() {
    console.log(this); 
}
Foo(); // at this line the context is 'window'
// output: 'window'
var foo1 = new Foo(); // at this line the context binds to 'foo1'
// output: 'Foo {}'
  • Explicitly assign the context of this : foo1.apply(context, arrayOfArgs), foo1.call(context, arg1, arg2, …), var foo2 = foo1.bind(context, arg1, arg2, …)— returns an instance of function with given context;

2. Closurefunctions ability to remember and access scope even if was called from another scope (function return function/block scope in block scope)

function a(arg1) { // arg1 scoped
    var arg2 = 0; // arg2 scoped
    return function b(){
        ++arg2;
        return arg1 + arg2;
    }
}
var foo = a(2);
foo(); // 3
foo(); // 4
var foo2 = a(4);
foo(); // 5
foo(); // 6

3. Inheritance

  • To inherit obj1 from obj2 , you can link an object to another object var obj1 = Object.create(obj2);
  • JS uses prototype inheritance. Each object has a __proto__ link. If we access any property of an object, the JS engine first checks if the object has it, if not — checks the prototype, and goes through __proto__ chain to find the property name, and then throws undefined if didn’t find;

4. Asynchronous Javascript

  • Event loop: In JS there are 3 types of memory: stack used for functions call, heap for each of the objects, queue — setTimeout. JS engine executes the function stack first. If the stack is empty, it pops the event from queue. If the event queue has another function call, it pushes it to stack and executes it again until it is empty. This is called event loop;
  • JS uses callback, promise, async-await to implement asynchronous patterns. You can read more about async JS and event loop in this article:

5. Hoisting

  • function definition moves to the top of block scope during JS compilation, then goes var ;
  • let and const are hoisted too but in the temporary dead zone;
// Code example              // After hoisting 
1. console.log('hoisting');  1. function foo(){
2. var a;                    2.    return null;
3. function foo(){           3. }
4.    return null;           4. var a;
5. }                         5. console.log('hoisting');
6. a = 5;                    6. a = 5;

6. Currying — nested functions:

function calcABC(a){
    return function(b){
        return function(c){
            return a+b+c;
        }
    }
}
console.log(calcABC(1)(2)(3));
// 6

7. Higher-order functions

  • map, reduce, filter, find
  • You can chain higher-order functions into composition
[1,2,3,4,5].map((num) => ({age: num})).filter((el) => el.age < 4);
// [{age: 1}, {age: 2}, {age: 3}]

Design patterns

1. Mixinextend the functionality of an object with the list of methods;

// Option 1
class Person{}
let Mixin = {foo(){}};
Object.assign(Person.prototype, Mixin);
let person = new Person();
person.foo();
// Option 2
let Mixin1 = {foo1(){}};
let Mixin2  = {__proto__: Mixin1, foo2(){}};

2. Factory — a class that can create one or many different objects (useful if you want to generate different mock data in Unit Tests);

personFactory.one({name: 'John'}); -> Person{name: 'John', age: 5}
personFactory.many(); -> [Person{name: 'Bill', age: 7}, Person{name: 'Anna', age: 3}]

3. Singleton — class which you can call the method directly, without creating an object;

let mySingleton = (function() {
    let instance = null;
    function init(){
        return {
           //list all the methods
           method(){}
        }
    }
    if(instance == null){
        instance = init();
    }
    return instance;
})();
mySingleton.method();

4. Facadeabstract more complex logic and wrap it in class. For example, service that stays between component and API layer:

ui component - Facade service (complex state object) - API layer (Redux);

5. MVC, MVVM — Model View Controller and Model View ViewModel.

React is MVC

  • state — Model;
  • JSX — View;
  • actions (violate — can be mixed with a view) — Controller ;

Angular is MVVM

  • component — ModelView
  • template — View (violate — not reusable)
  • properties — Model

6. Server vs Client-Side Rendering

SSR — Use SSR if a site is stable, static, SEO focused, can pay for additional servers;

pros

  • Faster page load (viewable, but not interactable);
  • Better for search engines (faster indexing);
  • Better with sites that have a lot of static content (blogs);

cons

  • More server requests;
  • Slower render to interact;
  • Full page reloads;

CSR — Use CSR if site under development, dynamic;

pros

  • Faster render after initial load;
  • Best for web app;

cons

  • The initial load can require more time

Conclusion

There is a ton of information that a developer needs to know to be confident to pass a front-end interview in big tech companies. Though the more complex rounds are made up of coding problems and system design (BTW, if you are interested in a separate article about coding problems, let’s collect 5000 claps👏), the domain of frontend knowledge is way important to dodge any type of web concept questions. Don’t forget to follow and subscribe if you learned something new today (and want to get more insights weekly). See you soon. 😉

You are Awesome ❤️

Huge respect to all these amazing people who recently joined my feed. Thank you everyone for keeping me motivated, you are the best! 🙌

Aljo, Maurício Júnior, Camilo Muñoz Hernandez, Jose Eduardo Rodriguez, Paul Smithson, Deep Patel, Zully Chumpitaz, Denis Akira, kaustubh shukla, Abi Amarulloh, Yogesh Tiwari, Maxim Porcari, AMI, Avani Arora, Diksha Naiwal, Gert Jan van Dijk, prathamesh karangutkar, mallikharjuna, Shane Healy, Carlos Inguanzo, Earl Cornet, akhila nair, Vasily, tom margraff, David Fekke, Abdullah Shabbir Mirza, Gordon Luk, Samael Saverem, Karim, DaveMartin, leidy johana llanos culma, Myat Thiha, Arhtur Fedotiev, Catalin Matei, Phao, Andy Kononenko IRONSOURCE LTD, jyoti verma, Sakam PavanKumar Reddy, nuke.

Learn more

Interview
Front End Development
JavaScript
HTML
Software Development
Recommended from ReadMedium