qns(quiz): extract from GFE

This commit is contained in:
Yangshun 2023-04-11 19:48:22 +08:00
parent cda773578a
commit 312e3927fa
184 changed files with 3716 additions and 0 deletions

View File

@ -0,0 +1,25 @@
---
title: Are you familiar with styling SVG?
---
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 SVGs you find on the web uses 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.
```html
<rect
x="10"
y="10"
width="100"
height="100"
stroke="blue"
fill="purple"
fill-opacity="0.5"
stroke-opacity="0.8" />
```
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 [overridden by CSS](https://css-tricks.com/presentation-attributes-vs-inline-styles/) styles defined in a stylesheet. Hence if you did something like `svg { fill: blue; }` it will override the purple fill that has been defined.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "are-you-familiar-with-styling-svg",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,41 @@
---
title: Can you describe the main difference between a `.forEach` loop and a `.map()` loop?
subtitle: 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.
```js
const a = [1, 2, 3];
const doubled = a.forEach((num, index) => {
// Do something with num and/or index.
});
// 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.
```js
const a = [1, 2, 3];
const doubled = a.map((num) => {
return num * 2;
});
// 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
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,15 @@
{
"slug": "can-you-describe-the-main-difference-between-a-foreach-loop-and-a-map-loop-and-why-you-would-pick-one-versus-the-other",
"languages": [],
"companies": [
"twitter"
],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,42 @@
---
title: Can you explain the difference between coding a website to be responsive versus using a mobile-first strategy?
---
These two approaches are not mutually exclusive. Making a website responsive means that some elements will respond 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.
```css
@media (min-width: 768px) {
.my-class {
font-size: 24px;
}
}
@media (max-width: 767px) {
.my-class {
font-size: 12px;
}
}
```
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:
```css
.my-class {
font-size: 12px;
}
@media (min-width: 768px) {
.my-class {
font-size: 24px;
}
}
```
A mobile-first strategy has the following 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.
- Mobile-first designs are more likely to be usable on larger devices (will just appear more stretched, but still usable). However, the reverse is not the case.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "can-you-explain-the-difference-between-coding-a-website-to-be-responsive-versus-using-a-mobile-first-strategy",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,42 @@
---
title: Can you give an example for destructuring an object or an array?
---
Destructuring is an expression available in ES2015 which enables a succinct and convenient way to extract values of Objects or Arrays and place them into distinct variables.
## Array destructuring
```js
// Variable assignment.
const foo = ['one', 'two', 'three'];
const [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"
```
```js
// Swapping variables
let a = 1;
let b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
```
## Object destructuring
```js
// Variable assignment.
const o = { p: 42, q: true };
const { p, q } = o;
console.log(p); // 42
console.log(q); // true
```
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "can-you-give-an-example-for-destructuring-an-object-or-an-array",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,37 @@
---
title: 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 parameter is broken into multiple functions that, when called in series, will accumulate all of the required parameters one at a time. This 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.
```js
function curry(fn) {
if (fn.length === 0) {
return fn;
}
function _curried(depth, args) {
return function (newArgument) {
if (depth - 1 === 0) {
return fn(...args, newArgument);
}
return _curried(depth - 1, [...args, newArgument]);
};
}
return _curried(fn.length, []);
}
function add(a, b) {
return a + b;
}
var curriedAdd = curry(add);
var addFive = curriedAdd(5);
var result = [0, 1, 2, 3, 4, 5].map(addFive); // [5, 6, 7, 8, 9, 10]
```
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "can-you-give-an-example-of-a-curry-function-and-why-this-syntax-offers-an-advantage",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,24 @@
---
title: Can you give an example of an `@media` property other than `screen`?
---
There are four types of `@media` properties (including `screen`):
- `all`: for all media type devices
- `print`: for printers
- `speech`: for screen readers that "reads" the page out loud
- `screen`: for computer screens, tablets, smart-phones etc.
Here is an example of `print` media type's usage:
```css
@media print {
body {
color: black;
}
}
```
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "can-you-give-an-example-of-an-media-property-other-than-screen",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,10 @@
---
title: Can you offer a use case for the new arrow => function syntax?
subtitle: How does this new syntax differ from other functions?
---
One obvious benefit of arrow functions is to simplify the syntax 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.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "can-you-offer-a-use-case-for-the-new-arrow-greater-function-syntax-how-does-this-new-syntax-differ-from-other-functions",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "high",
"difficulty": "medium"
}

View File

@ -0,0 +1,19 @@
---
title: 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](https://gist.github.com/jaysonrowe/1592432#gistcomment-790724).
```js
for (let i = 1; i <= 100; i++) {
let f = i % 3 == 0,
b = i % 5 == 0;
console.log(f ? (b ? 'FizzBuzz' : 'Fizz') : b ? 'Buzz' : i);
}
```
It is not advisable 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
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "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",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,28 @@
---
title: Why is it generally a good idea to position CSS `<link>`s between `<head></head>` and JS `<script>`s just before `</body>`?
subtitle: Do you know any exceptions?
---
In a nutshell, such a placement of CSS `<link>`s and JavaScript `<script>`s allows for faster rendering of the page and better overall performance.
## Placing `<link>`s in `<head>`
Putting `<link>`s in `<head>` is part of the 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. Placing CSS `<link>`s in the `<head>` ensures that the stylesheets are loaded and ready for use when the browser starts rendering the page.
This progressive rendering is a metric that sites are measured on in their performance 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>`
`<script>` tags block HTML parsing while they are being downloaded and executed which can slow down the display of your page. Placing the `<script>`s 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 an error and halt the entire script. If you need to put `<script>`s in the `<head>`, use the `defer` attribute, which will achieve the same effect of running the script only after the HTML is parsed but the browser can kick off the network request earlier to download the script.
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.
## `<head>` and `<body>` tags are now optional
As per the HTML5 specification, certain HTML tags like `<head>` and `<body>` are optional. Google's style guide even recommends removing them to save bytes. However, this practice is still not widely adopted and the performance gain is likely to be minimal and for most sites it's not likely going to matter.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/html-questions)

View File

@ -0,0 +1,15 @@
{
"slug": "css-link-between-head-and-js-script-just-before-body",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"html",
"performance"
],
"importance": "high",
"difficulty": "medium",
"featured": true
}

View File

@ -0,0 +1,22 @@
---
title: Describe Block Formatting Context (BFC) and how it works.
---
A Block Formatting Context (BFC) is part of the visual CSS rendering of a web page in which block boxes are laid out. Floats, absolutely positioned elements, `inline-blocks`, `table-cells`, `table-caption`s, 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](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context#Make_float_content_and_alongside_content_the_same_height). 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:
- 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`, `grid`, or `inline-grid`.
- 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](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing).
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "describe-block-formatting-context-bfc-and-how-it-works",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,9 @@
---
title: 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.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,14 @@
{
"slug": "describe-event-bubbling",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript",
"html"
],
"importance": "high",
"difficulty": "medium"
}

View File

@ -0,0 +1,34 @@
---
title: Describe `float`s 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.
## Clearfix hack
The `.clearfix` hack uses a clever CSS [pseudo-element](/questions/quiz/describe-pseudo-elements-and-discuss-what-they-are-used-for) (`::after`) to clear floats. Rather than setting the overflow on the parent, you apply an additional class `clearfix` to it. Then apply this CSS:
```css
.clearfix::after {
content: ' ';
visibility: hidden;
display: block;
height: 0;
clear: both;
}
```
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.
## Trivia
In the good old days, CSS frameworks such as Bootstrap 2 used the `float` property to implement its grid system. However with CSS Flexbox and Grid these days, there is no longer much need to use the `float` property.
## References
- [Clearfix: A Lesson In Web Development Evolution](https://css-tricks.com/clearfix-a-lesson-in-web-development-evolution/)
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "describe-floats-and-how-they-work",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,19 @@
---
title: Describe pseudo-elements and discuss what they are used for.
---
A CSS [pseudo-element](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements) 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`. Encourages separation of concerns because the triangle is considered part of styling and not really the DOM.
## Notes
- Pseudo-elements are different from [pseudo-classes](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes), which are used to style an element based on its _state_ (such as `:hover`, `:focus`, etc).
- Double colons should be used instead of single colon to distinguish pseudo-classes from pseudo-elements. Most browsers support both syntaxs since this distinction was not clear in legacy W3C specs.
## References
- [Pseudo-elements - CSS | MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements)
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "describe-pseudo-elements-and-discuss-what-they-are-used-for",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,28 @@
---
title: Describe the difference between a cookie, `sessionStorage` and `localStorage`.
---
## Similarities
Cookies, `localStorage`, and `sessionStorage`, are all:
- Storage mechanisms on the client side. This means the clients can read and modify the values.
- Key-value based storage.
- They are only able to store values as strings. Objects will have to be serialized into a string (`JSON.stringify()`) in order to be stored.
## Differences
| | Cookie | `localStorage` | `sessionStorage` |
| --- | --- | --- | --- |
| Initiator | Client or server. Server can use `Set-Cookie` header | Client | Client |
| Expiry | Manually set | Forever | On tab close |
| Persistent across browser sessions | Depends on whether expiration is set | Yes | No |
| Sent to server with every HTTP request | Cookies are automatically being sent via `Cookie` header | No | No |
| Capacity (per domain) | 4kb | 5MB | 5MB |
| Access | Any window | Any window | Same tab |
There are also other client-side storage mechanisms like [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) which is more powerful than the above-mentioned technologies but more complicated to use.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/html-questions)

View File

@ -0,0 +1,18 @@
{
"slug": "describe-the-difference-between-a-cookie-sessionstorage-and-localstorage",
"languages": [],
"companies": [
"bytedance"
],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"html",
"javascript"
],
"importance": "high",
"difficulty": "medium",
"featured": true,
"ranking": 2
}

View File

@ -0,0 +1,29 @@
---
title: Describe the difference between `<script>`, `<script async>` and `<script defer>`
---
`<script>` tags are used to include JavaScript on a web page. The `async` and `defer` attributes are used to change how/when the loading and execution of the script happens.
## Plain `<script>`
For normal `<script>` tags without any `async` or `defer`, when they are encountered, HTML parsing is blocked, the script is fetched and executed immediately. HTML parsing resumes after the script is executed.
## `<script async>`
In `<script async>`, the script will be fetched in parallel to HTML parsing and executed as soon as it is available (potentially before HTML parsing completes) and it will not necessarily be executed in the order in which it appears in the HTML document. Use `async` when the script is independent of any other scripts on the page, for example, analytics.
## `<script defer>`
In `<script defer>`, the script will be fetched in parallel to HTML parsing and executed when the documented has been fully parsed. If there are multiple of them, each deferred script is executed in the order they appeared in the HTML 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. A deferred script must not contain `document.write()`.
## Notes
Generally, the `async` attribute should be used for scripts that are not critical to the initial rendering of the page and do not depend on each other, while the `defer` attribute should be used for scripts that are critical to the initial rendering of the page or that depend on each other.
The `async` and `defer` attributes are ignored for scripts that have no `src` attribute.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/html-questions)

View File

@ -0,0 +1,16 @@
{
"slug": "describe-the-difference-between-script-async-and-script-defer",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"html",
"javascript"
],
"importance": "high",
"difficulty": "medium",
"featured": false,
"ranking": 1
}

View File

@ -0,0 +1,17 @@
---
title: Describe what you like and dislike about the CSS preprocessors you have used.
---
## Likes
- Mostly the advantages mentioned in ["What are the advantages/disadvantages of using CSS preprocessors?"](/questions/quiz/what-are-the-advantages-disadvantages-of-using-css-preprocessors).
- Less is written in JavaScript, which plays well with Node.
## Dislikes
- Sass relies on `node-sass`, which is a binding for LibSass written in C++. The library has to be recompiled frequently when when switching between Node.js versions.
- In Less, variable names are prefixed with `@`, which can be confused with native CSS keywords like `@media`, `@import` and `@font-face` rule.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "describe-what-you-like-and-dislike-about-the-css-preprocessors-you-have-used",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,17 @@
---
title: 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 positioned elements (elements which have a `position` value which is not `static`) and its descendants or flex items.
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 the 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 contents are stacked, the whole element is considered in the stacking order of the parent stacking context. A handful of CSS properties trigger a new stacking context, such as `opacity` less than 1, `filter` that is not `none`, and `transform` that is not`none`.
_**Note**: What exactly qualifies an element to create a stacking context is listed in this long set of [rules](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context#The_stacking_context)._
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "describe-z-index-and-how-stacking-context-is-formed",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,55 @@
---
title: What kind of things must you be wary of when designing or developing for multilingual sites?
---
Designing and developing for multilingual sites is part of internationalization (i18n).
## Search Engine Optimization
- Use the `lang` attribute on the `<html>` tag.
- Include the locale in the URL (e.g en_US, zh_CN, etc).
- Webpages should use `<link rel="alternate" hreflang="other_locale" href="url_for_other_locale">` to tell search engines that there is another page at the specified `href` with the same content but for another language/locale.
## Understanding the difference between locale vs language
Locale settings control how numbers, dates, and times display for your region: which may be a country, or a portion of country or may not even honor country boundaries.
## Language can differ between countries
Certain languages, especially the widely-spoken languages have different "flavors" in different countries (grammar rules, spelling, characters). It's important to differentiate languages for the target country and not assume/force one country's version of a language for all countries which speak the language. Examples:
- `en`: `en-US` (American English), `en-GB` (British English)
- `zh`: `zh-CN` (Chinese (Simplified)), `zh-TW` (Chinese (Traditional))
## Predict locale but don't restrict
Servers can determine the locale/language of visitors via a combination of HTTP `Accept-Language` headers and IPs. With these, visitors can automatically select the best locale for the visitor. However, predictions are not foolproof (especially if visitors are using VPNs) and visitors should still be allowed to change their country/language easily without hassle.
## Consider differences in the length of text in different languages
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. For example, some languages, such as German and French, tend to use longer words and sentences than English, which can cause layout issues if you do not take this into account.
## Language reading direction
Languages like English and French are written from left-to-right, top-to-bottom. However some languages, such as Hebrew and Arabic, are written from right to left. This can affect the layout of your site and the placement of elements on the page, so you must be careful to design your site in a way that accommodates different text directions.
## 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 `{% date %} 我会出发`. Note that the position of the variable is different due to grammar rules of the language.
## Formatting dates and currencies
Calendar dates are sometimes presented in different ways. Eg. "May 31, 2012" in the U.S. vs. "31 May 2012" in parts of Europe.
## Do not put text in images
Putting 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 support image text translation other languages, there needs to be a separate image created for each language which is not a scalable workflow for designers.
## Be mindful of how colors are perceived
Colors are perceived differently across languages and cultures. The design should use color appropriately.
## References
- [The Differences between Locales and Languages](https://devblogs.microsoft.com/setup/the-differences-between-locales-and-languages)
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/html-questions)

View File

@ -0,0 +1,15 @@
{
"slug": "designing-or-developing-for-multilingual-sites",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"html",
"i18n"
],
"importance": "mid",
"difficulty": "medium",
"featured": true
}

View File

@ -0,0 +1,11 @@
---
title: Difference between document `load` event and document `DOMContentLoaded` event?
---
The `DOMContentLoaded` event is fired when the initial HTML document 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
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "difference-between-document-load-event-and-document-domcontentloaded-event",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,27 @@
---
title: 'Difference between: `function Person(){}`, `var person = Person()`, and `var person = new Person()`?'
---
This question is pretty vague. Our 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.prototype)`.
```js
function Person(name) {
this.name = name;
}
var person = Person('John');
console.log(person); // undefined
console.log(person.name); // Uncaught TypeError: Cannot read property 'name' of undefined
var person = new Person('John');
console.log(person); // Person { name: "John" }
console.log(person.name); // "john"
```
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "difference-between-function-person-var-person-person-and-var-person-new-person",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,66 @@
---
title: ES2015 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:
```js
var person = { name: 'Tyler', age: 28 };
console.log(
'Hi, my name is ' + person.name + ' and I am ' + person.age + ' years old!',
);
// 'Hi, my name is Tyler and I am 28 years old!'
```
With template literals, you can now create that same output like this instead:
```js
const person = { name: 'Tyler', age: 28 };
console.log(`Hi, my name is ${person.name} and I am ${person.age} years old!`);
// '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:
```js
console.log('This is line one.\nThis is line two.');
// This is line one.
// 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:
```js
console.log('This is line one.\n' + 'This is line two.');
// This is line one.
// 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:
```js
console.log(`This is line one.
This is line two.`);
// This is line one.
// This is line two.
```
Another use case of template literals would be to use as a substitute for templating libraries for simple variable interpolations:
```js
const person = { name: 'Tyler', age: 28 };
document.body.innerHTML = `
<div>
<p>Name: ${person.name}</p>
<p>Age: ${person.age}</p>
</div>
`;
```
**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
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "es6-template-literals-offer-a-lot-of-flexibility-in-generating-strings-can-you-give-an-example",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,11 @@
---
title: Explain Ajax in as much detail as possible.
---
Ajax (asynchronous JavaScript and XML) is a set of web development 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 commonly 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
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,14 @@
{
"slug": "explain-ajax-in-as-much-detail-as-possible",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript",
"network"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,49 @@
---
title: Explain CSS sprites, and how you would implement them on a page or site.
---
CSS sprites combine multiple images into one single larger image file and uses a combination of CSS `background-image`, `background-position` and `background-size` to select a specific part of the larger image as the desired image.
It used to be a commonly-used technique for icons (e.g. Gmail uses sprites for all their images).
## 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.
## How to implement
1. Use a sprite generator that packs multiple images into one and generate the appropriate CSS for it.
1. Each image would have a corresponding CSS class with `background-image` and `background-position` properties defined.
1. To use that image, add the corresponding class to your element.
The generated stylesheet might look something like:
```css
.icon {
background-image: url('https://example.com/images/spritesheet.png');
width: 24px;
height: 24px;
}
.icon-cart {
background-position: 0 0;
}
.icon-arrow {
background-position: -24px 0;
}
```
And can be used in the HTML as such:
```html
<span class="icon icon-cart"></span>
<span class="icon icon-arrow"></span>
```
## References
- [Implementing image sprites in CSS - CSS: Cascading Style Sheets | MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Images/Implementing_image_sprites_in_CSS)
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,14 @@
{
"slug": "explain-css-sprites-and-how-you-would-implement-them-on-a-page-or-site",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css",
"performance"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,12 @@
---
title: Explain event delegation
---
Event delegation is a technique involving adding event listeners to a parent element instead of adding the event listeners to the descendant elements. The listener will fire whenever the event is triggered on the descendant elements due to the 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
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,16 @@
{
"slug": "explain-event-delegation",
"languages": [],
"companies": [
"linkedin"
],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript",
"html"
],
"importance": "high",
"difficulty": "medium"
}

View File

@ -0,0 +1,43 @@
---
title: Explain `Function.prototype.bind`
---
> 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.
_Source: [Function.prototype.bind() - JavaScript | MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind)_
`bind()` is most useful for binding the value of `this` in methods of classes that you want to pass into other functions. This was frequently done in React class component methods which were not defined using arrow functions.
```js
const john = {
age: 42,
getAge: function () {
return this.age;
},
};
console.log(john.getAge()); // 42
const unboundGetAge = john.getAge;
console.log(unboundGetAge()); // undefined
const boundGetAge = john.getAge.bind(john);
console.log(boundGetAge()); // 42
const mary = { age: 21 };
const boundGetAgeMary = john.getAge.bind(mary);
console.log(boundGetAgeMary()); // 21
```
In the example above, when the `getAge` method is called without a calling object (as `unboundGetAge`), the value is `undefined` because the value of `this` within `getAge()` becomes the global object. `boundGetAge()` has its `this` bound to `john`, hence it is able to obtain the `age` of `john`.
We can even use `getAge` on another object which is not `john`! `boundGetAgeMary` returns the `age` of `mary`.
## Practice
Try [implementing your own `Function.prototype.bind()` method](/questions/javascript/function-bind) on Great Front End.
## References
- [Function.prototype.bind() - JavaScript | MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind)
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "explain-function-prototype-bind",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "high",
"difficulty": "medium"
}

View File

@ -0,0 +1,47 @@
---
title: Explain "hoisting"
---
Hoisting is a term used to explain the behavior of variable declarations 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.
```js
console.log(foo); // undefined
var foo = 1;
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.
```js
// Function Declaration
console.log(foo); // [Function: foo]
foo(); // 'FOOOOO'
function foo() {
console.log('FOOOOO');
}
console.log(foo); // [Function: foo]
// Function Expression
console.log(bar); // undefined
bar(); // Uncaught TypeError: bar is not a function
var bar = function () {
console.log('BARRRR');
};
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.
```js
x; // undefined
y; // Reference error: y is not defined
var x = 'local';
let y = 'local';
```
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "explain-hoisting",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "high",
"difficulty": "medium"
}

View File

@ -0,0 +1,11 @@
---
title: Explain how a browser determines what elements match a CSS selector.
---
This question is related to the question about [writing efficient CSS](/questions/quiz/what-are-some-of-the-gotchas-for-writing-efficient-css). Browsers match selectors from rightmost (key selector) to the 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 a 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 the selector, and can stop traversing its parents.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "explain-how-a-browser-determines-what-elements-match-a-css-selector",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "high",
"difficulty": "medium"
}

View File

@ -0,0 +1,33 @@
---
title: 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 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 example: `https://example.com?callback=printData`. The server will then wrap the data within a function called `printData` and return it to the client.
```html
<!-- https://mydomain.com -->
<script>
function printData(data) {
console.log(`My name is ${data.name}!`);
}
</script>
<script src="https://example.com?callback=printData"></script>
```
```js
// File loaded from https://example.com?callback=printData
printData({ name: 'John Doe' });
```
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](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) is the recommended approach and JSONP is seen as a hack.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,15 @@
{
"slug": "explain-how-jsonp-works-and-how-its-not-really-ajax",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript",
"network",
"security"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,81 @@
---
title: Explain how prototypal inheritance works
---
This is an extremely common JavaScript interview question. All JavaScript objects have a `__proto__` property with the exception of objects created with `Object.create(null)`, 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](https://davidwalsh.name/javascript-objects).
## Example of Prototypal Inheritance
```js
function Parent() {
this.name = 'Parent';
}
Parent.prototype.greet = function () {
console.log('Hello from ' + this.name);
};
const child = Object.create(Parent.prototype);
// Call parent constructor with child
Parent.call(child);
child.cry = function () {
console.log('waaaaaahhhh!');
};
child.cry();
// waaaaaahhhh!
child.greet();
// hello from Parent
child.constructor;
// ƒ Parent() {
// this.name = 'Parent';
// }
child.constructor.name;
// '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:
- Object.create(Parent.prototype);
- Object.create(new Parent(null));
- Object.create(objLiteral);
- Currently, `child.constructor` is pointing to the `Parent`:
If we'd like to correct this, one option would be to do:
```js
function Parent() {
this.name = 'Parent';
}
Parent.prototype.greet = function () {
console.log('Hello from ' + this.name);
};
function Child() {
Parent.call(this);
this.name = 'Child';
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
const child = new Child();
child.greet();
// hello from Child
child.constructor.name;
// 'Child'
```
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,14 @@
{
"slug": "explain-how-prototypal-inheritance-works",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "high",
"difficulty": "medium",
"ranking": 1
}

View File

@ -0,0 +1,22 @@
---
title: 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 the value of `this` depends on how the function is called. Having read many explanations on `this` online, [Arnav Aggrawal](https://medium.com/@arnav_aggarwal)'s explanation was 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.
1. 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.
1. If a function is called as a method, such as `obj.method()` — `this` is the object that the function is a property of.
1. 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.
1. If multiple of the above rules apply, the rule that is higher wins and will set the `this` value.
1. 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](https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3).
#### Can you give an example of one of the ways that working with this has changed in ES2015?
ES2015 allows you to use [arrow functions](http://2ality.com/2017/12/alternate-this.html#arrow-functions) which uses the [enclosing lexical scope](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this). This is usually convenient, but does prevent the caller from controlling context via `.call` or `.apply`—the consequences 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
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,15 @@
{
"slug": "explain-how-this-works-in-javascript",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "high",
"difficulty": "medium",
"featured": true,
"ranking": 1
}

View File

@ -0,0 +1,85 @@
---
title: 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:
```js
let myObject = {};
Object.defineProperty(myObject, 'number', {
value: 42,
writable: false,
configurable: false,
});
console.log(myObject.number); // 42
myObject.number = 43;
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(...)`:
```js
let myObject = {
a: 2,
};
Object.preventExtensions(myObject);
myObject.b = 3;
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).
### 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).
```js
let immutableObject = Object.freeze({});
```
Freezing an object does not allow new properties to be added to an object and prevents users from removing or altering the existing properties. `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.
- Less complicated: 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.
- 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.
- Less memory needed: Using libraries like [Immer](https://immerjs.github.io/immer/) and [Immutable.js](https://immutable-js.com/), objects are modified using structural sharing and less memory is needed for having multiple objects with similar structures.
- No need for defensive copying: 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.
### Cons
- Complex to create yourself: 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 operations that leverage on structural sharing.
- Potential negative performance: Allocation (and deallocation) of many small objects rather than modifying existing ones can cause a performance impact. The complexity of either the allocator or the garbage collector usually depends on the number of objects on the heap.
- Complexity for cyclic data structures: Cyclic data structures such as graphs are difficult to build. If you have two objects which can't be modified after initialization, how can you get them to point to each other?
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "explain-the-difference-between-mutable-and-immutable-objects",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,11 @@
---
title: 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).
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "explain-the-difference-between-synchronous-and-asynchronous-functions",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "high",
"difficulty": "medium"
}

View File

@ -0,0 +1,27 @@
---
title: 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 on [hoisting](/questions/quiz/explain-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
```js
foo(); // 'FOOOOO'
function foo() {
console.log('FOOOOO');
}
```
## Function Expression
```js
foo(); // Uncaught TypeError: foo is not a function
var foo = function () {
console.log('FOOOOO');
};
```
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,9 @@
---
title: 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.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,14 @@
{
"slug": "explain-the-same-origin-policy-with-regards-to-javascript",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript",
"network"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,23 @@
---
title: Explain what a single page app is and how to make one SEO-friendly
---
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](https://developer.mozilla.org/en-US/docs/Web/API/History_API). New data required for the new page, usually in JSON format, is retrieved by the browser via [AJAX](https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started) 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.
## Pros
- 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.
## Cons
- 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 [Prerender](https://prerender.io/) to "render your javascript in a browser, save the static HTML, and return that to the crawlers".
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,21 @@
---
title: "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 parentheses: `(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 subsequent `()`. 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(){ }();`. Unfortunately, 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:
```js
const foo = void (function bar() {
return 'foo';
})();
console.log(foo); // undefined
```
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "explain-why-the-following-doesnt-work-as-an-iife-function-foo--what-needs-to-be-changed-to-properly-make-it-an-iife",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,36 @@
---
title: 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 generated 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.
## Box Model Rules
- The dimensions of a block element are calculated by `width`, `height`, `padding`, `border`s.
- 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 [describe floats and how they work](/questions/quiz/describe-floats-and-how-they-work)).
- If no `width` is specified, a non-`float`-ed block element will expand to fit the width of its parent minus the `padding`, unless it has a `max-width` property set, in which case it will be no wider than the specified maximum width.
- Some block-level elements (e.g. `table`, `figure`, and `input`) have inherent or default width values, and may not expand to fill the full width of their parent container.
- Note: `span` is an inline-level element and does not have a default width, so it will not expand to fit.
- 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 (`box-sizing: content-box`), `padding`s and `border`s are not part of the `width` and `height` of an element.
Note that `margin`s are not counted towards the actual size of the box. It affects the total space that the box will take up on the page, but only the space outside the box. The box's area stops at the `border` — it does not extend into the `margin`.
## Extra
Look up the `box-sizing` property, which affects how the total heights and widths of elements are calculated.
- `box-sizing: content-box`: This is the default value of `box-sizing` and adheres to the rules above.
- `box-sizing: border-box`: The `width` and `height` will include the content, padding and border, but not including the margin. This is a much more intuitive way to think about boxes and hence many CSS frameworks set `* { box-sizing: border-box; }` globally, so that all elements use such a box model by default. See the [question on `box-sizing: border-box`](/questions/css/what-does-box-sizing-border-box-do-what-are-its-advantages) for more information.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)
- [The box model | MDN](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model#the_standard_css_box_model)

View File

@ -0,0 +1,19 @@
{
"slug": "explain-your-understanding-of-the-box-model-and-how-you-would-tell-the-browser-in-css-to-render-your-layout-in-different-box-models",
"languages": [],
"companies": [
"amazon",
"google",
"linkedin"
],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "high",
"difficulty": "medium",
"featured": true,
"ranking": 1
}

View File

@ -0,0 +1,13 @@
---
title: 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). Bootstrap was using the `float` approach until Bootstrap 4 which switched to the `flex`-based approach.
Today, `flex` is the recommended approach for building grid systems and has [decent browser support (99.64%)](https://caniuse.com/#search=flex).
For the adventurous, they can look into [CSS Grid Layout](https://css-tricks.com/snippets/css/complete-guide-grid/), which uses the shiny new `grid` property. Grid is a two-dimensional grid-based layout system as compared to Flexbox, which is one-dimensional.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "have-you-ever-used-a-grid-system-and-if-so-what-do-you-prefer",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,36 @@
---
title: Have you ever worked with retina graphics?
subtitle: 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 specified 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:
```html
<div responsive-background-image>
<img
src="/images/test-1600.jpg"
sizes="
(min-width: 768px) 50vw,
(min-width: 1024px) 66vw,
100vw"
srcset="
/images/test-400.jpg 400w,
/images/test-800.jpg 800w,
/images/test-1200.jpg 1200w
" />
</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, to use SVGs where possible, as they render very crisply regardless of resolution.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "have-you-ever-worked-with-retina-graphics-if-so-when-and-what-techniques-did-you-use",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,13 @@
---
title: Have you played around with the new CSS Flexbox or Grid specs?
---
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. famous CSS frameworks like Bootstrap and Bulma are based on Flexbox, and Flexbox is still the tested and proven way to create layouts.
Grid is by far the most intuitive approach for creating grid-based layouts but browser support is not that wide at the moment. Many layout problems can already be solved with Flexbox, so there's not a huge need for Grid.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "have-you-played-around-with-the-new-css-flexbox-or-grid-specs",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "high",
"difficulty": "medium"
}

View File

@ -0,0 +1,9 @@
---
title: Have you used or implemented media queries or mobile-specific layouts/CSS?
---
An example would be transforming a stacked pill navigation into a fixed-bottom tab navigation beyond a certain breakpoint.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "have-you-used-or-implemented-media-queries-or-mobile-specific-layouts-css",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,15 @@
---
title: How can you share code between files?
---
This depends on the JavaScript environment.
On the client (browser environment), as long as the variables/functions 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 CommonJS. 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
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "how-can-you-share-code-between-files",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,14 @@
---
title: How do you organize your code?
subtitle: Do you use module pattern, classical inheritance, something else?
---
In the past, developers 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, developers prefer using React/Redux which utilize a single-directional data flow based on Flux architecture. It is common now to represent an app's data model 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.
Avoid using classical inheritance where possible. When and if you do, stick to [these rules](https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-9af8de78ccb4).
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "how-do-you-organize-your-code-module-pattern-classical-inheritance",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,20 @@
---
title: How do you serve a page with content in multiple languages?
---
> Assumption: The question is about how to serve a page with content available in multiple languages and the content within the page should be displayed only in one consistent language.
Serving a page in different languages is one of the aspects of internationalization (i18n).
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>`.
To let a search engine know that the same content is available in different languages, `<link>` tags with the `rel="alternate"` and `hreflang="..."` attributes should be used. E.g. `<link rel="alternate" hreflang="de" href="http://de.example.com/page.html" />`.
## Rendering
- **Server-side rendering:** The HTML markup will contain string placeholders and content for the specific language will be fetched from configuration in code or a translation service. The server then dynamically generates the HTML page with content in that particular language.
- **Client-side rendering:** The appropriate locale strings will be fetched and combined with the JavaScript-based views.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/html-questions)

View File

@ -0,0 +1,14 @@
{
"slug": "how-do-you-serve-a-page-with-content-in-multiple-languages",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"html",
"i18n"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,17 @@
---
title: How do you serve your pages for feature-constrained browsers?
subtitle: What techniques/processes do you use?
---
## Techniques
- 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 application for a base level of user experience, but adding functional enhancements when a browser supports it.
- Use [caniuse.com](https://caniuse.com/) to check for feature support.
- Autoprefixer for automatic vendor prefix insertion.
- Feature detection using [Modernizr](https://modernizr.com/).
- Use CSS Feature queries via [`@support``](https://developer.mozilla.org/en-US/docs/Web/CSS/@supports)
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "how-do-you-serve-your-pages-for-feature-constrained-browsers-what-techniques-processes-do-you-use",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,18 @@
---
title: 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.
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 detects the device and other features and then provides the appropriate 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 essentially 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
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "how-is-responsive-design-different-from-adaptive-design",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,13 @@
---
title: 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 CSS transpilation library), there may be plugins which allow you to opt in to using modern CSS syntax (and even W3C proposals) that will transform those sections of your code into equivalent backward-compatible code that will work in the targets you've used.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "how-would-you-approach-fixing-browser-specific-styling-issues",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css"
],
"importance": "mid",
"difficulty": "medium"
}

View File

@ -0,0 +1,16 @@
---
title: Consider HTML5 as an open web platform. What are the building blocks of HTML5?
---
- **Semantics**: HTML tags describe the content.
- **Styling**: Customizing appearance of HTML tags
- **Connectivity**: Communicate with the server in new and innovative ways.
- **Offline and storage**: Allows webpages to store data on the client-side locally and operate offline more efficiently.
- **Multimedia**: Makes video and audio first-class citizens in the Open Web.
- **2D/3D graphics and effects**: Allows a much more diverse range of presentation options.
- **Performance** and integration: Provides greater speed optimization and better usage of computer hardware.
- **Device access**: Allows for the usage of various input and output devices.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/html-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "html5-as-an-open-web-platform-building-blocks",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"html"
],
"importance": "low",
"difficulty": "medium"
}

View File

@ -0,0 +1,11 @@
---
title: Is there any reason you'd want to use `translate()` instead of `absolute` positioning, or vice-versa? And why?
---
`translate()` is a possible value of the CSS `transform` property. When using `translate()`, the element still occupies its original space (sort of like `position: relative`). But when changing the absolute positioning of elements, the elements are removed from the flow of the page and the positioning of the surrounding elements will be affected. Hence the page layout will have to be recalculated.
Changing `transform` or `opacity` does not trigger browser reflows or repaints but does trigger compositions; On the other hand, 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. Hence `translate()` is more efficient and will result in shorter paint times for smoother animations.
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/css-questions)

View File

@ -0,0 +1,14 @@
{
"slug": "is-there-any-reason-youd-want-to-use-translate-instead-of-absolute-positioning-or-vice-versa-and-why",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"css",
"performance"
],
"importance": "high",
"difficulty": "medium"
}

View File

@ -0,0 +1,47 @@
---
title: 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:
```js
const Person = function (firstName) {
this.firstName = firstName;
this.sayName1 = function () {
console.log(this.firstName);
};
this.sayName2 = () => {
console.log(this.firstName);
};
};
const john = new Person('John');
const dave = new Person('Dave');
john.sayName1(); // John
john.sayName2(); // John
// The regular function can have its 'this' value changed, but the arrow function cannot
john.sayName1.call(dave); // Dave (because "this" is now the dave object)
john.sayName2.call(dave); // John
john.sayName1.apply(dave); // Dave (because 'this' is now the dave object)
john.sayName2.apply(dave); // John
john.sayName1.bind(dave)(); // Dave (because 'this' is now the dave object)
john.sayName2.bind(dave)(); // John
var sayNameFromWindow1 = john.sayName1;
sayNameFromWindow1(); // undefined (because 'this' is now the window object)
var sayNameFromWindow2 = john.sayName2;
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: https://medium.com/@machnicki/handle-events-in-react-with-arrow-functions-ede88184bbb)
## References
- [Front End Interview Handbook](https://www.frontendinterviewhandbook.com/javascript-questions)

View File

@ -0,0 +1,13 @@
{
"slug": "what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": [
"javascript"
],
"importance": "mid",
"difficulty": "medium"
}

Some files were not shown because too many files have changed in this diff Show More