Skip to content

Instantly share code, notes, and snippets.

@georgebullock
Last active October 7, 2021 19:04
Show Gist options
  • Save georgebullock/d6c8bd0558f8ec31ef5797edb0bf0cc8 to your computer and use it in GitHub Desktop.
Save georgebullock/d6c8bd0558f8ec31ef5797edb0bf0cc8 to your computer and use it in GitHub Desktop.
Frontend Interview Questions

FRONTEND INTERVIEW QUESTIONS

1 - Which version control systems are you familiar with? How do you share code between projects in a lossless way?

I'm familiar with git and subversion.

I know of three options for sharing code between projects:

  • Cut and paste - Share code manually. Low coupling. High maintenance.

  • Versioned Packages - Each project is versioned and made available as a package. Increased coupling. Maintenance (i.e. versioning) is critical.

  • Monorepo - All code for all projects in one repo. High coupling. High maintenance.

2 - Name four ways to decrease page load.

  1. Create segmented (e.g. device, network) performance budgets and set goals for key variables like JS payload, image payload, time to first load, etc.
  2. Reduce file sizes:
    1. Image compression
    2. File minification
  3. Reduce HTTP Requests:
    1. Bundle your modules
    2. Use image sprites
  4. Split code and deliver it on demand
  5. Cache assets locally
  6. Deliver assets via CDN
  7. Avoid redirects
Additional Resources:

3 - What does CORS stand for and what issue does it address?

CORS is an acronym for Cross-Origin Resource Sharing

CORS addresses the problem that websites often require data that not hosted somewhere else (i.e. different domain, protocol, port).

By default browsers block cross-origin request made by scripts.

CORS is a protocol allowing cross-origin requests if the response includes the right CORS headers.

In other words, severs only allow outside requests machines that are on its guest list. CORS is bouncer with the guestlist. If you're not on the list, you're request are rejected.

To make CORS work, you need to configure your server to whitelist certain domains. Domains on the list can make cross-origin requests to your server.

Addtional resources:

4 - Explain what ARIA and screenreaders are, and how to make a website accessible.

ARIA stands for Accessible Rich Internet Applications.

It defines how to make websites accessible to people that are disabled (e.g. semantice markup, alt tags, aria-attributes, tab-index, high-contrast styles, etc.)

Screenreaders are tools that allow blind people to use websites via an interface that reads out loud what's on the users screen.

5 - What does a doctype do?

doctype tells the browser which version of HTML the document contains. The version of HTML determines which set of rules the browser applies when it renders the document.

6 - What are the building blocks of HTML5?

HTML5 refers to the latest version of HTML, which includes addtional elements and technologies whose purpose is to make the web more powerful and more accessible.

It includes improvements to:

  • Semantics e.g. new elements
  • Performance e.g. web workers, AJAX, history
  • Conncetivity e.g. web sockets
  • Multimedia e.g. video and audio elements
  • Device Access various APIs for touch, geolocation, etc.

7 - Describe the difference between localStorage, cookies, and sessionStorage.

Cookies, localStorage, and sessionStorage are all methods of programatically storing data in the users browsers. The main differences between them are their maturity, their max size, and their cross-session persistance.

Cookies are the most mature form storing data on users machines. They allow you to store small amounts of information (a few KB) for a defined period of time.

Local Storage is a relatively new method of storing information on users machines. It allows you to store much data than cookies or session storage (the amount is browser dependent). Like cookies, local storage is persistent across sessions.

Session storage is effectively local storage without cross-session persistence. Once the session ends, the storages is deleted.

8 - What are data-attributes good for?

Data attributes allow you to add additional information to your markup.

For example, JavaScript hooks and CSS scoping; instead of using classes and id's for hooks and scoping, you can use data-attributes.

Also, if there is some piece of info that should live in the DOM (e.g. the result of some calculation), data-attributes are an alternative place that data can live.

9 - What kind of things must you be wary of when designing or developing for multilingual sites? How do you serve a page with content in multiple languages?

Localization (l10n):

Refers to methods of adapting content to the local environment

  • Translation
  • Proper font encoding
  • Date, time, number representations
  • UI customiation (layout, colors)
  • Legal compliance

Localization Basics

  • Use lang attribute in document head
  • Use UTF-8 encoding
  • Web Open Font Format (WOFF / WOFF2)
  • Cosnider layout in terms of RTL
  • Consider spacing in terms of translation (e.g. DE has longer words)
  • Use Gregorian calendar
  • Use UTC for time
  • Use hreflang for each multiligual subpage (SEO optimization)

Internationalization (i18n):

Designing for convenient localization

  • Content and view separation
  • Parametrized templates

Approaches to Internationalization

  1. Separated instances (unique app for each market)
  2. Shared content w/dynamic language switching (e.g. global page w/local subpages)
  3. Machine translation. Natuaral Language Processing does translations on the fly.

Multilingualizm (m17n):

Combines localization and internalization to create systems that support multiple countries / regions specific.

  • Global gateway
  • Language or region selection
  • Automatic translation
  • Regional setting and geolocation detection

Other Technical Considerations:

  • Hardware
  • Connections speed
  • Browser popularity
Additional Resources:

UTF stands for Uniform Transformation Format. It's a method to standardize the digital representation of characters. It covers every major alphabet in the world and emoji. Every character receives a number in the format U+0639 that's how browsers and other word processers translate bits into characters humans can read.

10 - What is progressive rendering?

Progressive rendering refers to methods of improving page performance by deliberately augmenting how the browser renders content.

In short, it combines the benefits of client-side rendering and server-side rendering to create a solution that can deliver better UX by ensuring that users see the most important content as quickly as possible and less critical content rendering is deferred.

Common methods of progressive rendering include:

  • Streaming / Progressive HTML rendering
  • Lazy loading images
Additional Resources:

11 - Explain how this works in JavaScript. How does this work in classes versus functions?

It's a property of the execution context. It's value depends on the execution context:

In the "global" context it either refers to the Global Object or the Window object.

In the context of a function, the value this depends on how the funtion was called:

  1. Case 1: Basic Function Call
    • this points to the Global Object / Window Object
  2. Case 2: As a proprty on an object
    • this points to the object (the left of the dot rule)
  3. Case 3: With bind(), call, or apply
    • this refers to the object passed to bind(), call, or apply
  4. Case 4: With the new keyword
    • this refers to the object created when the constructor function is called

12 - Describe event bubbling and event capturing.

Event Bubbling:

Refers what happens when a DOM event occurs. It travels up the DOM running all the handlers on itself, and its ancestors, all the way up the DOM to the html element.

Some events bubble by default, some don't. If they don't bubble you can make them bubble by setting the useCapture parameter to true. Then you can capture events that don't bubble automatically (e.g. focus).

Event capturing is the inverse of event bubbling. Instead of the event propogating from innermost element to the outermost, it propogates from the outermost element to innermost. The use capture mode, you need set the third argument to document.addEventListenter() i.e. useCapture parameter to true.

13 - Explain variable hoisting.

Variable hoisting refers to how JavaScript handles variable declarations inside of function calls (or the Global scope).

All variable declarations are hoisted (i.e moved to the top of) of the variables scope.

The practical significance of "hoisting" is that it allows you to call functions before your define them.

Hoisting 'Gotchas':

  1. Variable hoisting only works with variables defined using the var keyword.
  2. If you try and use a variable declared with var before it's defined, it's value will be undefined.
  3. Variables declared with let and const are hoisted.
  4. If you try and use a variable declared with let or const before it's declared, JavaScript will throw a Reference error.
  5. In strict mode Javascript prevents declaring variables before they are used

Variable Declaration Notes:

  • Undeclared variable declaration's implicitly create 'global' variables.
  • Variable declarations are hoisted, but their values are not:
// This declaration...
function logMessage() {
    console.log(message);
    var message = 'Hello user';
}

// ... is transformed into this at runtime

function logMessage() {
    var message;
    console.log(message);
    message = 'Hello user';
}

14 - Explain the difference between:

function Animal() {}

var animal = Animal()
var animal = new Animal()

var animal = Animal() contains a function call. When the function is called, the code inside runs and that's it.

var animal = new Animal() contains is a function call, too. The difference is that when you call Animal with the new keyword in front of it a few things happen:

  1. A new object is created (let's call it "New Object")
  2. this inside Animal is set to new New Object
  3. New Object is prototype linked to new Animal (which is prototype linked to some other object all the way up to the Global/Window object)
  4. new Animal returns this / New Object by default unless you define it to return something else.
New Keword Diagram

new-keyword-diagram.jpeg

e2cce3396a601ffbbe8611f07151eb14.png

15 - What’s the difference between host objects and native objects?

"Native Objects" are objects defined by the JavaScript spec. All other objects are "host objects."

16 - What’s a typical use case for anonymous functions?

Callback functions. A second example - IIFEs.

It's good practice to name your callbacks so their names show up in the stack trace, which can make debugging easier. The tradeoff is you can't use arrow functions and take advantage of this being bound to it's closest enclosing context.

17 - Explain how JavaScript prototypal inheritance works.

JavaScript's inheritance model can be described as Objects Linking Other Objects (OLOO). You could visualize via a tree diagram.

At the top of the hierarchy is either the Global object (in node.js) or the Window object (in the browser).

All "native" objects inherit the properties of the Global / Window object by default via a hidden property called prototype.

You can can create new object that is "prototype" linked to another object. The new object will inherit all the properties of the original object.

The most common way to create a new protoype linked object is to declare a function and call that function with the new keyword. In JS jargon, the declared function is called a "Constructor" or "Constructor Function". Calling a constructor function creates a new object inherits all the properties on the constructor function's object.

Alternatively you can creat objects using Object.create() which allows you to create with the prototype of your choice.

The practical significance of the all this boils down to the following facts:

  • JavaScript doesn't support classes. OOP in JavaScript is really OLOO
  • When you run code JavaScript will look for all the properties on the current context's prototype. If it doesn't find it there, it will recursively look up the missing property on the prototypes of all the object linked to object that's executing until it finds the property. If it doesn't find the propery on any objects all the way up to the Global / Window object, then JavaScript will throw and reference error.

It's important to beware of the overwriting object properties via "shadowing."

18 - What is a closure, and how/why would you use one?

In JavaScript a closure is a term for describing how functions declared inside other functions can "remember" the proprties of the outer functions scope.

That means you can define an inner function inside an outer function, call the outer function and assign it to a variable, then call the inner function via the variable and it will have access to all the properties that were in the outer function's scope.

This allows you to do cool things like create a group of related functions and give them a common namespace.

19 - What’s the difference between null and undefined?

null literally means there is nothing there. undefined means there is something there, but it hasn't been defined yet.

20 - What is the difference between == and === ?

== returns true if two values are equal.

=== returns true if two values are both equal and they refer to the same object.

21 - What is Webpack? What problems does it solve?

Webpack is a module bundler. It takes many files and, via it's core and an ecosystem of plugins, transforms into one or more files.

Webpack allows developers to write break their JavaScript up into 'modules' (i.e. individual files) and avoid having to load each file via a script tag.

22 - Have you ever used a front-end framework or library? Which one?

I have used two frontend Frameworks. React and Veams.

Veams is framework for rapidly building HTML prototypes. It had CLI tool that allowed you to quickly scaffold projects with customized dependecies. It had a component class that had lifecycle hooks and was connected to a pub/sub implemnetation for communication between components It also came with a library of components, handlebars for templating, JSON objects as the backend, and several other features/helpers that made it easier to get started developing quickly and solve typical problems.

It was a good tool, but it was outdated, had a long learning curve, and the documentation was not particulalry good.

23 - Why is it called a Ternary operator; what does the word Ternary indicate?

Ternary operator is syntax for writing a conditional statement that returns one of two expressions (one expression when the condition is true and one when it's false)

It's called the Ternary operator because it's three-part contstruct (one condition and two expression):

const result = condition ? expression1 : expression2

24 - What tools and techniques do you use debugging JavaScript code?

For less difficult problems, I just use console.log(). For more difficult problems, I use a combination of the debugger and Chrome Dev Tools. In dev tools, I use breakpoints often, and occasionally, I watch variables.

What "Watching" Variables Means: It is possible to watch expression and variable values while debugging. On every breakpoint, each expression from the watchers list will be evaluated in the current context and displayed immediately before the breakpoint's source code listing.

25 - How do you debug JavaScript code that runs on the server, e.g. NodeJs?

You use the inspector, which includes the debugger statement. You can either run your script using the inspect flag or you can use an inspector client.

Inspector clients are the way to go because they are often built into familiar tools and offer a more visually rich degugging experience.

Popular options include node-inspect, Chrome (my choice), VSCode, and WebStorm

26 - What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?

Advantages:

  • Use latest features now (e.g. Babel)
  • Reduce bugs (e.g. Flow, TypeScript)
  • Increase speed via terser syntax (e.g. CoffeeScript)

Disadvantages:

  • Learning curve
  • Configuration
  • Maintenance (upgrading)
  • Less future proof

27 - Given this code, how would you implement the duplicate function?

Question:

// make this work
duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5]

Solution

const duplicate = (array) => {
	return array.concat(array);
}

28 - Can you give an example of a curry function and why this syntax offers an advantage?

A curry function is a form of HOC (i.e. a function that takes a function and returns a new transformed function without mutating the original functions).

You can use it to build up a return value via a discrete set of arguments and return a "complete function" (all properties are supplied) or a "partial function" if a non-required property is not available

Additional Resources:

29 - Can you give an example of destructuring an object or an array?

// Destructuring Assignment Object
const user = {
  name: "George",
  profession: "Frontend Developer",
  hobbies: ["sprinting", "photography", "growth"]
};

const { name, profession , hobbies } = user;

// Destructuring Assignment Array
const shoppingList = ['eggs','milk', 'steak', 'broccoli', 'cheese'];

const [item1, item2, item3, item4, item5] = shoppingList;

// 1. Add destructuring Object via ...rest example
// 2. Add destructuring Array via ...rest example

Source: https://javascript.info/destructuring-assignment

30 - Who invented JavaScript and why is it called JavaScript?

JavaScript was invented by Netscape and Brenden Eich in the mid 90s. It's was origianlly called LiveScript, but Netscape renamed it to JavaScript because, at that time, Java was the hot new languange and Netscape wanted to take advantage of Java's success.

31 - What is the difference between these two functions?

// What's the difference?
const sayHello = name => console.log(name)

function sayHello(name) {
 console.log(`${name}`)
}

const sayHello = name => console.log(name) is a function expression. The variable 'sayHello' is hoisted, but its assignment remains in the place where the 'sayHello' was declared. As a result, you can't call 'sayHello' before it's declared.

function sayHello(name) {
 console.log(`${name}`)
}

The above ☝️ is a function declaration. Their declarations are hoisted. As a result you can call them before they are defined.

32 - Why and when might you want to create static class members?

Static class members are properties that exist on a class itself as opposed to instances of the class. In fact, they are not callable on instances of the class.

Static class members are often used for class utility and factory methods.

Notes:

  1. This inside a static class method is the class
  2. Static methods and static properties are distinct things

Example:

The following example demonstrates several things:

  1. How a static method is implemented on a class.
  2. That a class with a static member can be sub-classed.
  3. How a static method can and cannot be called.
class Triple {
  static triple(n = 1) {
    return n * 3;
  }
}

class BiggerTriple extends Triple {
  static triple(n) {
    return super.triple(n) * super.triple(n);
  }
}

console.log(Triple.triple());        // 3
console.log(Triple.triple(6));       // 18

var tp = new Triple();

console.log(BiggerTriple.triple(3));
// 81 (not affected by parent's instantiation)

console.log(tp.triple());
// 'tp.triple is not a function'.

33 - What are the differences between variables created using let, var or const?

The main differences come down to four things:

  1. Scoping
  2. Reassignment
  3. Redeclaration
  4. Hoisting
Type Scoping Reassignment Redeclaration Hoisting
var global block allowed
let only block allowed not allowed not defined
const only block not allowed not allowed not defined

const must be initialized at declaration. That's not a requirment for var and let

Updating the properties of object's declared with const is allowed (I'm guessing that includes object literals, arrays, and functions)

34 - What happens when you go to a website? What’s a DNS?

DNS is like a phonebook for the internet. DNS servers translate domain names like "georgebullock.dev" into IP addresses so that browsers can load content.

Steps when you go to a website

  1. Browser looks up the domain name via DNS server
  2. DNS translate the domain name to an IP
  3. The browser opens a connection and tries to reach the server at the IP address
  4. If the browser can find the server via IP and connect to it, then it will request the resource at that endpoint.
  5. If the server is on the guest list it will approve the request for the resouce
  6. Your browser will get resource and render it on your computer

35 - What is the V8 Engine? Who uses it?

The V8 engine is a JavaScript compiler used by Google Chrome, node.js, and Electron

It's basic structure is a heap for managing memory and a stack for handling function calls.

Via Wikipedia: V8 compiles JavaScript directly to native machine code using just-in-time compilation before executing it. The compiled code is additionally optimized (and re-optimized) dynamically at runtime, based on heuristics of the code's execution profile. Optimization techniques used include inlining, elision of expensive runtime properties, and inline caching. The garbage collector is a generational incremental collector.

36 - What does $ in JavaScript code refer to?

By itself, it refers the unicode number U+0024 (i.e. a dollar sign).

It's also quite common to declare $ as a variable and assign JQuery to it.

37 - Explain the difference between layout, painting, and compositing.

Layout - Refers to how the browser calculates the size and position of elements after it processes stylesheets

Painting - Refers to how the browser renders actual pixels on the screen for everything that is visible. Usually done in layers.

Compositing - Refers to how the browser organizes the painted layers to make sure they are brought together correctly.

38 - What are some ways you may improve your website’s scrolling performance?

  1. Create a performance budget for scrolling
  2. Use DevTools to measure scroll performance
  3. Action: Use "cheap" styles (use less transitions, animations, box shadows)
  4. Reduce actions that cause repaints and reflows (use less "expensive" operations like offsetTop that are triggered a lot)
  5. Debounce scroll events (requestAnimationFrame)

39 - What is the output of the following code?

let fs = require('fs');

console.log('1');

fs.readFile('test.txt', 'utf8', function(error, data) {
 if (error) {
 throw error;
 }
 console.log('2');
});

console.log('3');

It will log "1", then "3", and then "2" if readFile doesn't return an error. Why? Because fs.readFile is an async function. That means it finish executing before logging "2", the program will continue running, and later when fs.readfile is done with its job, the callback function will be called and "2" will be logged.

40 - What is the event loop in JavaScript and what does it do?

The Event Loop moves async task callbacks from the Task Queue to the Call Stack after the callback's async task is finished and the stack is clear.

41 - What excites or interests you about coding?

  1. For me coding was the missing link between having business ideas and building an MVP to validate them. I'm still not there yet, but I'm getting closer. Someday I'm going to make a move. So, for me, coding is freedom. It's the freedom to have not only have an idea, but also having the skills to bring it to life on my own.

  2. Coding is probably as future-proof as a career as one can have in our current paradigm. So learning it, and staying sharp at it, is job security.

  3. A mentor once told me that if I want to move up in an organization I should be as close to the heart of what the business as possible. In tech, that's coding, product, and growth. I chose coding because without it you have no product and no growth.

42 - What did you learn yesterday/this week?

I learned how to test React components the React Testing Library way. Instead of testing implementation details, the library focuses on deterministically rendering components and then asserting against the rendered value.

It's tricky because you don't things like state and props directly like I imagined. I'm still wrapping my head around this render, query, assert pattern.

43 - Talk about your preferred development environment. Which Operating System, IDE, and Terminal do you use and why those in particular?

My preferred environment is a fully-loaded (processer, ram, storage) Macbook Pro 2015. Why? It was the last great Macbook model). Also a lot of software doesn't support Windows and Linux.

Naturally, I run OSX. Why? It's the default mac OS

I use iTerm with Oh My Zsh as my terminal. Why? It has a bunch of features and plugins that make file navigation and entering commands easier.

My preferred IDE is VSCode. I was Webstorm guy, but VSCode has a great ecosystem of extensions, it works, and it's free. I could justify paying Jetbrains 84 bucks when I could use VSCode and save the money.

44 - If you could master one technology this year, what would it be? How would you go about mastering that skill?

As opposed to a single technology, I'm focusing on mastering the React ecosystem.

My plan is to:

  1. Get a React job and use it to master the fundamentals
  2. On the side I will build a set of side projects to learn advanced concepts
  3. Once I have a firm grasp of the most key concepts and ideas, I want to teach someone else what I learned
  4. From there I just need to stay up to date with changes to the core API and thr surrounding ecosystem.

45 - How did you handle the last disagreement with your direct boss? How did it resolve? Would you give me your boss’s number to check their side of the story?

S: Working on Hyundai. Design had some ridiculous requirments considering out browser matrix and accessibilty requirments.

T: I needed to build a tab-containe with ridiculous requirments

A: I talked to my boss and the designer. Voiced my concerns. Designer made some small compromises, but I was forced to implement the thing.

R: I got it done and tried to avoid working that designer.

46 - What resources, forums, or tools do you use to learn about the latest front end development and design trends? Any favorites and why?

I subscribe to a bunch of newsletters. I read Medium articles. I read documentation. I do tutorials

  • I like Go Make Things for short practical tutorials
  • I have subscription to educative for premium tutorials
  • Stackshare is great for learning about new tools
  • Aligator IO, Dev.to, Scotch.io, Codeburst, and Medium for curated articles.

47 - If you joined on a project and they [the dev team] used tabs and you used spaces, what would you do? Would you try to convince the team to use spaces or would you join the herd and use tabs?

I wouldn't try and convince them of anything. I'm not married to any particular formatting rules. I will just do whatever the teams is already doing unless. Also with tools like Prettier, Husky, and Lint Staged this should be a non-issue. People can use whatever formatting they want and will be normalized when they make commits.

48 - Can you describe your workflow when you create a web page? What are the first five steps you take when creating a new project?

Right now I'm focused on building SPAs. So my process for building a page is:

  1. Review the design mock
  2. Break the mock up into components
  3. Build static versions of the components w/test
  4. Wire up the static components
  5. Determine which components have state
  6. Determine where state should live
  7. Add state
  8. Add inverse data flow via callbacks
  9. Setup e2e tests
  10. Refactor

49 - What is a recent technical challenge you experienced and how did you solve it?

Situation: I was working on small React project. I wanted to use it as a code sample.

Task: My task was to implement unit testing with Jest and RTL, but I don't have a lot of experience with either tool and I never used them in the context of React

Action: I burned a couple of hours reading the docs. From them I got a lot details, but I still didn't feel like a had a good conceptual overview. So I searched for a well-written article and found exactly what I was looking

React tests are all about arranging tests, taking action, and then asserting. Arranging is about getting your component rendered and setting up queries. Acting is about taking some action that is deterministic. Then you just need to assert against the values returned by your actions.

Result: Once I had that overview, I was able to develop a template for structuring my tests and used that to successfully add tests to my project.

50 - What actions have you taken on recent projects to increase the maintainability of the code? Any particular programming paradigms you like such as functional programming or test-driven development?

I'm including testing in all my projects from day one.

I'm feeling Kent Dodds approach to testing-trophy approach to testing.

It's a fresh take on how to invest your testing budget that takes the contemporary methods and tools of frontend into account.

I'm curious about functional programming. I like it's promise of having less bugs as a result of relying of composition of pure functions.

51 - What is SSL/TSL and how does the SSL/TSL Handshake work?

Additional Resources:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment