JS Flashcards

1
Q

What are polyfills?

A

Polyfills in JavaScript are pieces of code that provide modern functionality in older browsers or environments that do not natively support it. They act as “fillers” for missing features, enabling developers to use new JavaScript methods, APIs, or standards while maintaining compatibility with outdated browsers

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

How polyfills works?

A

Feature Detection: Polyfills first check if a feature is supported in the browser. If not, they provide a custom implementation using existing JavaScript capabilities.

Implementation: They can be written manually or included through libraries like core-js or services like Polyfill.io4.

Examples:

Adding Array.prototype.includes() for older browsers.

Providing fetch() support where it’s unavailable.

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

What is AbortController

A

AbortController is a JavaScript interface used to cancel asynchronous operations, such as fetch requests, before they complete. It provides a standardized way to manage cancellations, improving resource efficiency and user experience

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

What is Abort Signal

A

An AbortSignal is an object that communicates with asynchronous operations (like fetch requests) to allow them to be aborted (canceled) before completion.

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

Javascript is a single-threaded non-blocking asynchronous concurrent language. How do you understand that statement?

A

Single-threaded: JavaScript executes on a single thread, meaning it processes one task at a time. This is managed by the event loop.

Non-blocking: JavaScript uses asynchronous operations to avoid blocking the main thread. This allows other tasks to be processed while waiting for I/O operations to complete.

Asynchronous: JavaScript supports asynchronous programming, which enables tasks to be executed without blocking the main thread.

Concurrent: Although JavaScript is single-threaded, it achieves concurrency through asynchronous operations and the event loop, allowing multiple tasks to be processed in a seemingly concurrent manner.

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

What is EventLoop in JS?

A

The Event Loop in JavaScript is a mechanism that enables non-blocking I/O operations by managing asynchronous tasks. It consists of two main components: the call stack and the message queue (or task queue). The call stack executes synchronous code, while the message queue handles asynchronous tasks like setTimeout callbacks and promise resolutions. The Event Loop continuously checks the call stack; when it’s empty, it executes tasks from the message queue, ensuring efficient handling of asynchronous operations without blocking the main thread.

In more detail, tasks are categorized into macrotasks (e.g., setTimeout) and microtasks (e.g., promise callbacks), with microtasks prioritized over macrotasks. This allows for responsive and efficient execution of JavaScript code in both browsers and Node.js environments.

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

Why are namespaces important in JavaScript?

A

Namespaces help prevent naming conflicts, encapsulate code from other code, and avoid polluting the global scope with too many variables, which is especially important when building feature-rich applications or using third-party components

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

What happens when you declare the same variable multiple times in JavaScript without namespacing?

A

JavaScript allows redeclaration of variables using var without errors, with the latest value overwriting previous ones. For example: var x = 10; var x = 20; results in x being 20

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

What is the simplest way to create a namespace in JavaScript?

A

The simplest way is using an object literal:

const car = {
start: () => { console.log(‘start’) },
stop: () => { console.log(‘stop’) }
};

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

What is the Temporal Dead Zone?

A

The Temporal Dead Zone is the area of a block where a variable is inaccessible until the moment the computer completely initializes it with a value. It starts at the beginning of the block’s local scope and ends when the variable is fully initialized

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

Which variable declarations in JavaScript are affected by the Temporal Dead Zone?

A

Variables declared with let, const, and class are affected by the Temporal Dead Zone

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

What error is thrown when accessing a variable in its Temporal Dead Zone?

A

A ReferenceError is thrown when attempting to access a variable that is in its Temporal Dead Zone

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

How does the Temporal Dead Zone behavior differ between var and let/const variables?

A

var variables are hoisted and automatically initialized with undefined, so their TDZ ends immediately after hoisting. let and const variables are hoisted but remain uninitialized in the TDZ until their declaration is reached in the code execution

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

What happens in this code and why?
let a = f();
const b = 2;
function f() { return b; }

A

This code throws a ReferenceError. When f() is called, it tries to access b which is still in the TDZ because its declaration hasn’t been reached yet

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

What happens in this code and why?
let x = 10;
if (true) {
console.log(x);
let x = 20;
}

A

This code throws a ReferenceError. Even though there’s an x variable in the outer scope, the inner x is in the TDZ at the point of the console.log() call. Due to lexical scoping, the inner x shadows the outer one

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

var variables in JS are hoisted and set to undefined when having no value. What about let/const, are their hoisted as well?

A

Yes, but their values are not defined before initialization so they land in Temporal Dead Zone until then. If we try to access them before value assignment it will throw an ReferenceError.

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

Generators in JS

A

The Generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.
Generator is a subclass of the hidden Iterator class.

function* generator() {
yield 1;
yield 2;
yield 3;
}

const gen = generator(); // “Generator { }”

console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

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

Is it possible to create Infinite iterator in JS?

A

With a generator function, values are not evaluated until they are needed. Therefore a generator allows us to define a potentially infinite data structure.

function* infinite() {
let index = 0;

while (true) {
yield index++;
}
}

const generator = infinite(); // “Generator { }”

console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
// …

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

What is Iterator in JS?

A

An Iterator object is an object that conforms to the iterator protocol by providing a next() method that returns an iterator result object. All built-in iterators inherit from the Iterator class. The Iterator class provides a Symbol.iterator method that returns the iterator object itself, making the iterator also iterable. It also provides some helper methods for working with iterators.

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

What is Iteration protocols in JS?

A

Iteration protocols aren’t new built-ins or syntax, but protocols. These protocols can be implemented by any object by following some conventions.

There are two protocols: The iterable protocol and the iterator protocol.

The iterable protocol allows JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a for…of construct. Some built-in types are built-in iterables with a default iteration behavior, such as Array or Map, while other types (such as Object) are not.

The iterator protocol defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated.

An object is an iterator when it implements a next() method

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

What is a Map in JavaScript?

A

A Map is a collection of key-value pairs where keys and values can be of any type (primitive or objects). Unlike objects, Map preserves insertion order of elements and provides methods like set(), get(), has(), and delete() for manipulating data. Maps are optimized for frequent additions and removals of key-value pairs

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

What is a WeakMap in JavaScript?

A

A WeakMap is a collection of key-value pairs where keys must be objects (or non-registered symbols), and references to these keys are weakly held. This means if there are no other references to a key object, it can be garbage collected (removed) even if it exists in the WeakMap. WeakMap doesn’t prevent keys from being garbage collected

so weakmap works this way if we have fe:

const memoizationCache = new WeakMap();

function memoizedFunction(obj) {
if (!memoizationCache.has(obj)) {
const result = /* expensive computation using obj */;
memoizationCache.set(obj, result);
}
return memoizationCache.get(obj);
}

const memo = { data: {/* some data */} };
console.log(memoizedFunction(memo.data)); // Performs expensive computation
console.log(memoizedFunction(memo.data)); // Returns cached result

delete memo.data

then memoizationCache doesnt have memo.data key in it, and is deleted automatically.

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

What methods are available on WeakMap instances?

A

WeakMap has a limited API compared to Map, with just four methods:

set(key, value): Adds a new key-value pair

get(key): Retrieves a value by its key

has(key): Checks if a key exists

delete(key): Removes a key-value pair
WeakMap intentionally lacks any methods for enumeration (like keys(), values(), or entries())

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

Why can’t you iterate over a WeakMap’s contents?

A

WeakMap doesn’t allow enumeration of its keys or values because the contents depend on garbage collection, which would introduce non-determinism. If a WeakMap exposed methods to obtain a list of its keys, the list would depend on the state of garbage collection at any given moment, making results unpredictable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
What is a common use case for WeakMap?
WeakMap is commonly used for: Storing private data associated with objects Implementing caching/memoization where results are associated with objects Storing metadata about DOM nodes without causing memory leaks Associating data with objects that should not affect their lifecycle WeakMap allows the garbage collector to clean up object data when the object itself is no longer needed
25
Differences between useRef & useState.
26
How does useRef work inside?
27
Controlled vs uncontrolled React component
“controlled” (driven by props) or “uncontrolled” (driven by state)
28
What are microfrontends?
29
Main reasons to use microfrontends
30
Why switch(true) is wrong?
Why switch(true) should not be used: - one of the advantages of switch-case is typing. When one of the conditions is not handled, you will get an error. When we use switch(true), this advantage is lost - the occurrence of conditions will be important, but it is not visible. When using, if otherwise the conditions are well available. In the case of switch there is one of the conditions, but it is not necessary. If there is switch(true), it can be, but it will not be visible. There may be a change of conditions, when the application operation changes - possibility of no return/break statement, it may happen that there is more than one condition met.
31
What can be used instead of switch(true)?
- if-else. This is the simplest solution - the Strategy pattern. The pattern can also be used after help to get a uniform interface that provides action.
32
What is the purpose of iterator helpers in JavaScript?
To perform multiple chained array transformations efficiently without creating temporary arrays.
33
What does Iterator.prototype.drop() do?
Returns a new iterator that skips the given number of elements at the start.
34
What is the function of Iterator.prototype.take()?
Returns a new iterator that takes at most the given number of elements from the start.
35
True or False: Iterator.prototype.some() tests whether all elements produced by the iterator pass a test.
False
36
What does Iterator.prototype.every() do?
Tests whether all elements produced by the iterator pass the provided function.
37
What functionality does Iterator.prototype.filter() provide?
Returns an iterator on the filtered values.
38
How can iterables commonly be created in JavaScript?
Via the static method Iterator.from() and via the method values() of Array, NodeList, Set, and other containers.
39
Fill in the blank: The more memory efficient version of transformation chaining is: arr.values().drop(10).take(10).filter(el => el < 10).map(el => el + 5). _______.
toArray()
40
What does array.at(-1) return?
The last element of the array.
41
How does array.at(-2) differ from array[array.length - 2]?
Both return the second-to-last element, but at(-2) is more concise and readable.
42
What problem does Promise.withResolvers() solve?
It provides a cleaner way to create a promise along with its resolve and reject functions, avoiding manual variable assignment.
43
How do you use Promise.withResolvers() to create a promise and its resolvers?
const { promise, resolve, reject } = Promise.withResolvers();
44
How can you use a callback with String.prototype.replaceAll()?
You can pass a function as the second argument to perform dynamic replacements based on each match.
45
What is the output of 'A,B,C'.replaceAll(',', (m, i) => i)?
'A0B1C'
46
What is the modern way to swap two variables a and b in JavaScript?
[a, b] = [b, a];
47
What is the advantage of using structuredClone() over JSON.stringify()/parse() for deep copying objects?
structuredClone() supports more data types, handles cyclic references, and is more efficient for large objects.
48
Which API should you use to deeply clone an object with cyclic references?
structuredClone()
49
What is a tagged template in JavaScript?
A function that processes a template literal, allowing custom parsing or transformation of the interpolated values.
50
How could tagged templates help with HTML escaping?
By writing a function that escapes interpolated values in a template literal, preventing XSS vulnerabilities.
51
What is a key difference between Map/Set and WeakMap/WeakSet?
WeakMap and WeakSet only accept objects as keys and allow garbage collection when there are no references to the key.
52
When should you use WeakMap or WeakSet?
When you need to associate data with objects without preventing garbage collection of those objects.
53
What does set1.difference(set2) return?
A new set containing elements in set1 but not in set2.
54
Which method returns a set of elements present in both sets?
Set.prototype.intersection()
55
Which method returns a set of all unique elements from both sets?
Set.prototype.union()
56
Which method checks if two sets have no elements in common?
Set.prototype.isDisjointFrom()
57
Which method checks if all elements of one set are present in another set?
Set.prototype.isSubsetOf()
58
Which method checks if a set contains all elements of another set?
Set.prototype.isSupersetOf()
59
How could iterator helpers improve filtering a massive array in React?
By using iterator helpers, you can chain transformations without creating temporary arrays, improving performance in state-heavy React apps.
60
What mnemonic can help remember set operations?
'DUST' for Difference, Union, SymmetricDifference, and isSubsetOf/isSupersetOf for set comparisons.
61
Why is it risky to use JSON.stringify() for deep cloning objects with functions or cyclic references?
Because JSON.stringify() omits functions and throws errors on cyclic references, leading to incomplete or failed cloning.
62
How would you perform a memory-efficient transformation of a large array, skipping the first 10 elements, taking the next 10, filtering values less than 10, then adding 5 to each?
arr.values().drop(10).take(10).filter(el => el < 10).map(el => el + 5).toArray()
63
What is a namespace in JavaScript?
A namespace in JavaScript is a container that holds a set of identifiers (variables, functions, etc.) and helps prevent naming conflicts.
64
True or False: Namespaces are a built-in feature of JavaScript.
False: Namespaces are not a built-in feature; they are typically implemented using objects or modules.
65
Fill in the blank: In JavaScript, namespaces can be created using ______.
objects or modules
66
What is asynchronous JavaScript?
Asynchronous JavaScript allows code to run without blocking the execution of other code, enabling tasks to be performed concurrently.
67
True or False: The Event Loop is responsible for executing the code in a JavaScript environment.
True
68
What are Web APIs?
Web APIs are interfaces provided by the browser that allow JavaScript to interact with the browser environment and perform tasks such as making network requests.
69
Fill in the blank: The Event Loop continuously checks the _______ and the _______ queue for tasks to execute.
call stack, message
70
What is the primary purpose of microtasks in JavaScript?
Microtasks are used to handle tasks that need to be executed after the currently executing script but before the next rendering process.
71
Multiple Choice: Which of the following is NOT an example of a Web API? A) fetch B) setTimeout C) DOM manipulation
B) setTimeout
72
What is the difference between macrotasks and microtasks?
Macrotasks include tasks like setTimeout and setInterval, while microtasks include promises and mutation observers, with microtasks being processed before macrotasks.
73
True or False: Promises are a type of microtask.
True
74
What happens when a promise is resolved?
When a promise is resolved, its .then() handlers are added to the microtask queue to be executed after the current script execution.
75
Fill in the blank: The _______ queue is processed after the call stack is empty and before the next macrotask is executed.
microtask
76
What is the role of the call stack in JavaScript execution?
The call stack keeps track of the execution context of the currently running functions and manages function calls.
77
Multiple Choice: Which of the following can block the Event Loop? A) long-running synchronous code B) asynchronous callbacks C) microtasks
A) long-running synchronous code
78
What does the term 'event-driven programming' mean in the context of JavaScript?
Event-driven programming refers to a programming paradigm where the flow of the program is determined by events such as user actions or messages from other programs.
79
True or False: The Event Loop allows JavaScript to perform non-blocking operations.
True
80
What happens if there are multiple microtasks in the queue?
All microtasks will be executed one after the other before the Event Loop moves to the next macrotask.
81
What are the implications of using setTimeout with a delay of 0?
Using setTimeout with a delay of 0 schedules the function to run after the current call stack is cleared, but it does not run immediately.
82
Multiple Choice: Which of the following is processed first in the Event Loop? A) microtask queue B) macrotask queue
A) microtask queue
83
What is a common use cases for Web APIs in JavaScript?
Common use cases include making AJAX calls, manipulating the DOM, and handling events like clicks and keyboard inputs.
84
True or False: JavaScript is single-threaded, meaning it can only execute one command at a time.
True