30 Seconds of Interviews Flashcards

1
Q

What is the purpose of the alt attribute on images?

A

The alt attribute provides alternative information for an image if a user cannot view it. The alt attribute should be used to describe any images except those which only serve a decorative purpose, in which case it should be left empty.

Good to hear

  • Decorative images should have an empty alt attribute.
  • Web crawlers use alt tags to understand image content, so they are considered important for Search Engine Optimization (SEO).
  • Put the . at the end of alt tag to improve accessibility.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is CSS BEM?

A

The BEM methodology is a naming convention for CSS classes in order to keep CSS more maintainable by defining namespaces to solve scoping issues. BEM stands for Block Element Modifier which is an explanation for its structure. A Block is a standalone component that is reusable across projects and acts as a “namespace” for sub-components (Elements). Modifiers are used as flags when a Block or Element is in a certain state or is different in structure or style.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the purpose of cache-busting and how can you achieve it?

A

Browsers have a cache to temporarily store files on websites so they don’t need to be re-downloaded again when switching between pages or reloading the same page. The server is set up to send headers that tell the browser to store the file for a given amount of time. This greatly increases website speed and preserves bandwidth.

However, it can cause problems when the website has been changed by developers because the user’s cache still references old files. This can either leave them with old functionality or break a website if the cached CSS and JavaScript files are referencing elements that no longer exist, have moved or have been renamed.

Cache busting is the process of forcing the browser to download the new files. This is done by naming the file something different to the old file.

A common technique to force the browser to re-download the file is to append a query string to the end of the file.

  • src=”js/script.js” => src=”js/script.js?v=2”

The browser considers it a different file but prevents the need to change the file name.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the advantages of using CSS preprocessors?

A

CSS preprocessors add useful functionality that native CSS does not have, and generally make CSS neater and more maintainable by enabling DRY (Don’t Repeat Yourself) principles. Their terse syntax for nested selectors cuts down on repeated code. They provide variables for consistent theming (however, CSS variables have largely replaced this functionality) and additional tools like color functions (lighten, darken, transparentize, etc), mixins, and loops that make CSS more like a real programming language and gives the developer more power to generate complex CSS.

Good to hear

  • They allow us to write more maintainable and scalable CSS
  • Some disadvantages of using CSS preprocessors (setup, re-compilation time can be slow etc.)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the difference between the equality operators == and ===?

A

Triple equals (===) checks for strict equality, which means both the type and value must be the same. Double equals (==) on the other hand first performs type coercion so that both operands are of the same type and then applies strict comparison.

Good to hear

  • Whenever possible, use triple equals to test equality because loose equality == can have unintuitive results.
  • Type coercion means the values are converted into the same type.
  • Mention of falsy values and their comparison.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the difference between an element and a component in React?

A

An element is a plain JavaScript object that represents a DOM node or component. Elements are pure and never mutated, and are cheap to create.

A component is a function or class. Components can have state and take props as input and return an element tree as output (although they can represent generic containers or wrappers and don’t necessarily have to emit DOM). Components can initiate side effects in lifecycle methods (e.g. AJAX requests, DOM mutations, interfacing with 3rd party libraries) and may be expensive to create.

```const Component = () => “Hello”

const componentElement =

const domNodeElement =

```

Good to hear

  • Elements are immutable, plain objects that describe the DOM nodes or components you want to render.
  • Components can be either classes or functions, that take props as an input and return an element tree as the output.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Using flexbox, create a 3-column layout where each column takes up a col-{n} / 12 ratio of the container.

A

Set the .row parent to display: flex; and use the flex shorthand property to give the column classes a flex-grow value that corresponds to its ratio value.

```.row { display: flex; }

.col-2 { flex: 2; }

.col-7 { flex: 7; }

.col-3 { flex: 3; }```

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Can a web page contain multiple elements? What about elements?

A

Yes to both. The W3 documents state that the tags represent the header() and footer() areas of their nearest ancestor “section”. So not only can the page contain a header and a footer, but so can every and element.

Good to hear

  • W3 recommends having as many as you want, but only 1 of each for each “section” of your page, i.e. body, section etc.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Briefly describe the correct usage of the following HTML5 semantic elements: , ,,

A
  • is used to contain introductory and navigational information about a section of the page. This can include the section heading, the author’s name, time and date of publication, table of contents, or other navigational information.
  • is meant to house a self-contained composition that can logically be independently recreated outside of the page without losing its meaning. Individual blog posts or news stories are good examples.
  • is a flexible container for holding content that shares a common informational theme or purpose.
  • is used to hold information that should appear at the end of a section of content and contain additional information about the section. Author’s name, copyright information, and related links are typical examples of such content.

Good to hear

  • Other semantic elements are and
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What does lifting state up in React mean?

A

When several components need to share the same data, then it is recommended to lift the shared state up to their closest common ancestor. For example, if two child components share the same data, it is recommended to move the shared state to parent instead of maintaining the local state in both child components.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Can you name the four types of @media properties?

A
  • all, which applies to all media type devices
  • print, which only applies to printers
  • screen, which only applies to screens (desktops, tablets, mobile etc.)
  • speech, which only applies to screenreaders
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the difference between the postfix i++ and prefix ++i increment operators?

A

Both increment the variable value by 1. The difference is what they evaluate to.

The postfix increment operator evaluates to the value before it was incremented.

let i = 0

i++ // 0

// i === 1

The prefix increment operator evaluates to the value after it was incremented.

let i = 0

++i // 1

// i === 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

In which states can a Promise be?

A

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected: meaning that the operation failed.

A pending promise can either be fulfilled with a value, or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise’s then method are called.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you write comments inside a JSX tree in React?

A

Comments must be wrapped inside curly braces {} and use the /* */ syntax.

const tree = (

{/* Comment */}

Text

)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is a stateful component in React?

A

A stateful component is a component whose behavior depends on its state. This means that two separate instances of the component if given the same props will not necessarily render the same output, unlike pure function components.

// Stateful class component class App extends Component { constructor(props) { super(props) this.state = { count: 0 } } render() { // … } } // Stateful function component function App() { const [count, setCount] = useState(0) return // … }

Good to hear

  • Stateful components have internal state that they depend on.
  • Stateful components are class components or function components that use stateful Hooks.
  • Stateful components have their state initialized in the constructor or with useState().
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are defer and async attributes on a tag?

A

If neither attribute is present, the script is downloaded and executed synchronously, and will halt parsing of the document until it has finished executing (default behavior). Scripts are downloaded and executed in the order they are encountered.

The defer attribute downloads the script while the document is still parsing but waits until the document has finished parsing before executing it, equivalent to executing inside a DOMContentLoaded event listener. defer scripts will execute in order.

The async attribute downloads the script during parsing the document but will pause the parser to execute the script before it has fully finished parsing. async scripts will not necessarily execute in order.

Note: both attributes must only be used if the script has a src attribute (i.e. not an inline script).

Good to hear

  • Placing a defer script in the allows the browser to download the script while the page is still parsing, and is therefore a better option than placing the script before the end of the body.
  • If the scripts rely on each other, use defer.
  • If the script is independent, use async.
  • Use defer if the DOM must be ready and the contents are not placed within a DOMContentLoaded listener.
17
Q

Create a function batches that returns the maximum number of whole batches that can be cooked from a recipe.

/** It accepts two objects as arguments: the first object is the recipe for the food, while the second object is the available ingredients. Each ingredient’s value is a number representing how many units there are.

batches(recipe, available) */ //

0 batches can be made batches( { milk: 100, butter: 50, flour: 5 }, { milk: 132, butter: 48, flour: 51 } )

batches( { milk: 100, flour: 4, sugar: 10, butter: 5 }, { milk: 1288, flour: 9, sugar: 95 } ) // 1 batch can be made

batches( { milk: 100, butter: 50, cheese: 10 }, { milk: 198, butter: 52, cheese: 10 } ) // 2 batches can be made

batches( { milk: 2, sugar: 40, butter: 20 }, { milk: 5, sugar: 120, butter: 500 }

A

We must have all ingredients of the recipe available, and in quantities that are more than or equal to the number of units required. If just one of the ingredients is not available or lower than needed, we cannot make a single batch.

Use Object.keys() to return the ingredients of the recipe as an array, then use Array.prototype.map() to map each ingredient to the ratio of available units to the amount required by the recipe. If one of the ingredients required by the recipe is not available at all, the ratio will evaluate to NaN, so the logical OR operator can be used to fallback to 0 in this case.

Use the spread … operator to feed the array of all the ingredient ratios into Math.min() to determine the lowest ratio. Passing this entire result into Math.floor() rounds down to return the maximum number of whole batches.

const batches = (recipe, available) =>

Math.floor(

Math.min(…Object.keys(recipe).map(k => available[k] / recipe[k] || 0)

)

18
Q

Create a standalone function bind that is functionally equivalent to the method Function.prototype.bind.

function example() {

console.log(this)

}

const boundExample = bind(example, { a: true })

boundExample.call({ b: true }) // logs { a: true }

A

Return a function that accepts an arbitrary number of arguments by gathering them with the rest … operator. From that function, return the result of calling the fn with Function.prototype.apply to apply the context and the array of arguments to the function.

const bind = (fn, context) => (…args) => fn.apply(context, args)

19
Q

What is the purpose of callback function as an argument of setState?

A

The callback function is invoked when setState has finished and the component gets rendered. Since setState is asynchronous, the callback function is used for any post action.

setState({ name: “sudheer” }, () => {

console.log(“The name has updated and component re-rendered”)

})

Good to hear

  • The callback function is invoked after setState finishes and is used for any post action.
  • It is recommended to use lifecycle method rather this callback function.
20
Q

What is a callback? Can you show an example using one?

A

Callbacks are functions passed as an argument to another function to be executed once an event has occurred or a certain task is complete, often used in asynchronous code. Callback functions are invoked later by a piece of code but can be declared on initialization without being invoked.

As an example, event listeners are asynchronous callbacks that are only executed when a specific event occurs.

function onClick() {

console.log(“The user clicked on the page.”)

}

document.addEventListener(“click”, onClick)

However, callbacks can also be synchronous. The following map function takes a callback function that is invoked synchronously for each iteration of the loop (array element).

const map = (arr, callback) => {

const result = []

for (let i = 0; i < arr.length; i++) {

result.push(callback(arr[i], i))

}

return result

} map([1, 2, 3, 4, 5], n => n * 2) // [2, 4, 6, 8, 10]

Good to hear

  • Functions are first-class objects in JavaScript
  • Callbacks vs Promises
21
Q

Why does React use className instead of class like in HTML?

A

React’s philosophy in the beginning was to align with the browser DOM API rather than HTML, since that more closely represents how elements are created. Setting a class on an element meant using the className API:

const element = document.createElement(“div”)

element.className = “hello”

Additionally, before ES5, reserved words could not be used in objects:

const element = {

attributes: {
class: “hello”

}

}

In IE8, this will throw an error.

In modern environments, destructuring will throw an error if trying to assign to a variable:

const { class } = this.props // Error

const { className } = this.props // All good

const { class: className } = this.props // All good, but cumbersome!

However, class can be used as a prop without problems, as seen in other libraries like Preact. React currently allows you to use class, but will throw a warning and convert it to className under the hood. There is currently an open thread (as of January 2019) discussing changing className to class to reduce confusion.

22
Q

How do you clone an object in JavaScript?

A

Using the object spread operator …, the object’s own enumerable properties can be copied into the new object. This creates a shallow clone of the object.

const obj = { a: 1, b: 2 }

const shallowClone = { …obj }

With this technique, prototypes are ignored. In addition, nested objects are not cloned, but rather their references get copied, so nested objects still refer to the same objects as the original. Deep-cloning is much more complex in order to effectively clone any type of object (Date, RegExp, Function, Set, etc) that may be nested within the object.

Other alternatives include:

  • JSON.parse(JSON.stringify(obj)) can be used to deep-clone a simple object, but it is CPU-intensive and only accepts valid JSON (therefore it strips functions and does not allow circular references).
  • Object.assign({}, obj) is another alternative.
  • Object.keys(obj).reduce((acc, key) => (acc[key] = obj[key], acc), {}) is another more verbose alternative that shows the concept in greater depth.

Good to hear

  • JavaScript passes objects by reference, meaning that nested objects get their references copied, instead of their values.
  • The same method can be used to merge two objects.
23
Q
A