0% found this document useful (0 votes)
33 views

Frontend Developer Interview Questions

This document contains interview questions for frontend developers. It covers topics like HTML, CSS, JavaScript, and frameworks. There are over 100 questions organized into chapters to help prepare for technical interviews.

Uploaded by

huyang123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Frontend Developer Interview Questions

This document contains interview questions for frontend developers. It covers topics like HTML, CSS, JavaScript, and frameworks. There are over 100 questions organized into chapters to help prepare for technical interviews.

Uploaded by

huyang123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 126

Frontend Developer Interview

Questions
Prep for the interview and get the job
you want

Alejandro Garcia
This book is for sale at
http://leanpub.com/frontend-developer-interview-questions

This version was published on 2020-08-21

This is a Leanpub book. Leanpub empowers authors and


publishers with the Lean Publishing process. Lean Publishing is
the act of publishing an in-progress ebook using lightweight tools
and many iterations to get reader feedback, pivot until you have
the right book and build traction once you do.

© 2020 Alejandro Garcia


Tweet This Book!
Please help Alejandro Garcia by spreading the word about this
book on Twitter!
The suggested tweet for this book is:
Awesome book for a tech job interview !!
The suggested hashtag for this book is #frontend.
Find out what other people are saying about the book by clicking
on this link to search for this hashtag on Twitter:
#frontend
Contents

Other Books by Alejandro . . . . . . . . . . . . . . . . . . . 1

Your Free Gift . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Who is this book for ? . . . . . . . . . . . . . . . . . . . . 10
What this book covers ? . . . . . . . . . . . . . . . . . . . 10

Chapter 1: HTML Interview Questions . . . . . . . . . . . 11


What does a DOCTYPE do? . . . . . . . . . . . . . . . . . 11
How do you serve a page with content in multiple
languages? . . . . . . . . . . . . . . . . . . . . . . . 12
What kind of things must you be wary of when design-
ing or developing for multilingual sites? . . . . . 13
What are data- attributes good for? . . . . . . . . . . . . 14
Consider HTML5 as an open web platform. What are the
building blocks of HTML5? . . . . . . . . . . . . . 15
Describe the difference between a cookie, sessionStor-
age and localStorage. . . . . . . . . . . . . . . . . 16
Describe the difference between <script>, <script async>
and <script defer>. . . . . . . . . . . . . . . . . . 17
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? . . 18
What is progressive rendering? . . . . . . . . . . . . . . . 20
CONTENTS

Why you would use a srcset attribute in an image


tag? Explain the process the browser uses when
evaluating the content of this attribute. . . . . . . 21
Have you used different HTML templating languages
before? . . . . . . . . . . . . . . . . . . . . . . . . . 22

Chapter 2: CSS Interview Questions . . . . . . . . . . . . . 23


What is CSS selector specificity and how does it work? . 23
What’s the difference between “resetting” and “normal-
izing” CSS? Which would you choose, and why? 24
Describe floats and how they work. . . . . . . . . . . . . 25
Describe z-index and how stacking context is formed. . 26
Describe Block Formatting Context (BFC) and how it
works. . . . . . . . . . . . . . . . . . . . . . . . . . 27
What are the various clearing techniques and which is
appropriate for what context? . . . . . . . . . . . 28
Explain CSS sprites, and how you would implement
them on a page or site. . . . . . . . . . . . . . . . . 29
How would you approach fixing browser-specific styling
issues? . . . . . . . . . . . . . . . . . . . . . . . . . 30
How do you serve your pages for feature-constrained
browsers? What techniques/processes do you use? 30
What are the different ways to visually hide content (and
make it available only for screen readers)? . . . . 31
Have you ever used a grid system, and if so, what do you
prefer? . . . . . . . . . . . . . . . . . . . . . . . . . 32
Have you used or implemented media queries or mobile-
specific layouts/CSS? . . . . . . . . . . . . . . . . 32
Are you familiar with styling SVG? . . . . . . . . . . . . 32
Can you give an example of an @media property other
than screen? . . . . . . . . . . . . . . . . . . . . . . 34
What are some of the “gotchas” for writing efficient CSS? 34
What are the advantages/disadvantages of using CSS
preprocessors? . . . . . . . . . . . . . . . . . . . . 35
CONTENTS

Describe what you like and dislike about the CSS pre-
processors you have used. . . . . . . . . . . . . . . 36
How would you implement a web design comp that uses
non-standard fonts? . . . . . . . . . . . . . . . . . 37
Explain how a browser determines what elements match
a CSS selector. . . . . . . . . . . . . . . . . . . . . 37
Describe pseudo-elements and discuss what they are
used for. . . . . . . . . . . . . . . . . . . . . . . . . 38
Explain your understanding of the box model and how
you would tell the browser in CSS to render your
layout in different box models. . . . . . . . . . . . 39
What does * { box-sizing: border-box; } do? What
are its advantages? . . . . . . . . . . . . . . . . . . 40
What is the CSS display property and can you give a
few examples of its use? . . . . . . . . . . . . . . . 41
What’s the difference between inline and inline-block? 41
What’s the difference between a relative, fixed, abso-
lute and statically positioned element? . . . . . 44
What existing CSS frameworks have you used locally, or
in production? How would you change/improve
them? . . . . . . . . . . . . . . . . . . . . . . . . . 45
Have you played around with the new CSS Flexbox or
Grid specs? . . . . . . . . . . . . . . . . . . . . . . 45
Can you explain the difference between coding a web-
site to be responsive versus using a mobile-first
strategy? . . . . . . . . . . . . . . . . . . . . . . . . 46
How is responsive design different from adaptive design? 47
Have you ever worked with retina graphics? If so, when
and what techniques did you use? . . . . . . . . . 49
Is there any reason you’d want to use translate()
instead of absolute positioning, or vice-versa?
And why? . . . . . . . . . . . . . . . . . . . . . . . 50

Chapter 3: Javascript Interview Questions . . . . . . . . . 52


Explain event delegation . . . . . . . . . . . . . . . . . . . 52
CONTENTS

Explain how this works in JavaScript . . . . . . . . . . . 52


Explain how prototypal inheritance works . . . . . . . . 54
What do you think of AMD vs CommonJS? . . . . . . . 57
Explain why the following doesn’t work as an IIFE:
function foo(){ }();. What needs to be changed
to properly make it an IIFE? . . . . . . . . . . . . 58
What’s the difference between a variable that is: null,
undefined or undeclared? How would you go
about checking for any of these states? . . . . . . 59
What is a closure, and how/why would you use one? . . 61
Can you describe the main difference between a .forE-
ach loop and a .map() loop and why you would
pick one versus the other? . . . . . . . . . . . . . . 62
What’s a typical use case for anonymous functions? . . . 64
How do you organize your code? (module pattern, clas-
sical inheritance?) . . . . . . . . . . . . . . . . . . 65
What’s the difference between host objects and native
objects? . . . . . . . . . . . . . . . . . . . . . . . . 65
Difference between: function Person(){}, var person
= Person(), and var person = new Person()? . . 66
What’s the difference between .call and .apply? . . . . 67
Explain Function.prototype.bind. . . . . . . . . . . . . . 68
When would you use document.write()? . . . . . . . . . 68
What’s the difference between feature detection, feature
inference, and using the UA string? . . . . . . . . 69
Explain Ajax in as much detail as possible. . . . . . . . . 71
What are the advantages and disadvantages of using Ajax? 72
Explain how JSONP works (and how it’s not really Ajax). 72
Have you ever used JavaScript templating? If so, what
libraries have you used? . . . . . . . . . . . . . . . 74
Explain “hoisting”. . . . . . . . . . . . . . . . . . . . . . . 74
Describe event bubbling. . . . . . . . . . . . . . . . . . . 76
What’s the difference between an “attribute” and a “prop-
erty”? . . . . . . . . . . . . . . . . . . . . . . . . . 76
CONTENTS

Why is extending built-in JavaScript objects not a good


idea? . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Difference between document load event and document
DOMContentLoaded event? . . . . . . . . . . . . . . 78
What is the difference between == and ===? . . . . . . . . 78
Explain the same-origin policy with regards to JavaScript. 79
Make this work: . . . . . . . . . . . . . . . . . . . . . . . . 80
Why is it called a Ternary expression, what does the
word “Ternary” indicate? . . . . . . . . . . . . . . 80
What is "use strict";? What are the advantages and
disadvantages to using it? . . . . . . . . . . . . . . 81
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. . . . . . . 82
Why is it, in general, a good idea to leave the global scope
of a website as-is and never touch it? . . . . . . . 83
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? . . . 83
Explain what a single page app is and how to make one
SEO-friendly. . . . . . . . . . . . . . . . . . . . . . 84
What is the extent of your experience with Promises
and/or their polyfills? . . . . . . . . . . . . . . . . 86
What are the pros and cons of using Promises instead of
callbacks? . . . . . . . . . . . . . . . . . . . . . . . 87
What are some of the advantages/disadvantages of writ-
ing JavaScript code in a language that compiles to
JavaScript? . . . . . . . . . . . . . . . . . . . . . . 88
What tools and techniques do you use for debugging
JavaScript code? . . . . . . . . . . . . . . . . . . . 89
What language constructions do you use for iterating
over object properties and array items? . . . . . . 90
Explain the difference between mutable and immutable
objects. . . . . . . . . . . . . . . . . . . . . . . . . . 92
How can you achieve immutability in your own code? . 96
CONTENTS

Explain the difference between synchronous and asyn-


chronous functions. . . . . . . . . . . . . . . . . . 97
What is event loop? What is the difference between call
stack and task queue? . . . . . . . . . . . . . . . . 97
Explain the differences on the usage of foo between
function foo() {} and var foo = function()
{} . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
What are the differences between variables created using
let, var or const? . . . . . . . . . . . . . . . . . . 99
What are the differences between ES6 class and ES5
function constructors? . . . . . . . . . . . . . . . . 102
Can you offer a use case for the new arrow ⇒ function
syntax? How does this new syntax differ from
other functions? . . . . . . . . . . . . . . . . . . . 104
What advantage is there for using the arrow syntax for
a method in a constructor? . . . . . . . . . . . . . 104
What is the definition of a higher-order function? . . . . 106
Can you give an example for destructuring an object or
an array? . . . . . . . . . . . . . . . . . . . . . . . 108
ES6 Template Literals offer a lot of flexibility in gener-
ating strings, can you give an example? . . . . . . 109
Can you give an example of a curry function and why
this syntax offers an advantage? . . . . . . . . . . 111
What are the benefits of using spread syntax and how is
it different from rest syntax? . . . . . . . . . . . . 113
How can you share code between files? . . . . . . . . . . 114
Why you might want to create static class members? . . 115

Keep developing your interviewing skills . . . . . . . . . . 116

About the Author . . . . . . . . . . . . . . . . . . . . . . . . 117


Other Books by Alejandro 2

Other Books by
Alejandro

Your First Tech Interview: The Questions and Unique Formula to get the Job
you want
Other Books by Alejandro 3

Your First Tech Interview: The Questions and Unique Formula to


get the Job you want¹

Up to Speed with Javascript in 59 minutes

Up to Speed with Javascript in 59 minutes²


¹https://www.amazon.com/Your-First-Tech-Interview-Questions-ebook/dp/
B08DN1BX2V/ref=sr_1_3?crid=2WMGG8O7DREFP&dchild=1&keywords=tech+interview+
questions&qid=1596198458&s=books&sprefix=tech+intervi%2Caps%2C261&sr=1-3
²https://leanpub.com/javascript-in-59-minutes/?utm_source=ebook&utm_medium=
leanpub&utm_campaign=frontendIQ
Other Books by Alejandro 4

Javascript Snippets: Secret Code Snippets used by Powerful Developers to


create Innovative Apps

Javascript Snippets: Secret Code Snippets used by Powerful Devel-


opers to create Innovative Apps³
³https://leanpub.com/javascript-snippets/?utm_source=ebook&utm_medium=leanpub&
utm_campaign=frontendIQ
Other Books by Alejandro 5

Javascript Challenges

Javascript Challenges⁴
⁴https://leanpub.com/javascript-challenges/?utm_source=ebook&utm_medium=
leanpub&utm_campaign=frontendIQ
Other Books by Alejandro 6

Appwrite Up and Running: Build High Performance cross-platform Apps


quickly with this Free unified Backend

Appwrite Up and Running: Build High Performance cross-platform


Apps quickly with this Free unified Backend⁵
⁵https://leanpub.com/appwrite-up-and-running/?utm_source=ebook&utm_medium=
leanpub&utm_campaign=frontendIQ
Other Books by Alejandro 7

Data Science Workflow for Beginners: Start your Data Science Journey into a
Successful High Paying Career

Data Science Workflow for Beginners: Start your Data Science


Journey into a Successful High Paying Career⁶
⁶https://leanpub.com/data-science-workflow/?utm_source=ebook&utm_medium=
leanpub&utm_campaign=frontendIQ
Your Free Gift
As a thank you for reading this book, I would like to give you a Free
copy of Backend Developer Interview Questions⁷
In it, you will find a list of some questions any developer could face
in an interview.
Feel free to share this gift with friends !!

Tuesday Messages

On Tuesday, I send some of my Free books to subscribers. You can


expect updates, technical articles and courses recommendations.
People tell me this content is so valuable to them that sometimes
they ask me to send info on particular subjects.
If you would like to receive the exclusive free content only for
subscribers, then you can join here: Alejandro’s Updates⁸
⁷http://leanpub.com/backend-developer-interview-questions/c/uXEicE45Ilo7?utm_
source=ebook&utm_medium=leanpub&utm_campaign=frontendIQ
⁸https://alejandro-garcia-author.ck.page/2ed39fffaf
Introduction
Congrats, if you are reading this I assume you are starting to
prepare for your next interview !!
Getting an interview is the first step towards your new life, every
developer has some interesting stories about the interview that
landed their current job, some are like a fairy tale (magical and
exciting) while others are more like a day in the battlefield behind
enemy lines.
The truth is, you have to be prepared and I’m here to help you with
that. I’ve put together a list of questions and answers for you to
start practicing your next interview. The more questions you get to
read and think of possible solutions the higher chance of success.
In no way this book guarantees you are getting these exact ques-
tions, but they are a good way for you to start building the
confidence required to go through the interview process.
I’m happy to say that some of the developers who have already read
the book have provided great suggestions to improve it, so expect
an update soon. I’ll include more questions helping you study in
the most efficient and intelligent way possible.
When I wrote “Your First Tech Interview: The Questions and Unique
Formula to get the Job you want” my intention was to provide a
guide and strategy on how to approach the interview process so at
the end your chances of getting the job are close to 99.9%.
After completing that book, I thought about writing a series of
books with additional questions. I hope all these books help you
on the path to your new career.
Introduction 10

Who is this book for ?


This book is for those developers who are artists using code to bring
to life the most beautiful applications, it’s a quick reference with
interview questions and answers for them to practice until they
achieve perfection in their interviews.
The interview panel will be trying to make a critical decision, they
need to bring onboard a new developer that will help them improve
the efficiency of their applications. Your job now is to review as
many possible questions as you can so then you ignite amazing
conversations revealing innovative ways of improving the code
base of those applications.

What this book covers ?


Chapter 1 All the HTML related questions will be discussed in this
chapter.
Chapter 2 All the CSS related questions will be discussed in this
chapter.
Chapter 3 All the Javascript related questions will be discussed in
this chapter.
Chapter 1: HTML
Interview Questions
What does a DOCTYPE do?
DOCTYPE is an abbreviation for DOCument TYPE. A DOCTYPE
is always associated to a DTD - for Document Type Definition.
A DTD defines how documents of a certain type should be struc-
tured (i.e. a button can contain a span but not a div), whereas a
DOCTYPE declares what DTD a document supposedly respects (i.e.
this document respects the HTML DTD).
For webpages, the DOCTYPE declaration is required. It is used
to tell user agents what version of the HTML specifications your
document respects. Once a user agent has recognized a correct
DOCTYPE, it will trigger the no-quirks mode matching this DOC-
TYPE for reading the document. If a user agent doesn’t recognize
a correct DOCTYPE, it will trigger the quirks mode.
The DOCTYPE declaration for the HTML5 standards is <!DOCTYPE
html>.

References

• doctype⁹
• multipage¹⁰
• doctype Multipage¹¹
⁹https://html.spec.whatwg.org/multipage/syntax.html#the-doctype
¹⁰https://html.spec.whatwg.org/multipage/xhtml.html
¹¹https://quirks.spec.whatwg.org/
Chapter 1: HTML Interview Questions 12

How do you serve a page with


content in multiple languages?
I will assume that it is asking about the most common case, which is
how to serve a page with content available in multiple languages,
but the content within the page should be displayed only in one
consistent language.
When an HTTP request is made to a server, the requesting user
agent usually sends information about language preferences, such
as in the Accept-Language header. The server can then use this
information to return a version of the document in the appropriate
language if such an alternative is available. The returned HTML
document should also declare the lang attribute in the <html> tag,
such as <html lang="en">...</html>.
Of course this is useless for letting a search engine know that the
same content is available in different languages, and so you must
also make use of the hreflang attribute in the <head>. Eg. <link
rel="alternate" hreflang="de" href="http://de.example.com/page.html"
/>

In the back end, the HTML markup will contain i18n placeholders
and content for the specific language stored in YML or JSON
formats. The server then dynamically generates the HTML page
with content in that particular language, usually with the help of a
back end framework.

References

• getting Started¹²
• language¹³
¹²https://www.w3.org/International/getting-started/language
¹³https://support.google.com/webmasters/answer/189077
Chapter 1: HTML Interview Questions 13

What kind of things must you be


wary of when designing or
developing for multilingual sites?
• Use lang attribute in your HTML.
• Directing users to their native language - Allow a user to
change his country/language easily without hassle.
• Text in raster-based images (e.g. png, gif, jpg, etc.), is not a
scalable approach - Placing text in an image is still a popular
way to get good-looking, non-system fonts to display on any
computer. However, to translate image text, each string of text
will need to have a separate image created for each language.
Anything more than a handful of replacements like this can
quickly get out of control.
• Restrictive words/sentence length - Some content can be
longer when written in another language. Be wary of layout
or overflow issues in the design. It’s best to avoid designing
where the amount of text would make or break a design.
Character counts come into play with things like headlines,
labels, and buttons. They are less of an issue with free-flowing
text such as body text or comments.
• Be mindful of how colors are perceived - Colors are perceived
differently across languages and cultures. The design should
use color appropriately.
• Formatting dates and currencies - Calendar dates are some-
times presented in different ways. Eg. “May 31, 2012” in the
U.S. vs. “31 May 2012” in parts of Europe.
• Do not concatenate translated strings - Do not do anything
like "The date today is " + date. It will break in
languages with different word order. Use a template string
with parameters substitution for each language instead. For
example, look at the following two sentences in English and
Chinese respectively: I will travel on {% date %} and {%
Chapter 1: HTML Interview Questions 14

date %} ����. Note that the position of the variable is different


due to grammar rules of the language.
• Language reading direction - In English, we read from left-
to-right, top-to-bottom, in traditional Japanese, text is read
up-to-down, right-to-left.

References

• developing multilingual¹⁴

What are data- attributes good for?


Before JavaScript frameworks became popular, front end devel-
opers used data- attributes to store extra data within the DOM
itself, without other hacks such as non-standard attributes, extra
properties on the DOM. It is intended to store custom data private
to the page or application, for which there are no more appropriate
attributes or elements.
These days, using data- attributes is generally not encouraged. One
reason is that users can modify the data attribute easily by using
inspect element in the browser. The data model is better stored
within JavaScript itself and stay updated with the DOM via data
binding possibly through a library or a framework.
However, one perfectly valid use of data attributes, is to add a hook
for end to end testing frameworks such as Selenium and Capybara
without having to create a meaningless classes or ID attributes. The
element needs a way to be found by a particular Selenium spec and
something like data-selector='the-thing' is a valid way to do so
without convoluting the semantic markup otherwise.
¹⁴https://www.quora.com/What-kind-of-things-one-should-be-wary-of-when-
designing-or-developing-for-multilingual-sites
Chapter 1: HTML Interview Questions 15

References

• custom attributes¹⁵
• non visible data¹⁶

Consider HTML5 as an open web


platform. What are the building
blocks of HTML5?
• Semantics - Allowing you to describe more precisely what
your content is.
• Connectivity - Allowing you to communicate with the server
in new and innovative ways.
• Offline and storage - Allowing webpages to store data on the
client-side locally and operate offline more efficiently.
• Multimedia - Making video and audio first-class citizens in
the Open Web.
• 2D/3D graphics and effects - Allowing a much more diverse
range of presentation options.
• Performance and integration - Providing greater speed opti-
mization and better usage of computer hardware.
• Device access - Allowing for the usage of various input and
output devices.
• Styling - Letting authors write more sophisticated themes.

References

• html5¹⁷
¹⁵http://html5doctor.com/html5-custom-data-attributes/
¹⁶https://www.w3.org/TR/html5/dom.html#embedding-custom-non-visible-data-with-
the-data-*-attributes
¹⁷https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5
Chapter 1: HTML Interview Questions 16

Describe the difference between a


cookie, sessionStorage and localStorage.

All the above-mentioned technologies are key-value storage mech-


anisms on the client side. They are only able to store values as
strings.

cookie localStorage sessionStorage


Initiator Client or Client Client
server.
Server can
use
Set-Cookie
header
Expiry Manually Forever On tab
set close
Persistent Depends Yes No
across on whether
browser expiration
sessions is set
Sent to Cookies are No No
server with automati-
every cally being
HTTP sent via
request Cookie
header
Capacity 4kb 5MB 5MB
(per
domain)
Accessibility Any Any Same tab
window window
Note: If the user decides to clear browsing data via whatever
mechanism provided by the browser, this will clear out any cookie,
localStorage, or sessionStorage stored. It’s important to keep
this in mind when designing for local persistance, especially when
comparing to alternatives such as server side storing in a database
or similar (which of course will persist despite user actions).
Chapter 1: HTML Interview Questions 17

References

• cookies¹⁸
• local and session storage¹⁹

Describe the difference between


<script>, <script async> and <script
defer>.

• <script> - HTML parsing is blocked, the script is fetched and


executed immediately, HTML parsing resumes after the script
is executed.
• <script async> - The script will be fetched in parallel to
HTML parsing and executed as soon as it is available (po-
tentially before HTML parsing completes). Use async when
the script is independent of any other scripts on the page, for
example, analytics.
• <script defer> - The script will be fetched in parallel to
HTML parsing and executed when the page has finished
parsing. If there are multiple of them, each deferred script is
executed in the order they were encountered in the document.
If a script relies on a fully-parsed DOM, the defer attribute
will be useful in ensuring that the HTML is fully parsed before
executing. There’s not much difference in putting a normal
<script> at the end of <body>. A deferred script must not
contain document.write.

Note: The async and defer attributes are ignored for scripts that
have no src attribute.
¹⁸https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
¹⁹http://tutorial.techaltum.com/local-and-session-storage.html
Chapter 1: HTML Interview Questions 18

References

• async²⁰
• script tag async²¹
• async vs defer²²

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?
Placing <link>s in the <head>
Putting <link>s in the <head> is part of proper specification in
building an optimized website. When a page first loads, HTML
and CSS are being parsed simultaneously; HTML creates the DOM
(Document Object Model) and CSS creates the CSSOM (CSS Object
Model). Both are needed to create the visuals in a website, allowing
for a quick “first meaningful paint” timing. This progressive render-
ing is a category optimization sites are measured in their perfor-
mance scores. Putting stylesheets near the bottom of the document
is what prohibits progressive rendering in many browsers. Some
browsers block rendering to avoid having to repaint elements of the
page if their styles change. The user is then stuck viewing a blank
white page. Other times there can be flashes of unstyled content
(FOUC), which show a webpage with no styling applied.
Placing <script>s just before </body>
²⁰http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html
²¹https://stackoverflow.com/questions/10808109/script-tag-async-defer
²²https://bitsofco.de/async-vs-defer/
Chapter 1: HTML Interview Questions 19

<script> tags block HTML parsing while they are being down-
loaded and executed which can slow down your page. Placing
the scripts at the bottom will allow the HTML to be parsed and
displayed to the user first.
An exception for positioning of <script>s at the bottom is when
your script contains document.write(), but these days it’s not a
good practice to use document.write(). Also, placing <script>s
at the bottom means that the browser cannot start downloading
the scripts until the entire document is parsed. This ensures your
code that needs to manipulate DOM elements will not throw and
error and halt the entire script. If you need to put <script> in the
<head>, use the defer attribute, which will achieve the same effect
of downloading and running the script only after the HTML is
parsed.
Keep in mind that putting scripts just before the closing </body>
tag will create the illusion that the page loads faster on an empty
cache (since the scripts won’t block downloading the rest of the
document). However, if you have some code you want to run
during page load, it will only start executing after the entire page
has loaded. If you put those scripts in the <head> tag, they would
start executing before - so on a primed cache the page would
actually appear to load faster.

References

• rules²³
• prevent unstyled²⁴
• critical rendering²⁵
²³https://developer.yahoo.com/performance/rules.html#css_top
²⁴https://www.techrepublic.com/blog/web-designer/how-to-prevent-flash-of-unstyled-
content-on-your-websites/
²⁵https://developers.google.com/web/fundamentals/performance/critical-rendering-path/
Chapter 1: HTML Interview Questions 20

What is progressive rendering?


Progressive rendering is the name given to techniques used to
improve the performance of a webpage (in particular, improve
perceived load time) to render content for display as quickly as
possible.
It used to be much more prevalent in the days before broadband
internet but it is still used in modern development as mobile data
connections are becoming increasingly popular (and unreliable)!
Examples of such techniques:

• Lazy loading of images - Images on the page are not loaded


all at once. JavaScript will be used to load an image when the
user scrolls into the part of the page that displays the image.
• Prioritizing visible content (or above-the-fold rendering) -
Include only the minimum CSS/content/scripts necessary for
the amount of page that would be rendered in the users
browser first to display as quickly as possible, you can then
use deferred scripts or listen for the DOMContentLoaded/load
event to load in other resources and content.
• Async HTML fragments - Flushing parts of the HTML to the
browser as the page is constructed on the back end. More
details on the technique can be found here²⁶.

References

• progressive rendering²⁷
• rendering with marko²⁸
²⁶http://www.ebaytechblog.com/2014/12/08/async-fragments-rediscovering-progressive-
html-rendering-with-marko/
²⁷https://stackoverflow.com/questions/33651166/what-is-progressive-rendering
²⁸http://www.ebaytechblog.com/2014/12/08/async-fragments-rediscovering-progressive-
html-rendering-with-marko/
Chapter 1: HTML Interview Questions 21

Why you would use a srcset attribute


in an image tag? Explain the process
the browser uses when evaluating
the content of this attribute.
You would use the srcset attribute when you want to serve differ-
ent images to users depending on their device display width - serve
higher quality images to devices with retina display enhances the
user experience while serving lower resolution images to low-end
devices increase performance and decrease data wastage (because
serving a larger image will not have any visible difference). For
example: <img srcset="small.jpg 500w, medium.jpg 1000w,
large.jpg 2000w" src="..." alt=""> tells the browser to display
the small, medium or large .jpg graphic depending on the client’s
resolution. The first value is the image name and the second is
the width of the image in pixels. For a device width of 320px, the
following calculations are made:

• 500 / 320 = 1.5625


• 1000 / 320 = 3.125
• 2000 / 320 = 6.25

If the client’s resolution is 1x, 1.5625 is the closest, and 500w


corresponding to small.jpg will be selected by the browser.
If the resolution is retina (2x), the browser will use the closest
resolution above the minimum. Meaning it will not choose the 500w
(1.5625) because it is greater than 1 and the image might look bad.
The browser would then choose the image with a resulting ratio
closer to 2 which is 1000w (3.125).
srcsets solve the problem whereby you want to serve smaller
image files to narrow screen devices, as they don’t need huge
images like desktop displays do — and also optionally that you want
Chapter 1: HTML Interview Questions 22

to serve different resolution images to high density/low-density


screens.

References

• responsive images²⁹
• srcset³⁰

Have you used different HTML


templating languages before?
Yes, Pug (formerly Jade), ERB, Slim, Handlebars, Jinja, Liquid, and
EJS just to name a few. In my opinion, they are more or less the same
and provide similar functionality of escaping content and helpful
filters for manipulating the data to be displayed. Most templating
engines will also allow you to inject your own filters in the event
you need custom processing before display.
²⁹https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/
Responsive_images
³⁰https://css-tricks.com/responsive-images-youre-just-changing-resolutions-use-srcset/
Chapter 2: CSS Interview
Questions
What is CSS selector specificity and
how does it work?
The browser determines what styles to show on an element de-
pending on the specificity of CSS rules. We assume that the browser
has already determined the rules that match a particular element.
Among the matching rules, the specificity, four comma-separate
values, a, b, c, d are calculated for each rule based on the
following:

1. a is whether inline styles are being used. If the property


declaration is an inline style on the element, a is 1, else 0.
2. b is the number of ID selectors.
3. c is the number of classes, attributes and pseudo-classes
selectors.
4. d is the number of tags and pseudo-elements selectors.

The resulting specificity is not a score, but a matrix of values that


can be compared column by column. When comparing selectors
to determine which has the highest specificity, look from left to
right, and compare the highest value in each column. So a value in
column b will override values in columns c and d, no matter what
they might be. As such, specificity of 0,1,0,0 would be greater than
one of 0,0,10,10.
In the cases of equal specificity: the latest rule is the one that counts.
If you have written the same rule into your stylesheet (regardless of
Chapter 2: CSS Interview Questions 24

internal or external) twice, then the lower rule in your style sheet
is closer to the element to be styled, it is deemed to be more specific
and therefore will be applied.
I would write CSS rules with low specificity so that they can be
easily overridden if necessary. When writing CSS UI component
library code, it is important that they have low specificities so
that users of the library can override them without using too
complicated CSS rules just for the sake of increasing specificity or
resorting to !important.

References
• css specificity³¹
• specificity³²

What’s the difference between


“resetting” and “normalizing” CSS?
Which would you choose, and why?
• Resetting - Resetting is meant to strip all default browser
styling on elements. For e.g. margins, paddings, font-sizes
of all elements are reset to be the same. You will have to
redeclare styling for common typographic elements.
• Normalizing - Normalizing preserves useful default styles
rather than “unstyling” everything. It also corrects bugs for
common browser dependencies.

I would choose resetting when I have a very customized or uncon-


ventional site design such that I need to do a lot of my own styling
and do not need any default styling to be preserved.
³¹https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/
³²https://www.sitepoint.com/web-foundations/specificity/
Chapter 2: CSS Interview Questions 25

References

• normalize css³³

Describe floats and how they work.


Float is a CSS positioning property. Floated elements remain a
part of the flow of the page, and will affect the positioning of
other elements (e.g. text will flow around floated elements), unlike
position: absolute elements, which are removed from the flow of
the page.
The CSS clear property can be used to be positioned below
left/right/both floated elements.

If a parent element contains nothing but floated elements, its height


will be collapsed to nothing. It can be fixed by clearing the float
after the floated elements in the container but before the close of
the container.
The .clearfix hack uses a clever CSS pseudo selector (:after) to
clear floats. Rather than setting the overflow on the parent, you
apply an additional class clearfix to it. Then apply this CSS:

1 .clearfix:after {
2 content: ' ';
3 visibility: hidden;
4 display: block;
5 height: 0;
6 clear: both;
7 }
³³https://stackoverflow.com/questions/6887336/what-is-the-difference-between-
normalize-css-and-reset-css
Chapter 2: CSS Interview Questions 26

Alternatively, give overflow: auto or overflow: hidden property


to the parent element which will establish a new block formatting
context inside the children and it will expand to contain its children.

References

• floats³⁴

Describe z-index and how stacking


context is formed.
The z-index property in CSS controls the vertical stacking order
of elements that overlap. z-index only affects elements that have a
position value which is not static.

Without any z-index value, elements stack in the order that they
appear in the DOM (the lowest one down at the same hierarchy
level appears on top). Elements with non-static positioning (and
their children) will always appear on top of elements with default
static positioning, regardless of HTML hierarchy.
A stacking context is an element that contains a set of layers.
Within a local stacking context, the z-index values of its children
are set relative to that element rather than to the document root.
Layers outside of that context — i.e. sibling elements of a local
stacking context — can’t sit between layers within it. If an element
B sits on top of element A, a child element of element A, element C,
can never be higher than element B even if element C has a higher
z-index than element B.

Each stacking context is self-contained - after the element’s con-


tents are stacked, the whole element is considered in the stacking
order of the parent stacking context. A handful of CSS properties
³⁴https://css-tricks.com/all-about-floats/
Chapter 2: CSS Interview Questions 27

trigger a new stacking context, such as opacity less than 1, filter


that is not none, and transform that is notnone.
Note: What exactly qualifies an element to create a stacking context
is listed in this long set of rules³⁵.

References
• z index³⁶
• z-index³⁷
• understand z index³⁸

Describe Block Formatting Context


(BFC) and how it works.
A Block Formatting Context (BFC) is part of the visual CSS render-
ing of a web page in which block boxes are laid out. Floats, abso-
lutely positioned elements, inline-blocks, table-cells, table-captions,
and elements with overflow other than visible (except when that
value has been propagated to the viewport) establish new block
formatting contexts.
Knowing how to establish a block formatting context is important,
because without doing so, the containing box will not contain
floated children³⁹. This is similar to collapsing margins, but more
insidious as you will find entire boxes collapsing in odd ways.
A BFC is an HTML box that satisfies at least one of the following
conditions:
³⁵https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_
index/The_stacking_context#The_stacking_context
³⁶https://css-tricks.com/almanac/properties/z/z-index/
³⁷https://philipwalton.com/articles/what-no-one-told-you-about-z-index/
³⁸https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_
index/The_stacking_context
³⁹https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context#
Make_float_content_and_alongside_content_the_same_height
Chapter 2: CSS Interview Questions 28

• The value of float is not none.


• The value of position is neither static nor relative.
• The value of display is table-cell, table-caption, inline-block,
flex, or inline-flex.
• The value of overflow is not visible.

In a BFC, each box’s left outer edge touches the left edge of the
containing block (for right-to-left formatting, right edges touch).
Vertical margins between adjacent block-level boxes in a BFC
collapse. Read more on collapsing margins⁴⁰.

References
• block formatting⁴¹
• formating contexts⁴²

What are the various clearing


techniques and which is appropriate
for what context?
• Empty div method - <div style="clear:both;"></div>.
• Clearfix method - Refer to the .clearfix class above.
• overflow: auto or overflow: hidden method - Parent will
establish a new block formatting context and expand to
contains its floated children.

In large projects, I would write a utility .clearfix class and use


them in places where I need it. overflow: hidden might clip
children if the children is taller than the parent and is not very
ideal.
⁴⁰https://www.sitepoint.com/web-foundations/collapsing-margins/
⁴¹https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context
⁴²https://www.sitepoint.com/understanding-block-formatting-contexts-in-css/
Chapter 2: CSS Interview Questions 29

Explain CSS sprites, and how you


would implement them on a page or
site.
CSS sprites combine multiple images into one single larger image.
It is a commonly-used technique for icons (Gmail uses it). How to
implement it:

1. Use a sprite generator that packs multiple images into one and
generate the appropriate CSS for it.
2. Each image would have a corresponding CSS class with
background-image, background-position and background-size
properties defined.
3. To use that image, add the corresponding class to your
element.

Advantages:

• Reduce the number of HTTP requests for multiple images


(only one single request is required per spritesheet). But with
HTTP2, loading multiple images is no longer much of an
issue.
• Advance downloading of assets that won’t be downloaded
until needed, such as images that only appear upon :hover
pseudo-states. Blinking wouldn’t be seen.

References

• css sprites⁴³
⁴³https://css-tricks.com/css-sprites/
Chapter 2: CSS Interview Questions 30

How would you approach fixing


browser-specific styling issues?
• After identifying the issue and the offending browser, use
a separate style sheet that only loads when that specific
browser is being used. This technique requires server-side
rendering though.
• Use libraries like Bootstrap that already handles these styling
issues for you.
• Use autoprefixer to automatically add vendor prefixes to
your code.
• Use Reset CSS or Normalize.css.
• If you’re using Postcss (or a similar transpiling library), there
may be plugins which allow you to opt in for using modern
CSS syntax (and even W3C proposals) that will transform
those sections of your code into corresponding safe code that
will work in the targets you’ve used.

How do you serve your pages for


feature-constrained browsers? What
techniques/processes do you use?
• Graceful degradation - The practice of building an application
for modern browsers while ensuring it remains functional in
older browsers.
• Progressive enhancement - The practice of building an ap-
plication for a base level of user experience, but adding
functional enhancements when a browser supports it.
• Use caniuse.com⁴⁴ to check for feature support.
• Autoprefixer for automatic vendor prefix insertion.
⁴⁴https://caniuse.com/
Chapter 2: CSS Interview Questions 31

• Feature detection using Modernizr⁴⁵.


• Use CSS Feature queries @support⁴⁶

What are the different ways to


visually hide content (and make it
available only for screen readers)?
These techniques are related to accessibility (a11y).

• width: 0; height: 0. Make the element not take up any space


on the screen at all, resulting in not showing it.
• position: absolute; left: -99999px. Position it outside of
the screen.
• text-indent: -9999px. This only works on text within the
block elements.
• Meta tags. For example by using Schema.org, RDF, and JSON-
LD.
• WAI-ARIA. A W3C technical specification that specifies how
to increase the accessibility of web pages.

Even if WAI-ARIA is the ideal solution, I would go with the


absolute positioning approach, as it has the least caveats, works
for most elements and it’s an easy technique.

References
• wai aria⁴⁷
• accesibility⁴⁸
• a11project⁴⁹
⁴⁵https://modernizr.com/
⁴⁶https://developer.mozilla.org/en-US/docs/Web/CSS/@supports
⁴⁷https://www.w3.org/TR/wai-aria-1.1/
⁴⁸https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA
⁴⁹http://a11yproject.com/
Chapter 2: CSS Interview Questions 32

Have you ever used a grid system,


and if so, what do you prefer?
Before Flex became popular (around 2014), the float-based grid
system was the most reliable because it still has the most browser
support among the alternative existing systems (flex, grid). Boot-
strap was using the float approach until Bootstrap 4 which switched
to the flex-based approach. As of writing (2020), flex is the
recommended approach for building grid systems and has decent
browser support⁵⁰.
For the adventurous, they can look into CSS Grid Layout⁵¹, which
uses the shiny new grid property; it is even better than flex for
building grid layouts and will be the de facto way to do so in the
future.

Have you used or implemented


media queries or mobile-specific
layouts/CSS?
Yes. An example would be transforming a stacked pill navigation
into a fixed-bottom tab navigation beyond a certain breakpoint.

Are you familiar with styling SVG?


Yes, there are several ways to color shapes (including specifying
attributes on the object) using inline CSS, an embedded CSS section,
or an external CSS file. Most SVG you’ll find around the web use
⁵⁰https://caniuse.com/#search=flex
⁵¹https://css-tricks.com/snippets/css/complete-guide-grid/
Chapter 2: CSS Interview Questions 33

inline CSS, but there are advantages and disadvantages associated


with each type.
Basic coloring can be done by setting two attributes on the node:
fill and stroke. fill sets the color inside the object and stroke
sets the color of the line drawn around the object. You can use the
same CSS color naming schemes that you use in HTML, whether
that’s color names (that is red), RGB values (that is rgb(255,0,0)),
Hex values, RGBA values, etc.

1 <rect
2 x="10"
3 y="10"
4 width="100"
5 height="100"
6 stroke="blue"
7 fill="purple"
8 fill-opacity="0.5"
9 stroke-opacity="0.8"
10 />

The above fill="purple" is an example of a presentational attribute.


Interestingly, and unlike inline styles like style="fill: purple"
which also happens to be an attribute, presentational attributes can
be overriden by CSS⁵² styles defined in a stylesheet. So, if you did
something like svg { fill: blue; } it would override the purple
fill we’ve defined.

References

• fills and strokes⁵³


⁵²https://css-tricks.com/presentation-attributes-vs-inline-styles/
⁵³https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes
Chapter 2: CSS Interview Questions 34

Can you give an example of an


@media property other than screen?
Yes, there are four types of @media properties (including screen):

• all - for all media type devices


• print - for printers
• speech - for screenreaders that “reads” the page out loud
• screen - for computer screens, tablets, smart-phones etc.

Here is an example of print media type’s usage:

1 @media print {
2 body {
3 color: black;
4 }
5 }

References

• media syntax⁵⁴

What are some of the “gotchas” for


writing efficient CSS?
Firstly, understand that browsers match selectors from rightmost
(key selector) to left. Browsers filter out elements in the DOM
according to the key selector and traverse up its parent elements
to determine matches. The shorter the length of the selector chain,
⁵⁴https://developer.mozilla.org/en-US/docs/Web/CSS/@media#Syntax
Chapter 2: CSS Interview Questions 35

the faster the browser can determine if that element matches the
selector. Hence avoid key selectors that are tag and universal
selectors. They match a large number of elements and browsers
will have to do more work in determining if the parents do match.
BEM Block Element Modifier⁵⁵ methodology recommends that
everything has a single class, and, where you need hierarchy, that
gets baked into the name of the class as well, this naturally makes
the selector efficient and easy to override.
Be aware of which CSS properties trigger⁵⁶ reflow, repaint, and
compositing. Avoid writing styles that change the layout (trigger
reflow) where possible.

References

• rendering⁵⁷
• csstriggers⁵⁸

What are the


advantages/disadvantages of using
CSS preprocessors?
Advantages:

• CSS is made more maintainable.


• Easy to write nested selectors.
• Variables for consistent theming. Can share theme files across
different projects.
⁵⁵https://bem.info/
⁵⁶https://csstriggers.com/
⁵⁷https://developers.google.com/web/fundamentals/performance/rendering/
⁵⁸https://csstriggers.com/
Chapter 2: CSS Interview Questions 36

• Mixins to generate repeated CSS.


• Sass features like loops, lists, and maps can make configura-
tion easier and less verbose.
• Splitting your code into multiple files. CSS files can be split up
too but doing so will require an HTTP request to download
each CSS file.

Disadvantages:

• Requires tools for preprocessing. Re-compilation time can be


slow.
• Not writing currently and potentially usable CSS. For exam-
ple, by using something like postcss-loader⁵⁹ with webpack⁶⁰,
you can write potentially future-compatible CSS, allowing
you to use things like CSS variables instead of Sass variables.
Thus, you’re learning new skills that could pay off if/when
they become standardized.

Describe what you like and dislike


about the CSS preprocessors you
have used.
Likes:

• Mostly the advantages mentioned above.


• Less is written in JavaScript, which plays well with Node.

Dislikes:
⁵⁹https://github.com/postcss/postcss-loader
⁶⁰https://webpack.js.org/
Chapter 2: CSS Interview Questions 37

• I use Sass via node-sass, which is a binding for LibSass writ-


ten in C++. I have to frequently recompile it when switching
between node versions.
• In Less, variable names are prefixed with @, which can be
confused with native CSS keywords like @media, @import and
@font-face rule.

How would you implement a web


design comp that uses non-standard
fonts?
Use @font-face and define font-family for different font-weights.

Explain how a browser determines


what elements match a CSS selector.
This part is related to the above about writing efficient CSS.
Browsers match selectors from rightmost (key selector) to left.
Browsers filter out elements in the DOM according to the key
selector and traverse up its parent elements to determine matches.
The shorter the length of the selector chain, the faster the browser
can determine if that element matches the selector.
For example with this selector p span, browsers firstly find all the
<span> elements and traverse up its parent all the way up to the root
to find the <p> element. For a particular <span>, as soon as it finds
a <p>, it knows that the <span> matches and can stop its matching.
Chapter 2: CSS Interview Questions 38

References

• css selectors⁶¹

Describe pseudo-elements and


discuss what they are used for.
A CSS pseudo-element is a keyword added to a selector that lets you
style a specific part of the selected element(s). They can be used for
decoration (:first-line, :first-letter) or adding elements to the
markup (combined with content: ...) without having to modify
the markup (:before, :after).

• :first-line and :first-letter can be used to decorate text.


• Used in the .clearfix hack as shown above to add a zero-
space element with clear: both.
• Triangular arrows in tooltips use :before and :after. Encour-
ages separation of concerns because the triangle is considered
part of styling and not really the DOM.

References

• after and before⁶²


⁶¹https://stackoverflow.com/questions/5797014/why-do-browsers-match-css-selectors-
from-right-to-left
⁶²https://css-tricks.com/almanac/selectors/a/after-and-before/
Chapter 2: CSS Interview Questions 39

Explain your understanding of the


box model and how you would tell
the browser in CSS to render your
layout in different box models.
The CSS box model describes the rectangular boxes that are gener-
ated for elements in the document tree and laid out according to the
visual formatting model. Each box has a content area (e.g. text, an
image, etc.) and optional surrounding padding, border, and margin
areas.
The CSS box model is responsible for calculating:

• How much space a block element takes up.


• Whether or not borders and/or margins overlap, or collapse.
• A box’s dimensions.

The box model has the following rules:

• The dimensions of a block element are calculated by width,


height, padding, borders, and margins.
• If no height is specified, a block element will be as high as
the content it contains, plus padding (unless there are floats,
for which see below).
• If no width is specified, a non-floated block element will
expand to fit the width of its parent minus padding.
• The height of an element is calculated by the content’s
height.
• The width of an element is calculated by the content’s width.
• By default, paddings and borders are not part of the width and
height of an element.
Chapter 2: CSS Interview Questions 40

References

• css box model⁶³

What does * { box-sizing: border-box;


} do? What are its advantages?

• By default, elements have box-sizing: content-box applied,


and only the content size is being accounted for.
• box-sizing: border-box changes how the width and height
of elements are being calculated, border and padding are also
being included in the calculation.
• The height of an element is now calculated by the content’s
height + vertical padding + vertical border width.
• The width of an element is now calculated by the content’s
width + horizontal padding + horizontal border width.
• Taking into account paddings and borders as part of our box
model resonates better with how designers actually imagine
content in grids.

References

• box sizing⁶⁴
⁶³https://www.smashingmagazine.com/2010/06/the-principles-of-cross-browser-css-
coding/#understand-the-css-box-model
⁶⁴https://www.paulirish.com/2012/box-sizing-border-box-ftw/
Chapter 2: CSS Interview Questions 41

What is the CSS display property and


can you give a few examples of its
use?
• none, block, inline, inline-block, flex, grid, table, table-row,
table-cell, list-item.

display Description
none Does not display an element (the
elementv no longer affects the layout
of the document). All child element are
also no longer displayed. The
document is rendered as if the element
did not exist in the document tree
block The element consumes the whole line
in the block direction (which is usually
horizontal)
inline Elements can be laid out beside each
other
inline-block Similar to inline, but allows some
block properties like setting width and
height
table Behaves like the <table> element
table-row Behaves like the <tr> element
table-cell Behaves like the <td> element
list-item Behaves like a <li> element which
allows it to define list-style-type
and list-style-position

What’s the difference between inline


and inline-block?
I shall throw in a comparison with block for good measure.
Chapter 2: CSS Interview Questions 42

block inline-block inline


Size Fills up the Depends Depends
width of its on content. on content.
parent
container.
Positioning Start on a Flows Flows
new line along with along with
and other other
tolerates no content content
HTML and allows and allows
elements other other
next to it elements elements
(except beside it. beside it.
when you
add float)
Can Yes Yes No. Will
specify ignore if
width and being set.
height
Can be No Yes Yes
aligned
with
vertical-align
Chapter 2: CSS Interview Questions 43

block inline-block inline


Margins All sides All sides Only
and respected. respected. horizontal
paddings sides
respected.
Vertical
sides, if
specified,
do not
affect
layout.
Vertical
space it
takes up
depends on
line-height,
even
though the
border and
padding
appear
visually
around the
content.
Float - - Becomes
like a block
element
where you
can set
vertical
margins
and
paddings.
Chapter 2: CSS Interview Questions 44

What’s the difference between a


relative, fixed, absolute and statically
positioned element?
A positioned element is an element whose computed position
property is either relative, absolute, fixed or sticky.

• static - The default position; the element will flow into the
page as it normally would. The top, right, bottom, left and
z-index properties do not apply.
• relative - The element’s position is adjusted relative to itself,
without changing layout (and thus leaving a gap for the
element where it would have been had it not been positioned).
• absolute - The element is removed from the flow of the page
and positioned at a specified position relative to its closest
positioned ancestor if any, or otherwise relative to the initial
containing block. Absolutely positioned boxes can have mar-
gins, and they do not collapse with any other margins. These
elements do not affect the position of other elements.
• fixed - The element is removed from the flow of the page and
positioned at a specified position relative to the viewport and
doesn’t move when scrolled.
• sticky - Sticky positioning is a hybrid of relative and fixed
positioning. The element is treated as relative positioned
until it crosses a specified threshold, at which point it is
treated as fixed positioned.

References

• position⁶⁵
⁶⁵https://developer.mozilla.org/en/docs/Web/CSS/position
Chapter 2: CSS Interview Questions 45

What existing CSS frameworks have


you used locally, or in production?
How would you change/improve
them?
• Bootstrap - Slow release cycle. Bootstrap 4 has been in alpha
for almost 2 years. Add a spinner button component, as it is
widely used.
• Semantic UI - Source code structure makes theme customiza-
tion extremely hard to understand. Its unconventional them-
ing system is a pain to customize. Hardcoded config path
within the vendor library. Not well-designed for overriding
variables unlike in Bootstrap.
• Bulma - A lot of non-semantic and superfluous classes and
markup required. Not backward compatible. Upgrading ver-
sions breaks the app in subtle manners.

Have you played around with the


new CSS Flexbox or Grid specs?
Yes. Flexbox is mainly meant for 1-dimensional layouts while Grid
is meant for 2-dimensional layouts.
Flexbox solves many common problems in CSS, such as vertical
centering of elements within a container, sticky footer, etc. Boot-
strap and Bulma are based on Flexbox, and it is probably the
recommended way to create layouts these days. Have tried Flexbox
before but ran into some browser incompatibility issues (Safari) in
using flex-grow, and I had to rewrite my code using inline-blocks
and math to calculate the widths in percentages, it wasn’t a nice
experience.
Chapter 2: CSS Interview Questions 46

Grid is by far the most intuitive approach for creating grid-based


layouts (it better be!) but browser support is not wide at the
moment.

References

• flexbox⁶⁶

Can you explain the difference


between coding a website to be
responsive versus using a
mobile-first strategy?
Note that these two 2 approaches are not exclusive.
Making a website responsive means the some elements will re-
spond by adapting its size or other functionality according to the
device’s screen size, typically the viewport width, through CSS
media queries, for example, making the font size smaller on smaller
devices.

1 @media (min-width: 601px) {


2 .my-class {
3 font-size: 24px;
4 }
5 }
6
7 @media (max-width: 600px) {
8 .my-class {
9 font-size: 12px;
⁶⁶https://philipwalton.github.io/solved-by-flexbox/
Chapter 2: CSS Interview Questions 47

10 }
11 }

A mobile-first strategy is also responsive, however it agrees we


should default and define all the styles for mobile devices, and only
add specific responsive rules to other devices later. Following the
previous example:

1 .my-class {
2 font-size: 12px;
3 }
4
5 @media (min-width: 600px) {
6 .my-class {
7 font-size: 24px;
8 }
9 }

A mobile-first strategy has 2 main advantages:

• It’s more performant on mobile devices, since all the rules


applied for them don’t have to be validated against any media
queries.
• It forces to write cleaner code in respect to responsive CSS
rules.

How is responsive design different


from adaptive design?
Both responsive and adaptive design attempt to optimize the user
experience across different devices, adjusting for different viewport
sizes, resolutions, usage contexts, control mechanisms, and so on.
Chapter 2: CSS Interview Questions 48

Responsive design works on the principle of flexibility - a single


fluid website that can look good on any device. Responsive websites
use media queries, flexible grids, and responsive images to create
a user experience that flexes and changes based on a multitude of
factors. Like a single ball growing or shrinking to fit through several
different hoops.
Adaptive design is more like the modern definition of progressive
enhancement. Instead of one flexible design, adaptive design de-
tects the device and other features and then provides the appropri-
ate feature and layout based on a predefined set of viewport sizes
and other characteristics. The site detects the type of device used
and delivers the pre-set layout for that device. Instead of a single
ball going through several different-sized hoops, you’d have several
different balls to use depending on the hoop size.
Both have these methods have some issues that need to be weighed:

• Responsive design can be quite challenging, as you’re es-


sentially using a single albeit responsive layout to fit all
situations. How to set the media query breakpoints is one
such challenge. Do you use standardized breakpoint values?
Or, do you use breakpoints that make sense to your particular
layout? What if that layout changes?
• Adaptive design generally requires user agent sniffing, or DPI
detection, etc., all of which can prove unreliable.

References

• adaptive design⁶⁷
• responsive adaptive⁶⁸
• responsive vs adaptive⁶⁹
⁶⁷https://developer.mozilla.org/en-US/docs/Archive/Apps/Design/UI_layout_basics/
Responsive_design_versus_adaptive_design
⁶⁸http://mediumwell.com/responsive-adaptive-mobile/
⁶⁹https://css-tricks.com/the-difference-between-responsive-and-adaptive-design/
Chapter 2: CSS Interview Questions 49

Have you ever worked with retina


graphics? If so, when and what
techniques did you use?
Retina is just a marketing term to refer to high resolution screens
with a pixel ratio bigger than 1. The key thing to know is that using
a pixel ratio means these displays are emulating a lower resolution
screen in order to show elements with the same size. Nowadays we
consider all mobile devices retina defacto displays.
Browsers by default render DOM elements according to the device
resolution, except for images.
In order to have crisp, good-looking graphics that make the best
of retina displays we need to use high resolution images whenever
possible. However using always the highest resolution images will
have an impact on performance as more bytes will need to be sent
over the wire.
To overcome this problem, we can use responsive images, as spec-
ified in HTML5. It requires making available different resolution
files of the same image to the browser and let it decide which image
is best, using the html attribute srcset and optionally sizes, for
instance:

1 <div responsive-background-image>
2 <img
3 src="/images/test-1600.jpg"
4 sizes="
5 (min-width: 768px) 50vw,
6 (min-width: 1024px) 66vw,
7 100vw"
8 srcset="
9 /images/test-400.jpg 400w,
10 /images/test-800.jpg 800w,
Chapter 2: CSS Interview Questions 50

11 /images/test-1200.jpg 1200w
12 "
13 />
14 </div>

It is important to note that browsers which don’t support HTML5’s


srcset (i.e. IE11) will ignore it and use src instead. If we really need
to support IE11 and we want to provide this feature for performance
reasons, we can use a JavaScript polyfill, e.g. Picturefill (link in the
references).
For icons, I would also opt to use SVGs and icon fonts where
possible, as they render very crisply regardless of resolution.

References

• responsive images⁷⁰
• picturefill⁷¹
• responsive background⁷²

Is there any reason you’d want to


use translate() instead of absolute
positioning, or vice-versa? And why?
translate() is a value of CSS transform. Changing transform or
opacity does not trigger browser reflow or repaint but does trigger
compositions; whereas changing the absolute positioning triggers
reflow. transform causes the browser to create a GPU layer for the
element but changing absolute positioning properties uses the CPU.
⁷⁰https://css-tricks.com/responsive-images-youre-just-changing-resolutions-use-srcset/
⁷¹http://scottjehl.github.io/picturefill/
⁷²https://aclaes.com/responsive-background-images-with-srcset-and-sizes/
Chapter 2: CSS Interview Questions 51

Hence translate() is more efficient and will result in shorter paint


times for smoother animations.
When using translate(), the element still occupies its original
space (sort of like position: relative), unlike in changing the
absolute positioning.

References

• moving elements⁷³

⁷³https://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-
posabs-topleft/
Chapter 3: Javascript
Interview Questions
Explain event delegation
Event delegation is a technique involving adding event listeners
to a parent element instead of adding them to the descendant
elements. The listener will fire whenever the event is triggered on
the descendant elements due to event bubbling up the DOM. The
benefits of this technique are:

• Memory footprint goes down because only one single handler


is needed on the parent element, rather than having to attach
event handlers on each descendant.
• There is no need to unbind the handler from elements that
are removed and to bind the event for new elements.

References
• event delegate⁷⁴
• dom delegation⁷⁵

Explain how this works in JavaScript


There’s no simple explanation for this; it is one of the most
confusing concepts in JavaScript. A hand-wavey explanation is that
⁷⁴https://davidwalsh.name/event-delegate
⁷⁵https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation
Chapter 3: Javascript Interview Questions 53

the value of this depends on how the function is called. I have read
many explanations on this online, and I found Arnav Aggrawal⁷⁶’s
explanation to be the clearest. The following rules are applied:

1. If the new keyword is used when calling the function, this


inside the function is a brand new object.
2. If apply, call, or bind are used to call/create a function,
this inside the function is the object that is passed in as the
argument.
3. If a function is called as a method, such as obj.method()—
this is the object that the function is a property of.
4. If a function is invoked as a free function invocation, meaning
it was invoked without any of the conditions present above,
this is the global object. In a browser, it is the window object. If
in strict mode ('use strict'), this will be undefined instead
of the global object.
5. If multiple of the above rules apply, the rule that is higher
wins and will set the this value.
6. If the function is an ES2015 arrow function, it ignores all the
rules above and receives the this value of its surrounding
scope at the time it is created.

For an in-depth explanation, do check out his article on Medium⁷⁷.

Can you give an example of one of the ways


that working with this has changed in ES6?

ES6 allows you to use arrow functions⁷⁸ which uses the enclosing
lexical scope⁷⁹. This is usually convenient, but does prevent the
⁷⁶https://medium.com/@arnav_aggarwal
⁷⁷https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3
⁷⁸http://2ality.com/2017/12/alternate-this.html#arrow-functions
⁷⁹https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_
functions#No_separate_this
Chapter 3: Javascript Interview Questions 54

caller from controlling context via .call or .apply—the conse-


quences being that a library such as jQuery will not properly bind
this in your event handler functions. Thus, it’s important to keep
this in mind when refactoring large legacy applications.

References

• simple rules⁸⁰
• es6⁸¹

Explain how prototypal inheritance


works
This is an extremely common JavaScript interview question. All
JavaScript objects have a __proto__ property, that is a reference
to another object, which is called the object’s “prototype”. When a
property is accessed on an object and if the property is not found on
that object, the JavaScript engine looks at the object’s __proto__,
and the __proto__’s __proto__ and so on, until it finds the property
defined on one of the __proto__s or until it reaches the end of the
prototype chain. This behavior simulates classical inheritance, but
it is really more of delegation than inheritance⁸².

Example of Prototypal Inheritance

We already have a build-in Object.create, but if you were to


provide a polyfill for it, that might look like:

⁸⁰https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3
⁸¹https://stackoverflow.com/a/3127440/1751946
⁸²https://davidwalsh.name/javascript-objects
Chapter 3: Javascript Interview Questions 55

1 if (typeof Object.create !== 'function') {


2 Object.create = function (parent) {
3 function Tmp() {}
4 Tmp.prototype = parent;
5 return new Tmp();
6 };
7 }
8
9 const Parent = function () {
10 this.name = 'Parent';
11 };
12
13 Parent.prototype.greet = function () {
14 console.log('hello from Parent');
15 };
16
17 const child = Object.create(Parent.prototype);
18
19 child.cry = function () {
20 console.log('waaaaaahhhh!');
21 };
22
23 child.cry();
24 // Outputs: waaaaaahhhh!
25
26 child.greet();
27 // Outputs: hello from Parent

Things to note are:

• .greet is not defined on the child, so the engine goes up


the prototype chain and finds .greet off the inherited from
Parent.
• We need to call Object.create in one of following ways for
the prototype methods to be inherited:
Chapter 3: Javascript Interview Questions 56

– Object.create(Parent.prototype);
– Object.create(new Parent(null));
– Object.create(objLiteral);
– Currently, child.constructor is pointing to the Parent:

1 child.constructor
2 ƒ () {
3 this.name = "Parent";
4 }
5 child.constructor.name
6 "Parent"

• If we’d like to correct this, one option would be to do:

1 function Child() {
2 Parent.call(this);
3 this.name = 'child';
4 }
5
6 Child.prototype = Parent.prototype;
7 Child.prototype.constructor = Child;
8
9 const c = new Child();
10
11 c.cry();
12 // Outputs: waaaaaahhhh!
13
14 c.greet();
15 // Outputs: hello from Parent
16
17 c.constructor.name;
18 // Outputs: "Child"
Chapter 3: Javascript Interview Questions 57

References

• javascript the core⁸³


• inheritance⁸⁴

What do you think of AMD vs


CommonJS?
Both are ways to implement a module system, which was not
natively present in JavaScript until ES2015 came along. CommonJS
is synchronous while AMD (Asynchronous Module Definition)
is obviously asynchronous. CommonJS is designed with server-
side development in mind while AMD, with its support for asyn-
chronous loading of modules, is more intended for browsers.
I find AMD syntax to be quite verbose and CommonJS is closer to
the style you would write import statements in other languages.
Most of the time, I find AMD unnecessary, because if you served
all your JavaScript into one concatenated bundle file, you wouldn’t
benefit from the async loading properties. Also, CommonJS syntax
is closer to Node style of writing modules and there is less context-
switching overhead when switching between client side and server
side JavaScript development.
I’m glad that with ES2015 modules, that has support for both
synchronous and asynchronous loading, we can finally just stick to
one approach. Although it hasn’t been fully rolled out in browsers
and in Node, we can always use transpilers to convert our code.
⁸³http://dmitrysoshnikov.com/ecmascript/javascript-the-core/
⁸⁴https://www.quora.com/What-is-prototypal-inheritance/answer/Kyle-Simpson
Chapter 3: Javascript Interview Questions 58

References

• module systems⁸⁵
• commonjs⁸⁶

Explain why the following doesn’t


work as an IIFE: function foo(){ }();.
What needs to be changed to
properly make it an IIFE?
IIFE stands for Immediately Invoked Function Expressions. The
JavaScript parser reads function foo(){ }(); as function foo(){
} and ();, where the former is a function declaration and the
latter (a pair of parentheses) is an attempt at calling a function but
there is no name specified, hence it throws Uncaught SyntaxError:
Unexpected token ).

Here are two ways to fix it that involves adding more paren-
theses: (function foo(){ })() and (function foo(){ }()).
Statements that begin with function are considered to be function
declarations; by wrapping this function within (), it becomes a
function expression which can then be executed with the subse-
quent (). These functions are not exposed in the global scope and
you can even omit its name if you do not need to reference itself
within the body.
You might also use void operator: void function foo(){ }();. Un-
fortunately, there is one issue with such approach. The evaluation
of given expression is always undefined, so if your IIFE function
returns anything, you can’t use it. An example:

⁸⁵https://auth0.com/blog/javascript-module-systems-showdown/
⁸⁶https://stackoverflow.com/questions/16521471/relation-between-commonjs-amd-and-
requirejs
Chapter 3: Javascript Interview Questions 59

1 const foo = void (function bar() {


2 return 'foo';
3 })();
4
5 console.log(foo); // undefined

References

• iife⁸⁷
• void⁸⁸

What’s the difference between a


variable that is: null, undefined or
undeclared? How would you go
about checking for any of these
states?
Undeclared variables are created when you assign a value to an
identifier that is not previously created using var, let or const.
Undeclared variables will be defined globally, outside of the current
scope. In strict mode, a ReferenceError will be thrown when you
try to assign to an undeclared variable. Undeclared variables are
bad just like how global variables are bad. Avoid them at all cost!
To check for them, wrap its usage in a try/catch block.

⁸⁷http://lucybain.com/blog/2014/immediately-invoked-function-expression/
⁸⁸https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
Chapter 3: Javascript Interview Questions 60

1 function foo() {
2 x = 1; // Throws a ReferenceError in strict mode
3 }
4
5 foo();
6 console.log(x); // 1

A variable that is undefined is a variable that has been declared,


but not assigned a value. It is of type undefined. If a function does
not return any value as the result of executing it is assigned to a
variable, the variable also has the value of undefined. To check for
it, compare using the strict equality (===) operator or typeof which
will give the 'undefined' string. Note that you should not be using
the abstract equality operator to check, as it will also return true if
the value is null.

1 var foo;
2 console.log(foo); // undefined
3 console.log(foo === undefined); // true
4 console.log(typeof foo === 'undefined'); // true
5
6 console.log(foo == null); // true. Wrong, don't use this \
7 to check!
8
9 function bar() {}
10 var baz = bar();
11 console.log(baz); // undefined

A variable that is null will have been explicitly assigned to the null
value. It represents no value and is different from undefined in the
sense that it has been explicitly assigned. To check for null, simply
compare using the strict equality operator. Note that like the above,
you should not be using the abstract equality operator (==) to check,
as it will also return true if the value is undefined.
Chapter 3: Javascript Interview Questions 61

1 var foo = null;


2 console.log(foo === null); // true
3 console.log(typeof foo === 'object'); // true
4
5 console.log(foo == undefined); // true. Wrong, don't use \
6 this to check!

As a personal habit, I never leave my variables undeclared or


unassigned. I will explicitly assign null to them after declaring if
I don’t intend to use it yet. If you use a linter in your workflow,
it will usually also be able to check that you are not referencing
undeclared variables.

References
• variables⁸⁹
• global objects⁹⁰

What is a closure, and how/why


would you use one?
A closure is the combination of a function and the lexical environ-
ment within which that function was declared. The word “lexical”
refers to the fact that lexical scoping uses the location where a
variable is declared within the source code to determine where that
variable is available. Closures are functions that have access to the
outer (enclosing) function’s variables—scope chain even after the
outer function has returned.
Why would you use one?
⁸⁹https://stackoverflow.com/questions/15985875/effect-of-declared-and-undeclared-
variables
⁹⁰https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/
undefined
Chapter 3: Javascript Interview Questions 62

• Data privacy / emulating private methods with closures.


Commonly used in the module pattern⁹¹.
• Partial applications or currying⁹².

References

• closures⁹³
• what is a closure⁹⁴

Can you describe the main


difference between a .forEach loop
and a .map() loop and why you would
pick one versus the other?
To understand the differences between the two, let’s look at what
each function does.
forEach

• Iterates through the elements in an array.


• Executes a callback for each element.
• Does not return a value.

⁹¹https://addyosmani.com/resources/essentialjsdesignpatterns/book/
#modulepatternjavascript
⁹²https://medium.com/javascript-scene/curry-or-partial-application-8150044c78b8#
.l4b6l1i3x
⁹³https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
⁹⁴https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-
closure-b2f0d2152b36
Chapter 3: Javascript Interview Questions 63

1 const a = [1, 2, 3];


2 const doubled = a.forEach((num, index) => {
3 // Do something with num and/or index.
4 });
5
6 // doubled = undefined

map

• Iterates through the elements in an array.


• “Maps” each element to a new element by calling the function
on each element, creating a new array as a result.

1 const a = [1, 2, 3];


2 const doubled = a.map((num) => {
3 return num * 2;
4 });
5
6 // doubled = [2, 4, 6]

The main difference between .forEach and .map() is that .map()


returns a new array. If you need the result, but do not wish to
mutate the original array, .map() is the clear choice. If you simply
need to iterate over an array, forEach is a fine choice.

References

• map vs foreach⁹⁵
⁹⁵https://codeburst.io/javascript-map-vs-foreach-f38111822c0f
Chapter 3: Javascript Interview Questions 64

What’s a typical use case for


anonymous functions?
They can be used in IIFEs to encapsulate some code within a local
scope so that variables declared in it do not leak to the global scope.

1 (function () {
2 // Some code here.
3 })();

As a callback that is used once and does not need to be used any-
where else. The code will seem more self-contained and readable
when handlers are defined right inside the code calling them, rather
than having to search elsewhere to find the function body.

1 setTimeout(function () {
2 console.log('Hello world!');
3 }, 1000);

Arguments to functional programming constructs or Lodash (sim-


ilar to callbacks).

1 const arr = [1, 2, 3];


2 const double = arr.map(function (el) {
3 return el * 2;
4 });
5 console.log(double); // [2, 4, 6]

References
• anonymous functions⁹⁶
• anonymous⁹⁷
⁹⁶https://www.quora.com/What-is-a-typical-usecase-for-anonymous-functions
⁹⁷https://stackoverflow.com/questions/10273185/what-are-the-benefits-to-using-
anonymous-functions-instead-of-named-functions-fo
Chapter 3: Javascript Interview Questions 65

How do you organize your code?


(module pattern, classical
inheritance?)
In the past, I’ve used Backbone for my models which encourages
a more OOP approach, creating Backbone models and attaching
methods to them.
The module pattern is still great, but these days, I use React/Redux
which utilize a single-directional data flow based on Flux architec-
ture. I would represent my app’s models using plain objects and
write utility pure functions to manipulate these objects. State is
manipulated using actions and reducers like in any other Redux
application.
I avoid using classical inheritance where possible. When and if I do,
I stick to these rules⁹⁸.

What’s the difference between host


objects and native objects?
Native objects are objects that are part of the JavaScript language
defined by the ECMAScript specification, such as String, Math,
RegExp, Object, Function, etc.

Host objects are provided by the runtime environment (browser or


Node), such as window, XMLHTTPRequest, etc.
⁹⁸https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-
9af8de78ccb4
Chapter 3: Javascript Interview Questions 66

References

• native and host objects⁹⁹

Difference between: function


Person(){}, var person = Person(), and
var person = new Person()?

This question is pretty vague. My best guess at its intention is that


it is asking about constructors in JavaScript. Technically speaking,
function Person(){} is just a normal function declaration. The
convention is to use PascalCase for functions that are intended to
be used as constructors.
var person = Person() invokes the Person as a function, and not as
a constructor. Invoking as such is a common mistake if the function
is intended to be used as a constructor. Typically, the constructor
does not return anything, hence invoking the constructor like a
normal function will return undefined and that gets assigned to
the variable intended as the instance.
var person = new Person() creates an instance of the Person object
using the new operator, which inherits from Person.prototype. An
alternative would be to use Object.create, such as: Object.create(Person.prototyp

⁹⁹https://stackoverflow.com/questions/7614317/what-is-the-difference-between-native-
objects-and-host-objects
Chapter 3: Javascript Interview Questions 67

1 function Person(name) {
2 this.name = name;
3 }
4
5 var person = Person('John');
6 console.log(person); // undefined
7 console.log(person.name); // Uncaught TypeError: Cannot r\
8 ead property 'name' of undefined
9
10 var person = new Person('John');
11 console.log(person); // Person { name: "John" }
12 console.log(person.name); // "john"

References

• operators¹⁰⁰

What’s the difference between .call


and .apply?
Both .call and .apply are used to invoke functions and the first
parameter will be used as the value of this within the function.
However, .call takes in comma-separated arguments as the next
arguments while .apply takes in an array of arguments as the next
argument. An easy way to remember this is C for call and comma-
separated and A for apply and an array of arguments.

¹⁰⁰https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
Chapter 3: Javascript Interview Questions 68

1 function add(a, b) {
2 return a + b;
3 }
4
5 console.log(add.call(null, 1, 2)); // 3
6 console.log(add.apply(null, [1, 2])); // 3

Explain Function.prototype.bind.
Taken word-for-word from MDN¹⁰¹:

The bind() method creates a new function that, when


called, has its this keyword set to the provided value,
with a given sequence of arguments preceding any
provided when the new function is called.

In my experience, it is most useful for binding the value of this in


methods of classes that you want to pass into other functions. This
is frequently done in React components.

References
• bind¹⁰²

When would you use document.write()?


document.write() writes a string of text to a document stream
opened by document.open(). When document.write() is executed
¹⁰¹https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/
Function/bind
¹⁰²https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/
Function/bind
Chapter 3: Javascript Interview Questions 69

after the page has loaded, it will call document.open which clears
the whole document (<head> and <body> removed!) and replaces
the contents with the given parameter value. Hence it is usually
considered dangerous and prone to misuse.
There are some answers online that explain document.write() is
being used in analytics code or when you want to include styles
that should only work if JavaScript is enabled¹⁰³. It is even being
used in HTML5 boilerplate to load scripts in parallel and preserve
execution order¹⁰⁴! However, I suspect those reasons might be
outdated and in the modern day, they can be achieved without
using document.write(). Please do correct me if I’m wrong about
this.

References

• doc write¹⁰⁵
• script loading¹⁰⁶

What’s the difference between


feature detection, feature
inference, and using the UA string?
Feature Detection
Feature detection involves working out whether a browser supports
a certain block of code, and running different code depending on
whether it does (or doesn’t), so that the browser can always provide
¹⁰³https://www.quirksmode.org/blog/archives/2005/06/three_javascrip_1.html
¹⁰⁴https://github.com/paulirish/html5-boilerplate/wiki/Script-Loading-Techniques#
documentwrite-script-tag
¹⁰⁵https://www.quirksmode.org/blog/archives/2005/06/three_javascrip_1.html
¹⁰⁶https://github.com/h5bp/html5-boilerplate/wiki/Script-Loading-Techniques#
documentwrite-script-tag
Chapter 3: Javascript Interview Questions 70

a working experience rather crashing/erroring in some browsers.


For example:

1 if ('geolocation' in navigator) {
2 // Can use navigator.geolocation
3 } else {
4 // Handle lack of feature
5 }

Modernizr¹⁰⁷ is a great library to handle feature detection.


Feature Inference
Feature inference checks for a feature just like feature detection,
but uses another function because it assumes it will also exist, e.g.:

1 if (document.getElementsByTagName) {
2 element = document.getElementById(id);
3 }

This is not really recommended. Feature detection is more fool-


proof.
UA String
This is a browser-reported string that allows the network protocol
peers to identify the application type, operating system, software
vendor or software version of the requesting software user agent.
It can be accessed via navigator.userAgent. However, the string is
tricky to parse and can be spoofed. For example, Chrome reports
both as Chrome and Safari. So to detect Safari you have to check
for the Safari string and the absence of the Chrome string. Avoid
this method.
¹⁰⁷https://modernizr.com/
Chapter 3: Javascript Interview Questions 71

References

• feature detection¹⁰⁸
• user agent¹⁰⁹

Explain Ajax in as much detail as


possible.
Ajax (asynchronous JavaScript and XML) is a set of web develop-
ment techniques using many web technologies on the client side to
create asynchronous web applications. With Ajax, web applications
can send data to and retrieve from a server asynchronously (in the
background) without interfering with the display and behavior of
the existing page. By decoupling the data interchange layer from
the presentation layer, Ajax allows for web pages, and by extension
web applications, to change content dynamically without the need
to reload the entire page. In practice, modern implementations com-
monly substitute use JSON instead of XML, due to the advantages
of JSON being native to JavaScript.
The XMLHttpRequest API is frequently used for the asynchronous
communication or these days, the fetch API.

References

• ajax¹¹⁰
• ajax docs¹¹¹
¹⁰⁸https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_
testing/Feature_detection
¹⁰⁹https://stackoverflow.com/questions/20104930/whats-the-difference-between-feature-
detection-feature-inference-and-using-th
¹¹⁰https://en.wikipedia.org/wiki/Ajax_(programming)
¹¹¹https://developer.mozilla.org/en-US/docs/AJAX
Chapter 3: Javascript Interview Questions 72

What are the advantages and


disadvantages of using Ajax?
Advantages

• Better interactivity. New content from the server can be


changed dynamically without the need to reload the entire
page.
• Reduce connections to the server since scripts and stylesheets
only have to be requested once.
• State can be maintained on a page. JavaScript variables and
DOM state will persist because the main container page was
not reloaded.
• Basically most of the advantages of an SPA.

Disadvantages

• Dynamic webpages are harder to bookmark.


• Does not work if JavaScript has been disabled in the browser.
• Some webcrawlers do not execute JavaScript and would not
see content that has been loaded by JavaScript.
• Webpages using Ajax to fetch data will likely have to combine
the fetched remote data with client-side templates to update
the DOM. For this to happen, JavaScript will have to be parsed
and executed on the browser, and low-end mobile devices
might struggle with this.
• Basically most of the disadvantages of an SPA.

Explain how JSONP works (and how


it’s not really Ajax).
JSONP (JSON with Padding) is a method commonly used to bypass
the cross-domain policies in web browsers because Ajax requests
Chapter 3: Javascript Interview Questions 73

from the current page to a cross-origin domain is not allowed.


JSONP works by making a request to a cross-origin domain via a
<script> tag and usually with a callback query parameter, for ex-
ample: https://example.com?callback=printData. The server will
then wrap the data within a function called printData and return
it to the client.

1 <!-- https://mydomain.com -->


2 <script>
3 function printData(data) {
4 console.log(`My name is ${data.name}!`);
5 }
6 </script>
7
8 <script src="https://example.com?callback=printData"></sc\
9 ript>

1 // File loaded from https://example.com?callback=printData


2 printData({name: 'Yang Shun'});

The client has to have the printData function in its global scope
and the function will be executed by the client when the response
from the cross-origin domain is received.
JSONP can be unsafe and has some security implications. As JSONP
is really JavaScript, it can do everything else JavaScript can do, so
you need to trust the provider of the JSONP data.
These days, CORS¹¹² is the recommended approach and JSONP is
seen as a hack.

References
• cross origin¹¹³
¹¹²http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
¹¹³https://stackoverflow.com/a/2067584/1751946
Chapter 3: Javascript Interview Questions 74

Have you ever used JavaScript


templating? If so, what libraries
have you used?
Yes. Handlebars, Underscore, Lodash, AngularJS, and JSX. I disliked
templating in AngularJS because it made heavy use of strings in the
directives and typos would go uncaught. JSX is my new favorite as
it is closer to JavaScript and there is barely any syntax to learn.
Nowadays, you can even use ES2015 template string literals as a
quick way for creating templates without relying on third-party
code.

1 const template = `<div>My name is: ${name}</div>`;

However, do be aware of a potential XSS in the above approach as


the contents are not escaped for you, unlike in templating libraries.

Explain “hoisting”.
Hoisting is a term used to explain the behavior of variable dec-
larations in your code. Variables declared or initialized with the
var keyword will have their declaration “moved” up to the top of
their module/function-level scope, which we refer to as hoisting.
However, only the declaration is hoisted, the assignment (if there
is one), will stay where it is.
Note that the declaration is not actually moved - the JavaScript
engine parses the declarations during compilation and becomes
aware of declarations and their scopes. It is just easier to understand
this behavior by visualizing the declarations as being hoisted to the
top of their scope. Let’s explain with a few examples.
Chapter 3: Javascript Interview Questions 75

1 console.log(foo); // undefined
2 var foo = 1;
3 console.log(foo); // 1

Function declarations have the body hoisted while the function


expressions (written in the form of variable declarations) only has
the variable declaration hoisted.

1 // Function Declaration
2 console.log(foo); // [Function: foo]
3 foo(); // 'FOOOOO'
4 function foo() {
5 console.log('FOOOOO');
6 }
7 console.log(foo); // [Function: foo]
8
9 // Function Expression
10 console.log(bar); // undefined
11 bar(); // Uncaught TypeError: bar is not a function
12 var bar = function () {
13 console.log('BARRRR');
14 };
15 console.log(bar); // [Function: bar]

Variables declared via let and const are hoisted as well. However,
unlike var and function, they are not initialized and accessing them
before the declaration will result in a ReferenceError exception.
The variable is in a “temporal dead zone” from the start of the block
until the declaration is processed.
Chapter 3: Javascript Interview Questions 76

1 x; // undefined
2 y; // Reference error: y is not defined
3
4 var x = 'local';
5 let y = 'local';

References

• variable hosting¹¹⁴
• let or const¹¹⁵

Describe event bubbling.


When an event triggers on a DOM element, it will attempt to handle
the event if there is a listener attached, then the event is bubbled up
to its parent and the same thing happens. This bubbling occurs up
the element’s ancestors all the way to the document. Event bubbling
is the mechanism behind event delegation.

What’s the difference between an


“attribute” and a “property”?
Attributes are defined on the HTML markup but properties are
defined on the DOM. To illustrate the difference, imagine we have
this text field in our HTML: <input type="text" value="Hello">.

¹¹⁴https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_Types#
Variable_hoisting
¹¹⁵https://stackoverflow.com/questions/31219420/are-variables-declared-with-let-or-
const-not-hoisted-in-es6/31222689#31222689
Chapter 3: Javascript Interview Questions 77

1 const input = document.querySelector('input');


2 console.log(input.getAttribute('value')); // Hello
3 console.log(input.value); // Hello

But after you change the value of the text field by adding “World!”
to it, this becomes:

1 console.log(input.getAttribute('value')); // Hello
2 console.log(input.value); // Hello World!

References

• properties and attributes¹¹⁶

Why is extending built-in JavaScript


objects not a good idea?
Extending a built-in/native JavaScript object means adding prop-
erties/functions to its prototype. While this may seem like a good
idea at first, it is dangerous in practice. Imagine your code uses a
few libraries that both extend the Array.prototype by adding the
same contains method, the implementations will overwrite each
other and your code will break if the behavior of these two methods
is not the same.
The only time you may want to extend a native object is when
you want to create a polyfill, essentially providing your own imple-
mentation for a method that is part of the JavaScript specification
but might not exist in the user’s browser due to it being an older
browser.
¹¹⁶https://stackoverflow.com/questions/6003819/properties-and-attributes-in-html
Chapter 3: Javascript Interview Questions 78

References
• extend ojects¹¹⁷

Difference between document load


event and document DOMContentLoaded
event?
The DOMContentLoaded event is fired when the initial HTML docu-
ment has been completely loaded and parsed, without waiting for
stylesheets, images, and subframes to finish loading.
window’s load event is only fired after the DOM and all dependent
resources and assets have loaded.

References
• DOMContentLoaded¹¹⁸
• load¹¹⁹

What is the difference between ==


and ===?
== is the abstract equality operator while === is the strict equality
operator. The == operator will compare for equality after doing
any necessary type conversions. The === operator will not do type
conversion, so if two values are not the same type === will simply
return false. When using ==, funky things can happen, such as:
¹¹⁷http://lucybain.com/blog/2014/js-extending-built-in-objects/
¹¹⁸https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
¹¹⁹https://developer.mozilla.org/en-US/docs/Web/Events/load
Chapter 3: Javascript Interview Questions 79

1 1 == '1'; // true
2 1 == [1]; // true
3 1 == true; // true
4 0 == ''; // true
5 0 == '0'; // true
6 0 == false; // true

My advice is never to use the == operator, except for convenience


when comparing against null or undefined, where a == null will
return true if a is null or undefined.

1 var a = null;
2 console.log(a == null); // true
3 console.log(a == undefined); // true

References

• equals operator¹²⁰

Explain the same-origin policy with


regards to JavaScript.
The same-origin policy prevents JavaScript from making requests
across domain boundaries. An origin is defined as a combination
of URI scheme, hostname, and port number. This policy prevents a
malicious script on one page from obtaining access to sensitive data
on another web page through that page’s Document Object Model.
¹²⁰https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-
in-javascript-comparisons
Chapter 3: Javascript Interview Questions 80

References

• same origin poliycy¹²¹

Make this work:


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

1 function duplicate(arr) {
2 return arr.concat(arr);
3 }
4
5 duplicate([1, 2, 3, 4, 5]); // [1,2,3,4,5,1,2,3,4,5]

Or with ES6:

1 const duplicate = (arr) => [...arr, ...arr];


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

Why is it called a Ternary


expression, what does the word
“Ternary” indicate?

“Ternary” indicates three, and a ternary expression accepts three


operands, the test condition, the “then” expression and the “else”
expression. Ternary expressions are not specific to JavaScript and
I’m not sure why it is even in this list.
¹²¹https://en.wikipedia.org/wiki/Same-origin_policy
Chapter 3: Javascript Interview Questions 81

References

• conditional operator¹²²

What is "use strict";? What are the


advantages and disadvantages to
using it?

‘use strict’ is a statement used to enable strict mode to entire scripts


or individual functions. Strict mode is a way to opt into a restricted
variant of JavaScript.
Advantages:

• Makes it impossible to accidentally create global variables.


• Makes assignments which would otherwise silently fail to
throw an exception.
• Makes attempts to delete undeletable properties throw (where
before the attempt would simply have no effect).
• Requires that function parameter names be unique.
• this is undefined in the global context.
• It catches some common coding bloopers, throwing excep-
tions.
• It disables features that are confusing or poorly thought out.

Disadvantages:

• Many missing features that some developers might be used


to.
• No more access to function.caller and function.arguments.
¹²²https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/
Conditional_Operator
Chapter 3: Javascript Interview Questions 82

• Concatenation of scripts written in different strict modes


might cause issues.

Overall, I think the benefits outweigh the disadvantages, and I


never had to rely on the features that strict mode blocks. I would
recommend using strict mode.

References

• strict mode¹²³
• js use strict¹²⁴

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.

Check out this version of FizzBuzz by Paul Irish¹²⁵.

1 for (let i = 1; i <= 100; i++) {


2 let f = i % 3 == 0,
3 b = i % 5 == 0;
4 console.log(f ? (b ? 'FizzBuzz' : 'Fizz') : b ? 'Buzz' \
5 : i);
6 }
¹²³http://2ality.com/2011/10/strict-mode-hatred.html
¹²⁴http://lucybain.com/blog/2014/js-use-strict/
¹²⁵https://gist.github.com/jaysonrowe/1592432#gistcomment-790724
Chapter 3: Javascript Interview Questions 83

I would not advise you to write the above during interviews


though. Just stick with the long but clear approach. For more wacky
versions of FizzBuzz, check out the reference link below.

References

• loop¹²⁶

Why is it, in general, a good idea to


leave the global scope of a website
as-is and never touch it?
Every script has access to the global scope, and if everyone uses
the global namespace to define their variables, collisions will likely
occur. Use the module pattern (IIFEs) to encapsulate your variables
within a local namespace.

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?
The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and
all the images, scripts, links and sub-frames have finished loading.
¹²⁶https://gist.github.com/jaysonrowe/1592432
Chapter 3: Javascript Interview Questions 84

The DOM event DOMContentLoaded will fire after the DOM for the
page has been constructed, but do not wait for other resources to
finish loading. This is preferred in certain cases when you do not
need the full page to be loaded before initializing.
TODO.

References
• onload¹²⁷

Explain what a single page app is


and how to make one SEO-friendly.
The below is taken from the awesome Grab Front End Guide¹²⁸,
which coincidentally, is written by me!
Web developers these days refer to the products they build as
web apps, rather than websites. While there is no strict difference
between the two terms, web apps tend to be highly interactive
and dynamic, allowing the user to perform actions and receive a
response to their action. Traditionally, the browser receives HTML
from the server and renders it. When the user navigates to another
URL, a full-page refresh is required and the server sends fresh new
HTML to the new page. This is called server-side rendering.
However, in modern SPAs, client-side rendering is used instead.
The browser loads the initial page from the server, along with the
scripts (frameworks, libraries, app code) and stylesheets required
for the whole app. When the user navigates to other pages, a
page refresh is not triggered. The URL of the page is updated via
the HTML5 History API¹²⁹. New data required for the new page,
¹²⁷https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
¹²⁸https://github.com/grab/front-end-guide
¹²⁹https://developer.mozilla.org/en-US/docs/Web/API/History_API
Chapter 3: Javascript Interview Questions 85

usually in JSON format, is retrieved by the browser via AJAX¹³⁰


requests to the server. The SPA then dynamically updates the page
with the data via JavaScript, which it has already downloaded in
the initial page load. This model is similar to how native mobile
apps work.
The benefits:

• The app feels more responsive and users do not see the flash
between page navigations due to full-page refreshes.
• Fewer HTTP requests are made to the server, as the same
assets do not have to be downloaded again for each page load.
• Clear separation of the concerns between the client and the
server; you can easily build new clients for different platforms
(e.g. mobile, chatbots, smart watches) without having to
modify the server code. You can also modify the technology
stack on the client and server independently, as long as the
API contract is not broken.

The downsides:

• Heavier initial page load due to the loading of framework,


app code, and assets required for multiple pages.
• There’s an additional step to be done on your server which is
to configure it to route all requests to a single entry point and
allow client-side routing to take over from there.
• SPAs are reliant on JavaScript to render content, but not all
search engines execute JavaScript during crawling, and they
may see empty content on your page. This inadvertently hurts
the Search Engine Optimization (SEO) of your app. However,
most of the time, when you are building apps, SEO is not
the most important factor, as not all the content needs to
be indexable by search engines. To overcome this, you can
either server-side render your app or use services such as
¹³⁰https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
Chapter 3: Javascript Interview Questions 86

Prerender¹³¹ to “render your javascript in a browser, save the


static HTML, and return that to the crawlers”.

References

• single page apps¹³²


• single page advantages¹³³

What is the extent of your


experience with Promises and/or
their polyfills?
Possess working knowledge of it. A promise is an object that may
produce a single value sometime in the future: either a resolved
value or a reason that it’s not resolved (e.g., a network error
occurred). A promise may be in one of 3 possible states: fulfilled,
rejected, or pending. Promise users can attach callbacks to handle
the fulfilled value or the reason for rejection.
Some common polyfills are $.deferred, Q and Bluebird but not all
of them comply with the specification. ES2015 supports Promises
out of the box and polyfills are typically not needed these days.

References

• promise¹³⁴
¹³¹https://prerender.io/
¹³²https://github.com/grab/front-end-guide#single-page-apps-spas
¹³³http://stackoverflow.com/questions/21862054/single-page-app-advantages-and-
disadvantages
¹³⁴https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-
promise-27fc71e77261
Chapter 3: Javascript Interview Questions 87

What are the pros and cons of using


Promises instead of callbacks?
Pros

• Avoid callback hell which can be unreadable.


• Makes it easy to write sequential asynchronous code that is
readable with .then().
• Makes it easy to write parallel asynchronous code with
Promise.all().
• With promises, these scenarios which are present in callbacks-
only coding, will not happen:
– Call the callback too early
– Call the callback too late (or never)
– Call the callback too few or too many times
– Fail to pass along any necessary environment/parame-
ters
– Swallow any errors/exceptions that may happen

Cons

• Slightly more complex code (debatable).


• In older browsers where ES2015 is not supported, you need to
load a polyfill in order to use it.

References

• async performance¹³⁵
¹³⁵https://github.com/getify/You-Dont-Know-JS/blob/master/async%20%26%
20performance/ch3.md
Chapter 3: Javascript Interview Questions 88

What are some of the


advantages/disadvantages of
writing JavaScript code in a language
that compiles to JavaScript?
Some examples of languages that compile to JavaScript include
CoffeeScript, Elm, ClojureScript, PureScript, and TypeScript.
Advantages:

• Fixes some of the longstanding problems in JavaScript and


discourages JavaScript anti-patterns.
• Enables you to write shorter code, by providing some syn-
tactic sugar on top of JavaScript, which I think ES5 lacks, but
ES2015 is awesome.
• Static types are awesome (in the case of TypeScript) for large
projects that need to be maintained over time.

Disadvantages:

• Require a build/compile process as browsers only run JavaScript


and your code will need to be compiled into JavaScript before
being served to browsers.
• Debugging can be a pain if your source maps do not map
nicely to your pre-compiled source.
• Most developers are not familiar with these languages and
will need to learn it. There’s a ramp up cost involved for your
team if you use it for your projects.
• Smaller community (depends on the language), which means
resources, tutorials, libraries, and tooling would be harder to
find.
• IDE/editor support might be lacking.
Chapter 3: Javascript Interview Questions 89

• These languages will always be behind the latest JavaScript


standard.
• Developers should be cognizant of what their code is being
compiled to—because that is what would actually be running,
and that is what matters in the end.

Practically, ES2015 has vastly improved JavaScript and made it


much nicer to write. I don’t really see the need for CoffeeScript
these days.

References

• coffee script¹³⁶

What tools and techniques do you


use for debugging JavaScript code?
• React and Redux
– React Devtools¹³⁷
– Redux Devtools¹³⁸
• Vue
– Vue Devtools¹³⁹
• JavaScript
– Chrome Devtools¹⁴⁰
– debugger statement
– Good old console.log debugging
¹³⁶https://softwareengineering.stackexchange.com/questions/72569/what-are-the-pros-
and-cons-of-coffeescript
¹³⁷https://github.com/facebook/react-devtools
¹³⁸https://github.com/gaearon/redux-devtools
¹³⁹https://github.com/vuejs/vue-devtools
¹⁴⁰https://hackernoon.com/twelve-fancy-chrome-devtools-tips-dc1e39d10d9d
Chapter 3: Javascript Interview Questions 90

References
• devtools¹⁴¹
• debugging¹⁴²

What language constructions do you


use for iterating over object
properties and array items?
For objects:

• for-in loops - for (var property in obj) { console.log(property);


}. However, this will also iterate through its inherited prop-
erties, and you will add an obj.hasOwnProperty(property)
check before using it.
• Object.keys() - Object.keys(obj).forEach(function (property)
{ ... }). Object.keys() is a static method that will lists all
enumerable properties of the object that you pass it.
• Object.getOwnPropertyNames() - Object.getOwnPropertyNames(obj).forEach
(property) { ... }). Object.getOwnPropertyNames() is a
static method that will lists all enumerable and non-enumerable
properties of the object that you pass it.

For arrays:

• for loops - for (var i = 0; i < arr.length; i++). The


common pitfall here is that var is in the function scope and
not the block scope and most of the time you would want
block scoped iterator variable. ES2015 introduces let which
has block scope and it is recommended to use that instead. So
this becomes: for (let i = 0; i < arr.length; i++).
¹⁴¹https://hackernoon.com/twelve-fancy-chrome-devtools-tips-dc1e39d10d9d
¹⁴²https://raygun.com/blog/javascript-debugging/
Chapter 3: Javascript Interview Questions 91

• forEach - arr.forEach(function (el, index) { ... }). This


construct can be more convenient at times because you do
not have to use the index if all you need is the array elements.
There are also the every and some methods which will allow
you to terminate the iteration early.
• for-of loops - for (let elem of arr) { ... }. ES6 introduces
a new loop, the for-of loop, that allows you to loop over
objects that conform to the iterable protocol¹⁴³ such as String,
Array, Map, Set, etc. It combines the advantages of the for loop
and the forEach() method. The advantage of the for loop is
that you can break from it, and the advantage of forEach()
is that it is more concise than the for loop because you don’t
need a counter variable. With the for-of loop, you get both
the ability to break from a loop and a more concise syntax.

Most of the time, I would prefer the .forEach method, but it really
depends on what you are trying to do. Before ES6, we used for loops
when we needed to prematurely terminate the loop using break.
But now with ES6, we can do that with for-of loops. I would use
for loops when I need even more flexibility, such as incrementing
the iterator more than once per loop.
Also, when using the for-of loop, if you need to access both the
index and value of each array element, you can do so with the ES6
Array entries() method and destructuring:

1 const arr = ['a', 'b', 'c'];


2
3 for (let [index, elem] of arr.entries()) {
4 console.log(index, ': ', elem);
5 }
¹⁴³https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_
protocols#The_iterable_protocol
Chapter 3: Javascript Interview Questions 92

References

• foreach¹⁴⁴
• array¹⁴⁵

Explain the difference between


mutable and immutable objects.
Immutability is a core principle in functional programming, and
has lots to offer to object-oriented programs as well. A mutable
object is an object whose state can be modified after it is created.
An immutable object is an object whose state cannot be modified
after it is created.

What is an example of an immutable object


in JavaScript?

In JavaScript, some built-in types (numbers, strings) are immutable,


but custom objects are generally mutable.
Some built-in immutable JavaScript objects are Math, Date.
Here are a few ways to add/simulate immutability on plain JavaScript
objects.
Object Constant Properties
By combining writable: false and configurable: false, you
can essentially create a constant (cannot be changed, redefined or
deleted) as an object property, like:

¹⁴⁴http://2ality.com/2015/08/getting-started-es6.html#from-for-to-foreach-to-for-of
¹⁴⁵https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/
Array/entries
Chapter 3: Javascript Interview Questions 93

1 let myObject = {};


2 Object.defineProperty(myObject, 'number', {
3 value: 42,
4 writable: false,
5 configurable: false,
6 });
7 console.log(myObject.number); // 42
8 myObject.number = 43;
9 console.log(myObject.number); // 42

Prevent Extensions
If you want to prevent an object from having new properties added
to it, but otherwise leave the rest of the object’s properties alone,
call Object.preventExtensions(...):

1 var myObject = {
2 a: 2,
3 };
4
5 Object.preventExtensions(myObject);
6
7 myObject.b = 3;
8 myObject.b; // undefined

In non-strict mode, the creation of b fails silently. In strict mode, it


throws a TypeError.
Seal
Object.seal() creates a “sealed” object, which means it takes an
existing object and essentially calls Object.preventExtensions()
on it, but also marks all its existing properties as configurable:
false.

So, not only can you not add any more properties, but you also
cannot reconfigure or delete any existing properties (though you
can still modify their values).
Chapter 3: Javascript Interview Questions 94

Freeze
Object.freeze() creates a frozen object, which means it takes an
existing object and essentially calls Object.seal() on it, but it also
marks all “data accessor” properties as writable:false, so that their
values cannot be changed.
This approach is the highest level of immutability that you can
attain for an object itself, as it prevents any changes to the object
or to any of its direct properties (though, as mentioned above, the
contents of any referenced other objects are unaffected).

1 var immutable = Object.freeze({});

Freezing an object does not allow new properties to be added to an


object and prevents from removing or altering the existing proper-
ties. Object.freeze() preserves the enumerability, configurability,
writability and the prototype of the object. It returns the passed
object and does not create a frozen copy.

What are the pros and cons of


immutability?
Pros

• Easier change detection - Object equality can be determined


in a performant and easy manner through referential equality.
This is useful for comparing object differences in React and
Redux.
• Programs with immutable objects are less complicated to
think about, since you don’t need to worry about how an
object may evolve over time.
• Defensive copies are no longer necessary when immutable
objects are returning from or passed to functions, since there
is no possibility an immutable object will be modified by it.
Chapter 3: Javascript Interview Questions 95

• Easy sharing via references - One copy of an object is just as


good as another, so you can cache objects or reuse the same
object multiple times.
• Thread-safe - Immutable objects can be safely used between
threads in a multi-threaded environment since there is no
risk of them being modified in other concurrently running
threads.
• Using libraries like ImmmutableJS, objects are modified using
structural sharing and less memory is needed for having
multiple objects with similar structures.

Cons

• Naive implementations of immutable data structures and its


operations can result in extremely poor performance because
new objects are created each time. It is recommended to use
libraries for efficient immutable data structures and opera-
tions that leverage on structural sharing.
• Allocation (and deallocation) of many small objects rather
than modifying existing ones can cause a performance im-
pact. The complexity of either the allocator or the garbage
collector usually depends on the number of objects on the
heap.
• Cyclic data structures such as graphs are difficult to build. If
you have two objects which can’t be modified after initializa-
tion, how can you get them to point to each other?

References

• immutability¹⁴⁶
¹⁴⁶https://stackoverflow.com/questions/1863515/pros-cons-of-immutability-vs-mutability
Chapter 3: Javascript Interview Questions 96

How can you achieve immutability


in your own code?
One way to achieve immutability is to use libraries like immutable.js¹⁴⁷,
mori¹⁴⁸ or immer¹⁴⁹.
The alternative is to use const declarations combined with the
techniques mentioned above for creation. For “mutating” objects,
use the spread operator, Object.assign, Array.concat(), etc., to
create new objects instead of mutate the original object.
Examples:

1 // Array Example
2 const arr = [1, 2, 3];
3 const newArr = [...arr, 4]; // [1, 2, 3, 4]
4
5 // Object Example
6 const human = Object.freeze({race: 'human'});
7 const john = {...human, name: 'John'}; // {race: "human",\
8 name: "John"}
9 const alienJohn = {...john, race: 'alien'}; // {race: "al\
10 ien", name: "John"}

References

• pro cons immutability¹⁵⁰


• immutability javascript¹⁵¹
¹⁴⁷http://facebook.github.io/immutable-js/
¹⁴⁸https://github.com/swannodette/mori
¹⁴⁹https://github.com/immerjs/immer
¹⁵⁰https://stackoverflow.com/questions/1863515/pros-cons-of-immutability-vs-mutability
¹⁵¹https://www.sitepoint.com/immutability-javascript/
Chapter 3: Javascript Interview Questions 97

Explain the difference between


synchronous and asynchronous
functions.
Synchronous functions are blocking while asynchronous functions
are not. In synchronous functions, statements complete before the
next statement is run. In this case, the program is evaluated exactly
in order of the statements and execution of the program is paused
if one of the statements take a very long time.
Asynchronous functions usually accept a callback as a parameter
and execution continue on the next line immediately after the
asynchronous function is invoked. The callback is only invoked
when the asynchronous operation is complete and the call stack
is empty. Heavy duty operations such as loading data from a
web server or querying a database should be done asynchronously
so that the main thread can continue executing other operations
instead of blocking until that long operation to complete (in the
case of browsers, the UI will freeze).

What is event loop? What is the


difference between call stack and
task queue?
The event loop is a single-threaded loop that monitors the call stack
and checks if there is any work to be done in the task queue. If
the call stack is empty and there are callback functions in the task
queue, a function is dequeued and pushed onto the call stack to be
executed.
If you haven’t already checked out Philip Robert’s talk on the
Chapter 3: Javascript Interview Questions 98

Event Loop¹⁵², you should. It is one of the most viewed videos on


JavaScript.

References
• event loop¹⁵³
• event loop stack¹⁵⁴

Explain the differences on the usage


of foo between function foo() {} and
var foo = function() {}

The former is a function declaration while the latter is a function


expression. The key difference is that function declarations have its
body hoisted but the bodies of function expressions are not (they
have the same hoisting behavior as variables). For more explanation
on hoisting, refer to the question above on hoisting. If you try to
invoke a function expression before it is defined, you will get an
Uncaught TypeError: XXX is not a function error.

Function Declaration

1 foo(); // 'FOOOOO'
2 function foo() {
3 console.log('FOOOOO');
4 }

Function Expression
¹⁵²https://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-
anyway.html
¹⁵³https://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-
anyway.html
¹⁵⁴http://theproactiveprogrammer.com/javascript/the-javascript-event-loop-a-stack-and-
a-queue/
Chapter 3: Javascript Interview Questions 99

1 foo(); // Uncaught TypeError: foo is not a function


2 var foo = function () {
3 console.log('FOOOOO');
4 };

References

• function¹⁵⁵

What are the differences between


variables created using let, var or
const?

Variables declared using the var keyword are scoped to the function
in which they are created, or if created outside of any function, to
the global object. let and const are block scoped, meaning they
are only accessible within the nearest set of curly braces (function,
if-else block, or for-loop).

1 function foo() {
2 // All variables are accessible within functions.
3 var bar = 'bar';
4 let baz = 'baz';
5 const qux = 'qux';
6
7 console.log(bar); // bar
8 console.log(baz); // baz
9 console.log(qux); // qux
10 }
11
¹⁵⁵https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/
function
Chapter 3: Javascript Interview Questions 100

12 console.log(bar); // ReferenceError: bar is not defined


13 console.log(baz); // ReferenceError: baz is not defined
14 console.log(qux); // ReferenceError: qux is not defined

1 if (true) {
2 var bar = 'bar';
3 let baz = 'baz';
4 const qux = 'qux';
5 }
6
7 // var declared variables are accessible anywhere in the \
8 function scope.
9 console.log(bar); // bar
10 // let and const defined variables are not accessible out\
11 side of the block they were defined in.
12 console.log(baz); // ReferenceError: baz is not defined
13 console.log(qux); // ReferenceError: qux is not defined

var allows variables to be hoisted, meaning they can be referenced


in code before they are declared. let and const will not allow this,
instead throwing an error.

1 console.log(foo); // undefined
2
3 var foo = 'foo';
4
5 console.log(baz); // ReferenceError: can't access lexical\
6 declaration 'baz' before initialization
7
8 let baz = 'baz';
9
10 console.log(bar); // ReferenceError: can't access lexical\
11 declaration 'bar' before initialization
12
13 const bar = 'bar';
Chapter 3: Javascript Interview Questions 101

Redeclaring a variable with var will not throw an error, but let and
const will.

1 var foo = 'foo';


2 var foo = 'bar';
3 console.log(foo); // "bar"
4
5 let baz = 'baz';
6 let baz = 'qux'; // Uncaught SyntaxError: Identifier 'baz\
7 ' has already been declared

let and const differ in that let allows reassigning the variable’s
value while const does not.

1 // This is fine.
2 let foo = 'foo';
3 foo = 'bar';
4
5 // This causes an exception.
6 const baz = 'baz';
7 baz = 'qux';

References

• let¹⁵⁶
• var¹⁵⁷
¹⁵⁶https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
¹⁵⁷https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
Chapter 3: Javascript Interview Questions 102

What are the differences between


ES6 class and ES5 function
constructors?
Let’s first look at example of each:

1 // ES5 Function Constructor


2 function Person(name) {
3 this.name = name;
4 }
5
6 // ES6 Class
7 class Person {
8 constructor(name) {
9 this.name = name;
10 }
11 }

For simple constructors, they look pretty similar.


The main difference in the constructor comes when using inheri-
tance. If we want to create a Student class that subclasses Person
and add a studentId field, this is what we have to do in addition to
the above.
Chapter 3: Javascript Interview Questions 103

1 // ES5 Function Constructor


2 function Student(name, studentId) {
3 // Call constructor of superclass to initialize supercl\
4 ass-derived members.
5 Person.call(this, name);
6
7 // Initialize subclass's own members.
8 this.studentId = studentId;
9 }
10
11 Student.prototype = Object.create(Person.prototype);
12 Student.prototype.constructor = Student;
13
14 // ES6 Class
15 class Student extends Person {
16 constructor(name, studentId) {
17 super(name);
18 this.studentId = studentId;
19 }
20 }

It’s much more verbose to use inheritance in ES5 and the ES6
version is easier to understand and remember.

References

• inheritance¹⁵⁸
• classical inheritance¹⁵⁹
¹⁵⁸https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance
¹⁵⁹https://eli.thegreenplace.net/2013/10/22/classical-inheritance-in-javascript-es5
Chapter 3: Javascript Interview Questions 104

Can you offer a use case for the new


arrow ⇒ function syntax? How does
this new syntax differ from other
functions?
One obvious benefit of arrow functions is to simplify the syn-
tax needed to create functions, without a need for the function
keyword. The this within arrow functions is also bound to the
enclosing scope which is different compared to regular functions
where the this is determined by the object calling it. Lexically-
scoped this is useful when invoking callbacks especially in React
components.

What advantage is there for using


the arrow syntax for a method in a
constructor?
The main advantage of using an arrow function as a method inside
a constructor is that the value of this gets set at the time of
the function creation and can’t change after that. So, when the
constructor is used to create a new object, this will always refer to
that object. For example, let’s say we have a Person constructor that
takes a first name as an argument has two methods to console.log
that name, one as a regular function and one as an arrow function:
Chapter 3: Javascript Interview Questions 105

1 const Person = function (firstName) {


2 this.firstName = firstName;
3 this.sayName1 = function () {
4 console.log(this.firstName);
5 };
6 this.sayName2 = () => {
7 console.log(this.firstName);
8 };
9 };
10
11 const john = new Person('John');
12 const dave = new Person('Dave');
13
14 john.sayName1(); // John
15 john.sayName2(); // John
16
17 // The regular function can have its 'this' value changed\
18 , but the arrow function cannot
19 john.sayName1.call(dave); // Dave (because "this" is now \
20 the dave object)
21 john.sayName2.call(dave); // John
22
23 john.sayName1.apply(dave); // Dave (because 'this' is now\
24 the dave object)
25 john.sayName2.apply(dave); // John
26
27 john.sayName1.bind(dave)(); // Dave (because 'this' is no\
28 w the dave object)
29 john.sayName2.bind(dave)(); // John
30
31 var sayNameFromWindow1 = john.sayName1;
32 sayNameFromWindow1(); // undefined (because 'this' is now\
33 the window object)
34
35 var sayNameFromWindow2 = john.sayName2;
Chapter 3: Javascript Interview Questions 106

36 sayNameFromWindow2(); // John

The main takeaway here is that this can be changed for a normal
function, but the context always stays the same for an arrow
function. So even if you are passing around your arrow function
to different parts of your application, you wouldn’t have to worry
about the context changing.
This can be particularly helpful in React class components. If you
define a class method for something such as a click handler using
a normal function, and then you pass that click handler down into
a child component as a prop, you will need to also bind this in the
constructor of the parent component. If you instead use an arrow
function, there is no need to also bind “this”, as the method will
automatically get its “this” value from its enclosing lexical context.
See this article for an excellent demonstration and sample code:
Handle Events in React¹⁶⁰

References

• arrow functions¹⁶¹
• react arrow functions¹⁶²

What is the definition of a


higher-order function?
A higher-order function is any function that takes one or more
functions as arguments, which it uses to operate on some data,
¹⁶⁰https://medium.com/@machnicki/handle-events-in-react-with-arrow-functions-
ede88184bbb
¹⁶¹https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_
functions
¹⁶²https://medium.com/@machnicki/handle-events-in-react-with-arrow-functions-
ede88184bbb
Chapter 3: Javascript Interview Questions 107

and/or returns a function as a result. Higher-order functions are


meant to abstract some operation that is performed repeatedly. The
classic example of this is map, which takes an array and a function
as arguments. map then uses this function to transform each item in
the array, returning a new array with the transformed data. Other
popular examples in JavaScript are forEach, filter, and reduce.
A higher-order function doesn’t just need to be manipulating
arrays as there are many use cases for returning a function from
another function. Function.prototype.bind is one such example
in JavaScript.
Map
Let say we have an array of names which we need to transform
each string to uppercase.

1 const names = ['irish', 'daisy', 'anna'];

The imperative way will be as such:

1 const transformNamesToUppercase = function (names) {


2 const results = [];
3 for (let i = 0; i < names.length; i++) {
4 results.push(names[i].toUpperCase());
5 }
6 return results;
7 };
8 transformNamesToUppercase(names); // ['IRISH', 'DAISY', '\
9 ANNA']

Use .map(transformerFn) makes the code shorter and more declar-


ative.
Chapter 3: Javascript Interview Questions 108

1 const transformNamesToUppercase = function (names) {


2 return names.map((name) => name.toUpperCase());
3 };
4 transformNamesToUppercase(names); // ['IRISH', 'DAISY', '\
5 ANNA']

References

• higher order functions¹⁶³


• js first class¹⁶⁴

Can you give an example for


destructuring an object or an array?
Destructuring is an expression available in ES6 which enables a
succinct and convenient way to extract values of Objects or Arrays
and place them into distinct variables.
Array destructuring

1 // Variable assignment.
2 const foo = ['one', 'two', 'three'];
3
4 const [one, two, three] = foo;
5 console.log(one); // "one"
6 console.log(two); // "two"
7 console.log(three); // "three"

¹⁶³https://medium.com/javascript-scene/higher-order-functions-composing-software-
5365cf2cbe99
¹⁶⁴https://hackernoon.com/effective-functional-javascript-first-class-and-higher-order-
functions-713fde8df50a
Chapter 3: Javascript Interview Questions 109

1 // Swapping variables
2 let a = 1;
3 let b = 3;
4
5 [a, b] = [b, a];
6 console.log(a); // 3
7 console.log(b); // 1

Object destructuring

1 // Variable assignment.
2 const o = {p: 42, q: true};
3 const {p, q} = o;
4
5 console.log(p); // 42
6 console.log(q); // true

References

• destructuring¹⁶⁵
• es6 destructure¹⁶⁶

ES6 Template Literals offer a lot of


flexibility in generating strings, can
you give an example?
Template literals help make it simple to do string interpolation, or
to include variables in a string. Before ES2015, it was common to
do something like this:
¹⁶⁵https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/
Destructuring_assignment
¹⁶⁶https://ponyfoo.com/articles/es6-destructuring-in-depth
Chapter 3: Javascript Interview Questions 110

1 var person = {name: 'Tyler', age: 28};


2 console.log(
3 'Hi, my name is ' + person.name + ' and I am ' + person\
4 .age + ' years old!',
5 );
6 // 'Hi, my name is Tyler and I am 28 years old!'

With template literals, you can now create that same output like
this instead:

1 const person = {name: 'Tyler', age: 28};


2 console.log(`Hi, my name is ${person.name} and I am ${per\
3 son.age} years old!`);
4 // 'Hi, my name is Tyler and I am 28 years old!'

Note that you use backticks, not quotes, to indicate that you are
using a template literal and that you can insert expressions inside
the ${} placeholders.
A second helpful use case is in creating multi-line strings. Before
ES2015, you could create a multi-line string like this:

1 console.log('This is line one.\nThis is line two.');


2 // This is line one.
3 // This is line two.

Or if you wanted to break it up into multiple lines in your code so


you didn’t have to scroll to the right in your text editor to read a
long string, you could also write it like this:

1 console.log('This is line one.\n' + 'This is line two.');


2 // This is line one.
3 // This is line two.

Template literals, however, preserve whatever spacing you add to


them. For example, to create that same multi-line output that we
created above, you can simply do:
Chapter 3: Javascript Interview Questions 111

1 console.log(`This is line one.


2 This is line two.`);
3 // This is line one.
4 // This is line two.

Another use case of template literals would be to use as a substitute


for templating libraries for simple variable interpolations:

1 const person = {name: 'Tyler', age: 28};


2 document.body.innerHTML = `
3 <div>
4 <p>Name: ${person.name}</p>
5 <p>Name: ${person.age}</p>
6 </div>
7 `;

Note that your code may be susceptible to XSS by using .innerHTML.


Sanitize your data before displaying it if it came from a user!

References

• template literals¹⁶⁷

Can you give an example of a curry


function and why this syntax offers
an advantage?
Currying is a pattern where a function with more than one param-
eter is broken into multiple functions that, when called in series,
will accumulate all of the required parameters one at a time. This
¹⁶⁷https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Chapter 3: Javascript Interview Questions 112

technique can be useful for making code written in a functional


style easier to read and compose. It’s important to note that for
a function to be curried, it needs to start out as one function,
then broken out into a sequence of functions that each accepts one
parameter.

1 function curry(fn) {
2 if (fn.length === 0) {
3 return fn;
4 }
5
6 function _curried(depth, args) {
7 return function (newArgument) {
8 if (depth - 1 === 0) {
9 return fn(...args, newArgument);
10 }
11 return _curried(depth - 1, [...args, newArgument]);
12 };
13 }
14
15 return _curried(fn.length, []);
16 }
17
18 function add(a, b) {
19 return a + b;
20 }
21
22 var curriedAdd = curry(add);
23 var addFive = curriedAdd(5);
24
25 var result = [0, 1, 2, 3, 4, 5].map(addFive); // [5, 6, 7\
26 , 8, 9, 10]
Chapter 3: Javascript Interview Questions 113

References

• currying¹⁶⁸

What are the benefits of using


spread syntax and how is it different
from rest syntax?
ES6’s spread syntax is very useful when coding in a functional
paradigm as we can easily create copies of arrays or objects
without resorting to Object.create, slice, or a library function.
This language feature is used often in Redux and RxJS projects.

1 function putDookieInAnyArray(arr) {
2 return [...arr, 'dookie'];
3 }
4
5 const result = putDookieInAnyArray(['I', 'really', "don't\
6 ", 'like']); // ["I", "really", "don't", "like", "dookie"\
7 ]
8
9 const person = {
10 name: 'Todd',
11 age: 29,
12 };
13
14 const copyOfTodd = {...person};

ES6’s rest syntax offers a shorthand for including an arbitrary


number of arguments to be passed to a function. It is like an
inverse of the spread syntax, taking data and stuffing it into an
¹⁶⁸https://hackernoon.com/currying-in-js-d9ddc64f162e
Chapter 3: Javascript Interview Questions 114

array rather than unpacking an array of data, and it works in


function arguments, as well as in array and object destructuring
assignments.

1 function addFiveToABunchOfNumbers(...numbers) {
2 return numbers.map((x) => x + 5);
3 }
4
5 const result = addFiveToABunchOfNumbers(4, 5, 6, 7, 8, 9,\
6 10); // [9, 10, 11, 12, 13, 14, 15]
7
8 const [a, b, ...rest] = [1, 2, 3, 4]; // a: 1, b: 2, rest\
9 : [3, 4]
10
11 const {e, f, ...others} = {
12 e: 1,
13 f: 2,
14 g: 3,
15 h: 4,
16 }; // e: 1, f: 2, others: { g: 3, h: 4 }

References
• spread syntax¹⁶⁹
• rest parameters¹⁷⁰

How can you share code between


files?
This depends on the JavaScript environment.
¹⁶⁹https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_
syntax
¹⁷⁰https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_
parameters
Chapter 3: Javascript Interview Questions 115

On the client (browser environment), as long as the variables/func-


tions are declared in the global scope (window), all scripts can refer
to them. Alternatively, adopt the Asynchronous Module Definition
(AMD) via RequireJS for a more modular approach.
On the server (Node.js), the common way has been to use Com-
monJS. Each file is treated as a module and it can export variables
and functions by attaching them to the module.exports object.
ES2015 defines a module syntax which aims to replace both AMD
and CommonJS. This will eventually be supported in both browser
and Node environments.

References
• whyamd¹⁷¹
• moudles¹⁷²

Why you might want to create static


class members?
Static class members (properties/methods) are not tied to a specific
instance of a class and have the same value regardless of which
instance is referring to it. Static properties are typically configura-
tion variables and static methods are usually pure utility functions
which do not depend on the state of the instance.

References
• static variable methods¹⁷³
¹⁷¹http://requirejs.org/docs/whyamd.html
¹⁷²https://nodejs.org/docs/latest/api/modules.html
¹⁷³https://stackoverflow.com/questions/21155438/when-to-use-static-variables-methods-
and-when-to-use-instance-variables-methods
Keep developing your
interviewing skills
This book is just a starting point for you to get inspired to keep
preparing for tech and frontend development interviews.
The more questions and answers you can prep the more confidence
you will build, this will have 2 positive effects: An incredible
appetite to take more questions, and a positive and energyzed
attitude during your interview which increases the chances of
landing the job.
Also remember, the more courses you can take on technologies and
frameworks to develop great frontend applications the better.
I want to say thanks for taking your time and reading the whole
book, I really appreciate your commitment towards your education
and professional success, and for that I’d like to point you in the
right direction with the following incredible resources which will
help you achieve your goals.

• Sites with online courses with discounts: Online Courses¹⁷⁴


• Facebook community for developers: The Programming Hub¹⁷⁵
• Quora Group: The Programming Hub¹⁷⁶

I hope this book was useful, please feel free to contact me with
any questions. Also I would appreciate your honest review or any
feedback to improve the next editions of the book.
Thanks a lot for following along !!
¹⁷⁴https://coursesim.com
¹⁷⁵https://www.facebook.com/theproghub
¹⁷⁶https://www.quora.com/q/vlyubtzhdhpacqzr?invite_code=Yj9D6Z7H2Bf4CONidZmD
About the Author
Alejandro is a programmer and writer with the goal of inspiring
people to learn about several tech related topics.
He’s also a Udemy Instructor here’s a link to his profile: Alejandro
Garcia Udemy Instructor¹⁷⁷

Other Author Profiles

Amazon: Alejandro on Amazon¹⁷⁸


Leanpub: Alejandro on Leanpub¹⁷⁹

Copyright

The information in this book is distributed on an “As Is” basis,


without warranty. While every precaution has been taken in the
preparation of this work, neither the author nor the publisher shall
have any liability to any person or entity with respect to any loss
or damage caused or alleged to be caused directly or indirectly by
the information contained in it.
Chapters 1 - 3 licensed under MIT License¹⁸⁰

¹⁷⁷https://www.udemy.com/user/alejandro-garcia-172
¹⁷⁸https://www.amazon.com/Alejandro-Garcia/e/B08CF2H6TB
¹⁷⁹https://leanpub.com/u/alejandro-garcia
¹⁸⁰https://github.com/yangshun/front-end-interview-handbook/blob/master/LICENSE

You might also like