This file contains a number of front-end interview questions from the original repository and answers I answered.
This repository is not to make the answers complete with people. This is to fill my personal answers to the original questions. Therefore, I am afraid I do not merge others' answers, and any PR concerning it will be silently closed.
The questions and some of its contents are from the original repository. If interested in getting involved, it would be the right place.
- General Questions - Answers
- HTML Questions - Answers
- CSS Questions - Answers
- JS Questions - Answers
- Testing Questions - Answers
- Performance Questions - Answers
- Network Questions - Answers
- Coding Questions - Answers
- Fun Questions - Answers
I studied about a Node.js ORM called Bookshelf.js and Express middleware implementation. I also solved some problems in Project Euler using Haskell, in which I am currently interested
I'm generally interested in quite everything about coding. Nowadays I'm especially fascinated by Haskell, one of the most beautiful languages I've ever experienced.
Also I like to create tools and services I and many others can be helped by and enjoy using.
Recently I worked on building a web service and we needed to write test cases for APIs of it. When writing a test case, it needs several database entities which will be used in the test case, and it is really a pain to write all the insertion code for the database and cleanup at the end.
To resolve the problem, I implemented concepts called 'state' and 'environment'.
'State' refers to a database instance which a session contains. 'Environment'
helps the 'state' manage its own entities. With the concepts, entities can be
created and managed easily in each test session and also cleaned all together
with the cleanup
method implemented in a state instance.
What UI, Security, Performance, SEO, Maintainability or Technology considerations do you make while building a web application or site?
- UI: I like minimal UI which contains only what it should. I believe it results in the better user experience, as a user knows what to do intuitively.
- Security: I always try to make both frontend and backend secure, concerning CSRF, XSS, etc.
- Performance: I consider space and time complexity for the algorithms and logics I use and write.
- SEO: Set meta tags for search engines and consider and consider server-side rendering for SPA.
- Maintainability: Try to keep the source code consistent and make objects immutable. Use statically typed languages such as TypeScript. Use CI with tests and lints.
- Technology: I like to learn new technologies, but if the project is in production, I would consider using technologies which is well-documented and widely used.
I like to work in terminal shell environments. For the time being, my favourite dev environment are like below:
- OS X
- iTerm2
- Tmux
- Vim
Nevertheless, I don't want to say they are the silver bullets for everything. I always try to find the best environment for each language and requirement.
Git. Not really familiar with others, but at least have experience of Subversion and Mercurial too.
I usually use Node.js to build a web page, so will describe the workflow with it.
- Decide a CSS preprocessor. I may consider using SCSS, but Less and Stylus are also viable options.
- Decide a HTML template engine. I may go with Pug(formerly Jade).
- Decide a JavaScript preprocessor or other languages being compiled to it. I may go with TypeScript or ES6 with Babel.
- Decide a task manager. I recently like to just use NPM scripts instead of using huge task managers like Gulp or Grunt.
- Write tests and make them fail.
- Write app code and check the tests succeed.
- Set CI.
- Publish the code and check a task in CI succeed.
Use a CSS preprocessor to nest them with @import
statements in class names
for each stylesheet, and merge them into a built file. In production, minify
the built file with a CSS minifier.
Progressive enhancement is a way to implement a web page where basic features, which are supported by most environments, are implemented first and then progressively enhance them for advanced environments.
On the other hand, graceful degradation is an opposite. The advanced features are freely implemented at any time, and additional works are done to support the environment where the features don't work well.
Minimise CSS and JavaScript using minifier(or uglifier), archive them using gzip, use separated file servers, use CDN, etc.
It depends on browser implementations. Usually 6 to 8 in the modern browsers, and less in the old browsers.
When we use several subdomains pointing the same domain, we can increase the concurrency level of the download.
- Use minifier and gzip to decrease the page size - actual
- Show spinner or progress bar - perceived
- Preload the page before actually loading it using libraries like InstantClick - both actual and perceived
- I would use tabs because it is the convention used for the project.
- Introduce a linter or other scripts to ensure indentations are consistent
- Use a tool like EditorConfig to configure editors team members are using automatically
<div class='slide-page'>...</div>
<div class='slide-page'>...</div>
<div class='slide-page'>...</div>
html, body, .slide-page {
width: 100%;
height: 100%;
}
.slide-page {
position: fixed;
top: 0;
left: 0;
display: none;
}
.slide-page:first-child {
display: block;
}
window.addEventListener('click', () => {
document.querySelector('.slide-page').remove();
});
Haskell. Haskell really helps developers a lot to perform much better, even though they don't really use Haskell directly because through learning Haskell, we can have better understand for other languages as well. It has been, and will be a well-designed language and many other languages have been adopting functional concepts from it and I would say it is fascinating and valuable language for every developer.
Standards describe how a thing does and should work. It is extremely important especially in software, because the thing can be used by many people for different perposes. For example, there are several engines for JavaScript including V8, JavaScriptCore, Rhino, etc, and if there is no standard for the language, developers and users cannot feel ensured when doing something with it.
Standards bodies, in the same manner, do a key role to form a standards and are essential in everywhere including both software and hardware.
It is caused when content is loaded before styles are applied to the content. It happens when style tags are placed after other content, or applied asynchronously, for example, by scripts.
To avoid FOUC, the styles should be placed in order that they can be loaded
and applied in the same rendering process as HTML elements do. The easiest way
is to place them in the head
, and avoid applying styles by scripts at the
first load.
They are for accessibility. To make a website accessible, we should try to
follow the usage of HTML elements, for example, h1
for headers and section
for sections. Also it's good to take care of using visual contents, such as
not forgetting to add an alt
attribute to img
tags.
- pros: They use GPU, so they are CPU-efficient. Don't consume JavaScript event loops.
- cons: Hard to handle, as CSS doesn't contain logics. Not supported in old browsers.
Opposite to CSS animations
CORS stands for cross-origin resource sharing. There could be situation where some resources should be allowed from sources having different origin. CORS is a standard to enable cross-site HTTP requests for:
- AJAX API call
- Web Fonts
- WebGL textures
- Image/video frames drawn to a canvas using drawImage
- Stylesheets
- Scripts
It specifies which markup standard the page is using. With the information, the browser determines how to render the page according to the page's source code.
They are modes used by browser rendering engines. In the standards mode, the engine will render a page as HTML and CSS specifications specify. The quirks mode is to render legacy pages written before these standards are fixed. The legacy pages contain non-standard behaviours emulated in old browsers such as Internet Explorer 5 or Navigator 4.
We can enforce browsers to use standards mode with a <!DOCTYPE html>
tag.
Not answered yet
IE < 8 will show a download dialog for the pages, instead of rendering them properly.
Use lang
(or xml:lang
for XHTML) in tags. Also metadata and
Content-Language
HTTP header can be used.
hreflang
attr in linkdir
attr indicating language direction, such asrtl
<meta charset='UTF-8'>
font-size
for:lang({language_code})
selectors in CSS- difference in word langth for each language
It makes HTML elements contain extra information without using non-standard attributes, or other hacks like that.
Not answered yet
Not answered yet
<script>
stops rendering process, and download and run a script.<script async>
don't stop rendering process while asynchronously downloading a script. When finishing download, it stops rendering and runs the script.<script defer>
don't stop rendering process while asynchronously downloading a script. When finishing rendering, it runs the script.
Why is it generally a good idea to position CSS <link>
s between <head></head>
and JS <script>
s just before </body>
? Do you know any exceptions?
Not answered yet
When a HTTP response is flushed multiple times, a browser doesn't wait until the whole content is loaded and renders each part earlier.
Yes. Jinja2 and Django template language in Python. Jade and EJS in JavaScript. Some more in other languages.
Not answered yet
- Resetting: Remove all the native styles provided by browsers
- Normalizing: Make the browser styles consistent
There are left
, right
and none
for float
. Each value indicates how an
element should float. When float
is set, each element will get out of its
normal flow and will be shifted to the specified direction, until it gets its
container or another floated element.
z-index
tells how elements should be stacked in a screen. Stacking context
can be formed in several situations, but most famously, by a root element and
positioned elements. In each stacking context, z-index
will be calculated
separately for its children and will stack the children in ascending order.
BFC is a part of rendering a webpage. It's used to determine from which positioning and clearing should be done. The context is created by several ways, but the most famously, by a root element, float, positioned elements.
clear:both;
overflow: hidden;
height: auto;
CSS sprite is combining multiple images into a merged one image and use CSS to render each of them properly for each element.
It's usually implemented using background: url(...) x-axis y-axis;
, or
both background-image
and background-position
.
Image replacement technique is to replace a normal text element with an image. There are many methods such as H5BP and Scott Kellum, as suggested here.
My faviourite is H5BP, as it is the simplest and most intuitive one.
Not answered yet
Not answered yet
What are the different ways to visually hide content (and make it available only for screen readers)?
Not answered yet
Yes, but not so many. I prefer Bootstrap.
Yes.
Not answered yet
@media print {
...
}
Usually about CSS selectors.
- Avoid key selector for large numbers of elements
- Prefer class and ID selector to tag selector
- Avoid redundant selectors
- Care of batching
Not answered yet
@font-face
to write my ownfont-family
@import
to import prepared web font(e.g. Google Webfonts)
- Reads right-to-left
- Check matching elements for the key(right-most) selector
- Check if the elements are matching parents for the next selectors
It's to style a part of an element, like ::first-letter
or ::before
.
They can be used to add a special symbol before a paragraph, change color of first character of a line, etc.
Explain your understanding of the box model and how you would tell the browser in CSS to render your layout in different box models.
Not answered yet
Not answered yet
Not answered yet
Not answered yet
Not answered yet
The 'C' in CSS stands for Cascading. How is priority determined in assigning styles (a few examples)? How can you use this system to your advantage?
CSS priority is determined by specificity and inheritance.
- Specificity: ID > class, psuedo-class > element, psudo-element
- Inheritence: specified value → computed value → used value → actual value
What existing CSS frameworks have you used locally, or in production? How would you change/improve them?
Not answered yet
Yes.
- Responsive: There is one basic layout, and it changes responsively to screen changes
- Adaptive: For each possible screen size, there is a distinct layout.
@media (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
...
}
Is there any reason you'd want to use translate()
instead of absolute positioning, or vice-versa? And why?
Not answered yet
When an event is fired from an element, the event will be bubbled up to its
parent nodes. However, the original element where the event occurs, called
'target', stays the same in the event object. Using the target
property, we
can always keep tracking which element actually causes an event captured by
its parent, and it can help use reduce the number of event handlers as we
sometimes don't need to add event listeners for every element.
Not answered yet
Not answered yet
Not answered yet
Not answered yet
(function foo() { })(); // or
(function foo() { }());
Not answered yet
Not answered yet
Not answered yet
Not answered yet
- Host objects: what an environment(browser, Node.js, etc) provides
- Native objects: what JavaScript provides
Not answered yet
Not answered yet
Not answered yet
When someone gives me one million dollar for doing it.
- Feature detection: directly check if a feature is implemented
if (Promise) {
let a = Promise.resolve('hello');
}
- Feature inference: infer if a feature is implemented by checking other properties
if (MozSmsMessage) {
// guess it must be Firefox...
}
- UA string: UA stands for UserAgent, which a browser natively exposes to scripts and HTTP header
console.log(navigator.userAgent); // "Mozilla/5.0 (Macintosh; ..."
Not answered yet
A JSONP response contains a callback function usually written in JavaScript, and when the response is flushed, the callback will be launched. It's more like script tag injection, rather than AJAX.
Yes.
Handlebars, Mustache, etc.
Not answered yet
It's when an event is bubbled into container elements, in the higher level of a DOM tree.
- Attribute: specified in HTML, always in the form of string
- Property: specified in DOM object, can have any type of JavaScript
Not answered yet
- document ready: when a HTML document is loaded and rendered
- document load: when a HTML document and assets in the document are all loaded and rendered
Not answered yet
Same-origin means having same host, port and protocol(HTTP or HTTPS). If a script in the different origin should be accessed, we can consider using CORS.
duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5]
let duplicate = (arr) => arr.concat(arr);
Not answered yet
Advantages
- Cannot assign a value to an undefined global variable
- Fire TypeError for not-allowed assignments
this
in a normal function refers toundefined
, instead ofglobal
In short, it secures JavaScript.
Disadvantage
- When using global strict mode and concatenating the script with other scripts not using strict mode, the other scripts can be broken.
Create a for loop that iterates up to 100
while outputting "fizz" at multiples of 3
, "buzz" at multiples of 5
and "fizzbuzz" at multiples of 3
and 5
Not answered yet
Not answered yet
Why would you use something like the load
event? Does this event have disadvantages? Do you know any alternatives, and why would you use those?
Not answered yet
Not answered yet
Not answered yet
Not answered yet
What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?
Not answered yet
Not answered yet
Not answered yet
Not answered yet
Not answered yet
Not answered yet
- Prevent regression errors
- Ensure there is no missing part to change when refactoring
- Tests can be used as specs
- Test process can be shared amongst team members
- It may or may not take more time to prototype.
For JavaScript, the basic assert
module is quite enough for simple tests.
But when it gets a big and production-level project, it is a better idea to
set a test framework. For backend, I usually use Mocha. For frontend, Mocha
can still be used with headless browsers such as PhantomJS. There are also
other famous tools like Selenium for browser tests.
- A unit test is on a small unit and checks if each unit works well.
- A functional test is on a particular feature and check if it generates a proper output for a provided input.
- An integration test checks if each part(or unit) of code works well together and results in combination functions correctly.
It is to keep source codes in a repository consistent and easy to read. Linting also prevent possible mistakes developers can make. For example, some linter provides options to check which indentation should be used(it is not actually what a linter should do though). A linter can also check if there is any used variable which hasn't been declared, or if there is any unused variable. In short, linting is a kind of static analysis.
- What tools would you use to find a performance bug in your code?
- What are some ways you may improve your website's scrolling performance?
- Explain the difference between layout, painting and compositing.
It's because browsers usually have limits on the number of concurrent downloads from a domain at a moment. So, serving assets from multiple domains can increase the concurrent level.
Do your best to describe the process from the time you type in a website's URL to it finishing loading on your screen.
When I enter a website's URL, in the transport layer, it will ask a local DNS what is the IP of the provided URL. We know the IP of the local DNS server by the DHCP protocol, when a node connects to internet and gets an IP address.
After that, a browser will try to establish a TCP connection with a server having the retrieved IP by 3-way handshake. When it establish a TCP connection, the browser will form an HTTP request containing an HTTP header and body.
After the HTTP request is sent and the server responds with an HTTP response, the browser will parse the HTTP response header and body, and will render the website. If the document contains additional assets, the browser will create HTTP requests for the assets and send them like above.
- What are the differences between Long-Polling, Websockets and Server-Sent Events?
- Explain the following request and response headers:
- Diff. between Expires, Date, Age and If-Modified-...
- Do Not Track
- Cache-Control
- Transfer-Encoding
- ETag
- X-Frame-Options
- What are HTTP actions? List all HTTP actions that you know, and explain them.
var foo = 10 + '20';
Answer: '1020'
, because of type coercion from Number to String
add(2, 5); // 7
add(2)(5); // 7
Answer: A general solution for any number of parameters
'use strict';
let sum = (arr) => arr.reduce((a, b) => a + b);
let addGenerator = (numArgs, prevArgs) => {
return function () {
let totalArgs = prevArgs.concat(Array.from(arguments));
if (totalArgs.length === numArgs) {
return sum(totalArgs);
}
return addGenerator(numArgs, totalArgs);
};
};
let add = addGenerator(2, []);
add(2, 5); // 7
add(2)(5); // 7
add()(2, 5); // 7
add()(2)(5); // 7
add()()(2)(5); // 7
"i'm a lasagna hog".split("").reverse().join("");
Answer: It's actually a reverse method for a string - 'goh angasal a m\'i'
( window.foo || ( window.foo = "bar" ) );
Answer: Always 'bar'
var foo = "Hello";
(function() {
var bar = " World";
alert(foo + bar);
})();
alert(foo + bar);
Answer:
- First:
Hello World
- Second: Throws an exception,
ReferenceError: bar is not defined
var foo = [];
foo.push(1);
foo.push(2);
Answer: .push
is mutable - 2
var foo = {n: 1};
var bar = foo;
foo.x = foo = {n: 2};
Answer: undefined
. Rather, bar.x
is {n: 2}
.
foo.x = foo = {n: 2}
is the same as foo.x = (foo = {n: 2})
. It is because
a left term is first referenced and then a right term is evaluated when an
assignment is performed in JavaScript. When foo.x
is referenced, it refers
to an original object, {n: 1}
. So, when the result of the right term, {n: 2}
, is evaluated, it will assigned to the original object, which is at the
moment referenced by bar
.
console.log('one');
setTimeout(function() {
console.log('two');
}, 0);
console.log('three');
Answer: one
, three
and two
. It's because console.log('two');
will be
invoked in the next event loop.
Pen.
It is a markdown previewer written in JavaScript with realtime preview. The preview page is updated powered by VirtualDOM of React, which means that only modified parts in the original markdown are actually updated in the DOM tree of the preview page. It's super cool(at least I believe). If interested, please look into it 😄
I personally use Tmux and Vim with several customisations. I especially recommend using CtrlP and Syntastic for Vim.
I won't describe them in detail here, but if you're using Vim, you must love them.
Many. You can find them in my GitHub page.
I like to write useful tools not only for developers, but for normal users. So many of my pet projects are about tools including markdown previewers, a input changer, etc. I also write some JavaScript packages as well.
What is Internet Explorer? Nevermind. I like the color of its logo.
I'm a fan of coffee. I usually drink cups of coffee a day, especially a working day.
I also like to drink tea and beer 🍺