Intermediate Interview Questions Flashcards

1
Q

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

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
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.
 - Event listeners are asynchronous callbacks that are only executed when a specific event occurs: 
document.addEventListener("click", onClick)
-Callbacks can also be synchronous:
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]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
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"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you clone an object in JavaScript?

A
1. Using the object spread operator ... 
const obj = { a: 1, b: 2 }
const shallowClone = { ...obj }
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.
2.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).
3.Object.assign({}, obj) is another alternative.
4.Object.keys(obj).reduce((acc, key) => (acc[key] = obj[key], acc), {}) is another more verbose alternative that shows the concept in greater depth.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you compare two objects in JavaScript?

A

Objects are being compared by their reference (location in memory), unlike primitive values which are compared by value. I
In order to test if two objects are equal in structure, a helper function is required. It will iterate through the own properties of each object to test if they have the same values, including nested objects.

function isDeepEqual(obj1, obj2, testPrototypes = false) {
  if (obj1 === obj2) {
    return true
  }

if (typeof obj1 === “function” && typeof obj2 === “function”) {
return obj1.toString() === obj2.toString()
}

if (obj1 instanceof Date && obj2 instanceof Date) {
return obj1.getTime() === obj2.getTime()
}

if (
Object.prototype.toString.call(obj1) !==
Object.prototype.toString.call(obj2) ||
typeof obj1 !== “object”
) {
return false
}

  const prototypesAreEqual = testPrototypes
    ? isDeepEqual(
        Object.getPrototypeOf(obj1),
        Object.getPrototypeOf(obj2),
        true
      )
    : true
  const obj1Props = Object.getOwnPropertyNames(obj1)
  const obj2Props = Object.getOwnPropertyNames(obj2)

return (
obj1Props.length === obj2Props.length &&
prototypesAreEqual &&
obj1Props.every(prop => isDeepEqual(obj1[prop], obj2[prop]))
)
}

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

What is CORS?

A

Cross-Origin Resource Sharing is a mechanism that uses additional HTTP headers to grant a browser permission to access resources from a server at an origin different from the website origin.
An example of a cross-origin request is a web application served from http://mydomain.com that uses AJAX to make a request for http://yourdomain.com.

  • CORS behavior is not an error,  it’s a security mechanism to protect users.
  • CORS is designed to prevent a malicious website that a user may unintentionally visit from making a request to a legitimate website to read their personal data or perform actions against their will.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Describe the layout of the CSS Box Model and briefly describe each component.

A

Content: The inner-most part of the box filled with content, such as text, an image, or video player. It has the dimensions: content-box width and content-box height.

Padding: The transparent area surrounding the content. It has dimensions: padding-box width and padding-box height.

Border: The area surrounding the padding (if any) and content. It has dimensions: border-box width and border-box height.

Margin: The transparent outer-most layer that surrounds the border. It separates the element from other elements in the DOM. It has dimensions: margin-box width and margin-box height.

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

What is the DOM?

A
The DOM (Document Object Model) is a cross-platform API that treats HTML and XML documents as a tree structure consisting of nodes. These nodes (such as elements and text nodes) are objects that can be programmatically manipulated and any visible changes made to them are reflected live in the document. In a browser, this API is available to JavaScript where DOM nodes can be manipulated to change their styles, contents, placement in the document, or interacted with through event listeners.
-The DOM is constructed progressively in the browser as a page loads, which is why scripts are often placed at the bottom of a page, in the  with a defer attribute, or inside a DOMContentLoaded event listener. Scripts that manipulate DOM nodes should be run after the DOM has been constructed to avoid errors.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the difference between em and rem units?

A

Both em and rem units are based on the font-size CSS property. The only difference is where they inherit their values from.
- em units inherit their value from the font-size of the parent element
- rem units inherit their value from the font-size of the root element (html)
In most browsers, the font-size of the root element is set to 16px by default.

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

What is event delegation and why is it useful?

A

Event delegation is a technique of delegating events to a single common ancestor. Due to event bubbling, events “bubble” up the DOM tree by executing any handlers progressively on each ancestor element up to the root that may be listening to it.
DOM events provide useful information about the element that initiated the event via Event.target. This allows the parent element to handle behavior as though the target element was listening to the event, rather than all children of the parent or the parent itself.
Instead of:

document.querySelectorAll(“button”).forEach(button => {
button.addEventListener(“click”, handleButtonClick)
})
Event delegation involves using a condition to ensure the child target matches our desired element:

document.addEventListener("click", e => {
  if (e.target.closest("button")) {
    handleButtonClick()
  }
})
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the difference between an expression and a statement in JavaScript?

A

There are two main syntactic categories in JavaScript: expressions and statements. A third one is both together, referred to as an expression statement. They are roughly summarized as:
-Expression: produces a value
-Statement: performs an action
-Expression statement: produces a value and performs an action
// If you can print it or assign it to a variable, it’s an expression. If you can’t, it’s a statement. //

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

What are truthy and falsy values in JavaScript?

A
There are 6 falsy values in JavaScript. They are:
 - false
 - undefined
 - null
 - "" (empty string)
 - NaN
 - 0 (both +0 and -0)
Every other value is considered truthy.
A value's truthiness can be examined by passing it into the Boolean function or using !!
Boolean("")    // false
Boolean([ ])    // true
!!""    // false
!![ ]    // true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does 0.1 + 0.2 === 0.3 evaluate to?

A

0.1 + 0.2 // 0.30000000000000004
It evaluates to false because JavaScript uses the IEEE 754 standard for Math and it makes use of 64-bit floating numbers. This causes precision errors when doing decimal calculations, in short, due to computers working in Base 2 while decimal is Base 10.
A solution to this problem would be to use a function that determines if two numbers are approximately equal by defining an error margin (epsilon) value that the difference between two values should be less than.

const approxEqual = (n1, n2, epsilon = 0.0001) => Math.abs(n1 - n2) < epsilon
approxEqual(0.1 + 0.2, 0.3) // true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the difference between the array methods map() and forEach()?

A

Both methods iterate through the elements of an array. map() maps each element to a new element by invoking the callback function on each element and returning a new array. On the other hand, forEach() invokes the callback function for each element but does not return a new array.

Use forEach() if you need to iterate over an array and cause mutations to the elements without needing to return values to generate a new array.

map() is the right choice to keep data immutable where each value of the original array is mapped to a new array.

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

How does hoisting work in JavaScript?

A

Hoisting is a JavaScript mechanism where variable and function declarations are put into memory during the compile phase. This means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.

However, the value is not hoisted with the declaration.
The following snippet:

console.log(hoist);
var hoist = "value";

is equivalent to:

var hoist;
console.log(hoist);
hoist = “value”;

Hoisting also allows you to invoke a function declaration before it appears to be declared in a program.

myFunction() // No error; logs "hello"
function myFunction() {
  console.log("hello")
}
But be wary of function expressions that are assigned to a variable:
myFunction() // Error: `myFunction` is not a function
var myFunction = function() {
  console.log("hello")
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is hoisting in JavaScript?

A

Hoisting is JavaScript’s default behavior of moving declarations to the top;
Functions declarations are hoisted before variable declarations;

17
Q
What will the console log in this example?
var foo = 1
var foobar = function() {
  console.log(foo)
  var foo = 2
}
foobar()
A

undefined
why? it is equivalent to:

var foolbar = function() {
var foo;
console.log(foo);
foo = 2;
}