Intermediate Interview Questions Flashcards
What is the purpose of callback function as an argument of setState?
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.
What is a callback? Can you show an example using one?
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]
Why does React use className instead of class like in HTML?
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 do you clone an object in JavaScript?
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 do you compare two objects in JavaScript?
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]))
)
}
What is CORS?
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.
Describe the layout of the CSS Box Model and briefly describe each component.
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.
What is the DOM?
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.
What is the difference between em and rem units?
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.
What is event delegation and why is it useful?
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() } })
What is the difference between an expression and a statement in JavaScript?
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. //
What are truthy and falsy values in JavaScript?
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
What does 0.1 + 0.2 === 0.3 evaluate to?
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
What is the difference between the array methods map() and forEach()?
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 does hoisting work in JavaScript?
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") }