Prescreen Interview Quiz Questions Flashcards

1
Q

Describe event bubbling

A

Event bubbling is a mechanism in the DOM where an event triggered on a child element propagates up through its ancestors. When an event is fired on an element, the event first runs the handlers on the element itself, then on its parent, and so on upwards through the DOM tree to the root.

This is useful for event delegation, as you can attach a single event listener to a parent element to catch events from all its descendants.

To stop event bubbling, you can use event.stopPropagation().

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

Explain Function.prototype.bind

A

The .bind method creates a new function that, when called, has its this keyword set to the provided value. The method also allows you to partially apply arguments to the function. Essentially, bind enables you to execute a function with a specific this context and with predefined initial arguments, if needed.

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.

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

What is the CSS display property and can you give a few examples of its use?

A

The display CSS property sets whether an element is treated as a block or inline box and can also control layout used for its children.

  • block: Element takes full width, new line before and after.
  • inline: No new line, takes necessary width.
  • inline-block: Like inline, but can set width/height.
  • flex: Enables flexbox layout for children.
  • grid: Enables grid-based layout.
  • none: Element not displayed.

Examples:
- display: block; for divs, headings.
- display: inline; for spans, links.
- display: flex; for creating flexible UI layouts.

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

Why is it generally a good idea to position CSS <link>s between <head></head> and JS <script>s just before </body>?

A

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.

  • CSS in <head>: Placing CSS links in the <head> ensures that styles are applied as soon as the HTML is loaded, improving the perceived performance and avoiding FOUC (Flash of Unstyled Content).
  • JS before </body>: JavaScript files are usually placed just before the closing </body> tag to prevent blocking the rendering of the page. JavaScript is blocking by nature; it stops HTML parsing until the script is downloaded and executed.
    • Non-blocking alternatives: Modern practices include using attributes like async and defer to load JavaScript files without blocking HTML parsing, which gives you more flexibility on script positioning.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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

A

The == operator performs loose equality comparison, meaning it converts the operands to the same type before making the comparison. The === operator performs strict equality comparison, meaning it does not convert the operands to the same type.

  • ==: 5 == “5” returns true
  • ===: 5 === “5” returns false

Use === for more predictable results and to avoid unintended type coercion.

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

Explain how a browser determines what elements match a CSS selector.

A

The browser uses a process known as the “Cascade” to determine which elements match a CSS selector. When a CSS rule is applied, the browser starts by parsing the selectors from right to left. It checks elements in the DOM against the far-right selector and moves through ancestors to see if they match the preceding selectors.

The matching process also takes into account the specificity of the selector. A more specific selector will override the styles of a less specific one.

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

What’s a typical use case for anonymous functions?

A
  1. Encapsulating code in IIFEs to prevent variable leakage to the global scope.
  2. Single-use callbacks, often making code more self-contained and readable.
  3. Arguments to functional programming methods like map, filter, or in libraries like Lodash.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the differences between variables created using let, var or const?

A

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

var allows variables to be hoisted, meaning they can be referenced in code before they are declared. let and const will not allow this, instead throwing an error.

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

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

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

What’s the difference between .call and .apply in JavaScript?

A

Both .call and .apply are methods to invoke functions and set the this context, but they differ in how they handle function arguments.

  • .call: Takes a list of arguments after the this argument -
    func.call(thisArg, arg1, arg2, ...);
  • .apply: Takes an array-like object for arguments after the this argument - func.apply(thisArg, [arg1, arg2, ...]);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What’s the difference between a relative, fixed, absolute and static-ally positioned element?

A

Each of these values for the position property in CSS controls how an element is positioned within its parent or within the viewport.

  • Static: Default positioning. The element flows into its natural position in the document layout - top, right, bottom, left properties have no effect.
  • Relative: Positioned relative to its normal position - top, right, bottom, left properties will move the element from its normal position.
  • Fixed: Positioned relative to the browser viewport - top, right, bottom, left properties will position the element in relation to the viewport.
  • Absolute: Positioned relative to the nearest positioned ancestor, if any; otherwise relative to the initial containing block (often the <html> element) - top, right, bottom, left properties will position the element in relation to its containing block.
  • Sticky: A mix of relative and fixed positioning. The element is treated as relative until it crosses a specified threshold, at which point it becomes fixed - top, right, bottom, left properties will position the element within its container until a certain scroll position is reached.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Is there any reason you’d want to use translate() instead of absolute positioning, or vice-versa? And why?

A

Using translate() and absolute positioning serve different purposes and have distinct performance implications.

  1. Layout Impact:
    • translate(): Element occupies its original space, like position: relative. Doesn’t affect surrounding elements.
    • absolute: Removes the element from the flow of the page, affecting positioning of surrounding elements.
  2. Performance:
    • translate(): More efficient, triggers only compositions and uses the GPU. Ideal for smoother, more efficient animations.
    • absolute: Triggers reflows and repaints, using the CPU. Can impact performance negatively.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Explain “hoisting”

A

Hoisting is a JavaScript behavior where variable and function declarations are moved, or “hoisted,” to the top of their containing scope during compilation. However, only the declarations are hoisted, not the initializations. With var, the variable is hoisted and initialized with undefined. With let and const, the variable is hoisted but remains uninitialized (in the “Temporal Dead Zone”). Function declarations are also hoisted, but function expressions are not.

For example, a variable declared with var is accessible before its declaration, but it will be undefined.

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

Describe the difference between a cookie, sessionStorage and localStorage.

A

All three are client-side storage technologies but differ in lifespan, capacity, and accessibility.

Cookie
- Lifespan: Can be set manually, otherwise session-based.
- Capacity: Up to 4KB.
- Accessibility: Both server and client-side. Sent with each HTTP request, affecting performance.
- Scope: Domain-specific.

sessionStorage
- Lifespan: Limited to a session (tab/window). Cleared when the session ends.
- Capacity: 5-10MB depending on the browser.
- Accessibility: Client-side only.
- Scope: Tab-specific.

localStorage
- Lifespan: Persistent, until explicitly deleted.
- Capacity: 5-10MB depending on the browser.
- Accessibility: Client-side only.
- Scope: Shared across all tabs/windows from the same domain.

Cookies are suitable for small bits of data and for server-client communication. sessionStorage and localStorage are useful for larger amounts of client-side-only data storage, with sessionStorage being ephemeral and localStorage being persistent.

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

Explain your understanding of the box model in CSS

A

The CSS box model describes the layout of each element on a web page. It consists of:

  1. Content: The box content, defined by width and height.
  2. Padding: Space between the content.
  3. Border: Goes around the padding and content.
  4. Margin: Space between the border and the outside edge of the element.

Different Box Models:

  • Content-Box: This is the default value of the box-sizing property. The width and height properties are applied only to the element’s content, not its padding or border - box-sizing: content-box;
  • Border-Box: The width and height properties include content, padding, and border, but not the margin - box-sizing: border-box;

You can globally set all elements to use the border-box model, via a CSS rule.

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

Explain how this works in JavaScript.

A

The overarching rule is that this is determined at the time a function is invoked by inspecting where it’s called, its call site. It follows these rules, in order of precedence:

  1. New Keyword: If the function is called with new, this inside the function will be a brand new object. Without it will refer to global object (see 4 below)
  2. Apply, Call, Bind: When using apply, call, or bind to call/create a function, this will be the object passed as an argument.
  3. Method Invocation: When a function is called as a method, i.e., obj.method(), this will be the object that owns the method.
  4. Free Function Invocation / Global: If none of the conditions above are met, this defaults to the global object. In a browser, it’s the window object; in strict mode ('use strict'), it’s undefined.
  5. Rule Precedence: If multiple rules apply, the one higher on this list takes precedence.
  6. Arrow Functions: ES2015 arrow functions ignore all these rules and take on the this value of their surrounding scope value of its surrounding scope at the time it’s created.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between <script>, <script async>, and <script defer>?

A

<script>: The browser will stop HTML parsing and execute the script immediately. If the script has an src attribute, the browser will also block rendering until the script is downloaded and executed.

<script async>: The script will be downloaded asynchronously and executed as soon as it is downloaded, without waiting for HTML parsing to complete. HTML parsing may be interrupted to execute the script. Useful for independent scripts such as analytics.

<script defer>: The script will be downloaded asynchronously but will be executed only after the HTML parsing is completed (before firing DOMContentLoaded). Useful for scripts that rely on the DOM structure.

Both async and defer attributes are effective only for external scripts - the attributes are ignored for scripts that have no src attribute.

<script>s with defer or async that contain document.write() will be ignored with a message like “A call to document.write() from an asynchronously-loaded external script was ignored”.

17
Q

Explain event delegation

A

Event delegation is a technique where you add an event listener to a parent element instead of individual child elements. When an event occurs on a descendant, it bubbles up and triggers the listener on the parent.

  • This approach reduces memory footprint by eliminating the need for multiple event handlers on each child element.
  • It also simplifies dynamic element manipulation, as you don’t have to attach or detach event handlers when elements are added or removed.
18
Q

What’s the difference between inline and inline-block?

A

Both inline and inline-block allow elements to sit next to each other horizontally, but they have distinct behaviors:

Inline
- Elements don’t start on a new line; they appear on the same line as the content before and after them.
- Width and height are ignored. Only line-height, vertical-align, and text-align affect the element.
- Only horizontal margins and padding apply. Vertical margins and padding will have no effect.

Inline-Block
- Similar to inline, elements sit next to each other. However, they behave like block elements within.
- Width and height can be set, and the element respects these dimensions.
- All margins and padding apply.

19
Q

What is the event loop?

What is the difference between call stack and task queue?

A

Event Loop:
The event loop is a single-threaded loop that continually checks the call stack and the task queue. It moves tasks from the task queue to the call stack for execution when the call stack is empty.

Call Stack vs Task Queue:
- Call Stack: Where function calls are put to be executed. It follows the Last-In, First-Out (LIFO) principle.
- Task Queue: Holds callback functions that are to be executed once the call stack is empty.

The event loop facilitates the asynchronous behavior in JavaScript by moving tasks from the task queue to the call stack when the call stack is empty.

Check out Philip Robert’s talk on the Event Loop

20
Q

What does * { box-sizing: border-box; } do in CSS?

A
  1. Behavior: Changes the box model for all elements so that width and height include padding and border, not just content.
  2. Default: Normally, elements use box-sizing: content-box, which does not include padding and border in size calculations.

Advantages:

  • Aligns with how designers typically think about element sizing.
  • Simplifies layout and grid calculations by taking padding and border into account.
21
Q

What’s the difference between a variable that is: null, undefined, or undeclared in JavaScript?

How would you go about checking for any of these states?

A
  • undefined: A variable that has been declared but has not been assigned a value.
  • null: Explicitly represents no value or no object. Needs to be assigned.
  • undeclared: A variable that has not been declared at all and does not exist in the code.

Examples:
- let x; // x is undefined
- let y = null; // y is null
- console.log(z); // ReferenceError: z is not defined (undeclared)

undefined and null are both falsy values but are not equal (undefined !== null).

To check for these states:
- For undefined: if (typeof variable === 'undefined')
- For null: if (variable === null)
- For undeclared: Wrap its usage in a try/catch block - or if (typeof someUndeclaredVariable === 'undefined')

22
Q

What are the pros and cons of using Promises instead of callbacks?

A

Both Promises and callbacks are techniques in JavaScript for handling asynchronous operations.

Pros:
1. Better readability and maintainability.
2. Simplified error handling through .catch().
3. Supports chaining for complex logic with .then().
4. Native methods for parallel execution (Promise.all(), Promise.race()).
5. Well-defined state management (pending, fulfilled, rejected).
6. Standardization - Promises are part of the spec

Cons:
1. Higher memory overhead.
2. Not cancelable by default.
3. Risk of uncaught errors if .catch() is omitted.
4. Can be overkill for very simple asynchronous tasks.

23
Q

Can you offer a use case for the new arrow => function syntax? How does this new syntax differ from other functions?

A

Arrow functions are often used for short, simple functions and when you want to maintain the lexical this value from the surrounding code. They are commonly used in array methods like .map(), .filter(), and .forEach().

Detailed differences
* Syntax: More concise, especially for single-parameter functions.
* this behavior: Arrow functions do not have their own this; they inherit it from the surrounding code.
* No arguments Object: Arrow functions do not have the arguments object, unlike regular functions.
* Cannot be used as Constructors: Arrow functions cannot be used with new.
* No prototype Property: Arrow functions do not have a prototype property.

24
Q

What language constructions do you use for iterating over object properties and array items?

A

Iterating Over Array Items:
1. for loop
2. forEach() method
3. for...of loop
4. map(), filter(), reduce() methods for functional approaches

Iterating Over Object Properties:
1. for...in loop
2. Object.keys(obj).forEach()
3. Object.entries(obj).forEach()
4. Object.getOwnPropertyNames()

Note: for...in will also enumerate through the prototype chain, so it’s often combined with hasOwnProperty() to filter out inherited properties.

25
Q

What is a closure, and how/why would you use one?

A

A closure is the combination of a function and the lexical environment within which that function was declared.

The word “lexical” refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Closures are functions that have access to the outer (enclosing) function’s variables—scope chain even after the outer function has returned.

Technically, when the outer function returns the inner function, relevant data from it’s variable environment is attached to the function reference via the hidden [[scope]] property.

Example use cases:
1. Data Privacy: Emulate private methods with closures in the module pattern.
2. Partial Applications or Currying: Create functions with pre-filled arguments.
3. Functional Logic: Use for memoization or “once” functions that run only a single time.

26
Q

Explain how prototypal inheritance works in JavaScript.

A

Prototypal inheritance in JavaScript is a mechanism by which objects inherit features from one another through their prototypes.

Every JavaScript object has a \_\_proto\_\_ property, except for those created with Object.create(null). This property points to the object’s prototype, which is a reference to another object.

When attempting to access a property or method that is not present on an object, JavaScript will traverse up the object’s prototype chain (via the \_\_proto\_\_) until it either finds the property/method or reaches the end of the chain.

To set up inheritance, you can establish an object’s prototype to another object using methods like Object.create() (preferred), Object.setPrototypeOf(), or by using the prototype property with constructor functions.

This behavior simulates classical inheritance, but is more akin to delegation.

// Example
function Animal(name) {
  this.name = name;
}
Animal.prototype.makeSound = function () {
  console.log('Sound');
};
function Dog(name) {
  Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.bark = function () {
  console.log('Woof!');
};
const myDog = new Dog('Fido');
myDog.makeSound(); // Looks up the prototype chain and finds makeSound
myDog.bark(); // Woof!
27
Q

What is CSS selector specificity and how does it work?

A

Specificity is the set of rules engines use in CSS to decide which selector is most specific when multiple rules could apply to an element.

  • The heirarchy is based on (from high to low):
    1. If it is an inline style
    2. IDs
    3. Classes, Pseudo-classes, Attributes
    4. Elements, Pseudo-elements
  • Specificity is usually calculated using a four-value specificity vector:
    [ inline style, ID, class, element].
  • A more specific selector will override the properties set by a less specific one.
  • The !important declaration overrides any other declarations but should be used sparingly.
  • In the case of equal Specificity, the last declared rule wins.
28
Q

Explain the difference between synchronous and asynchronous functions

A
  • Synchronous functions execute line by line, blocking the execution thread until the current operation is complete.
  • Asynchronous functions, allow tasks to be offloaded for non-blocking execution. They often make use of callbacks, promises, or async/await syntax to handle future results or errors. Asynchronous functions let other tasks run in the meantime, making them ideal for I/O-bound operations like file reading, API calls, or any tasks that would otherwise take a long time to complete.
29
Q
A