JavaScript - Advanced Flashcards

1
Q

What is the call() method?

A

The call method is used to invoke a function with a specified this value and arguments provided individually.

It takes the function’s this value as the first argument, followed by the function arguments.

function greet(name) {
console.log(Hello, ${name}! I am ${this.role}.);
}

const person = {
role: ‘developer’,
};

greet.call(person, ‘John’);

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

What is the appy() method?

A

The apply method is similar to call, but it accepts arguments as an array or an array-like object.

The first argument is still the this value.

function greet(name) {
console.log(Hello, ${name}! I am ${this.role}.);
}

const person = {
role: ‘developer’,
};

greet.apply(person, [‘John’]);

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

What is the bind() method?

A

The bind method returns a new function with the specified this value and partially applied arguments.

It does not immediately invoke the function but allows you to store it for later use.

function greet(name) {
console.log(Hello, ${name}! I am ${this.role}.);
}

const person = {
role: ‘developer’,
};

const greetPerson = greet.bind(person);
greetPerson(‘John’);

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

What is the difference between the call(), apply() and bind() methods?

A

The main difference is that call and apply invoke the function immediately, whereas bind returns a new function that can be invoked later.

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

Explain the concept of lexical scoping?

A

Lexical scoping, also known as static scoping, is a scoping mechanism where the scope of a variable is determined by its location in the source code during the lexical phase of compilation.

In JavaScript, variables are scoped to the nearest enclosing block or function.

function outer() {
const x = 10;

function inner() {
console.log(x); // Accessible due to lexical scoping
}

inner();
}

outer();

In the example above, the inner function can access the variable x defined in its outer function due to lexical scoping.

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

Explain the concept of Dynamic Scoping?

A

Dynamic scoping is a scoping mechanism where the scope of a variable is determined by the current execution context or the calling stack.

In dynamic scoping, the scope chain is based on the runtime flow of the program.

Dynamic scoping is not natively supported in JavaScript, as it follows lexical scoping. However, you can simulate dynamic scoping behavior using the this context or by using the call or apply methods to change the execution context.

For example:

function outer() {
const x = 10;

function inner() {
console.log(this.x); // Accessible due to dynamic scoping (context-based)
}

inner.call({ x: 20 }); // Change the execution context dynamically
}

outer();

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

What is the key difference between Lexical Scoping and Dynamic Scoping?

A

lexical scoping is determined by the structure of the code, while dynamic scoping is based on the runtime context or calling stack.

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

What are the different ways to create classes in JavaScript?

A

Constructor Functions

ES6 Classes

Factory Functions

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

Constructor Functions

A

Constructor functions use the new keyword to create instances of an object with shared properties and methods.

They define properties and methods inside the constructor function using this.

function Person(name) {
this.name = name;
}

Person.prototype.greet = function() {
console.log(Hello, my name is ${this.name}.);
};

const john = new Person(‘John’);
john.greet();

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

ES6 Classes

A

ES6 introduced a more concise syntax for creating classes using the class keyword. They provide a cleaner syntax for defining classes and their methods.

class Person {
constructor(name) {
this.name = name;
}

greet() {
console.log(Hello, my name is ${this.name}.);
}
}

const john = new Person(‘John’);
john.greet();

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

Factory Functions

A

Factory functions are functions that return an object. They encapsulate the creation logic and allow you to create multiple instances with different internal states.

function createPerson(name) {
return {
name,
greet() {
console.log(Hello, my name is ${this.name}.);
}
};
}

const john = createPerson(‘John’);
john.greet();

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

Explain the concept of memoization in JavaScript and how it can improve performance.

A

Memoization is a technique used to optimize function performance by caching the results of expensive function calls and returning the cached result when the same inputs occur again.

It aims to avoid redundant computations and improve overall execution speed.

function fibonacci(n, cache = {}) {
if (n in cache) {
return cache[n]; // Return cached result
}

if (n <= 2) {
return 1;
}

const result = fibonacci(n - 1, cache) + fibonacci(n - 2, cache);
cache[n] = result; // Cache the result for future use
return result;
}

console.log(fibonacci(10)); // 55

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

How does JavaScript handle memory management and garbage collection?

A

The garbage collector is responsible for managing memory allocation and deallocation to ensure efficient memory usage in JavaScript applications.

The process of garbage collection involves the following steps: marking, sweeping, memory compaction.

JavaScript’s garbage collector is typically implemented as a generational garbage collector. It divides objects into different generations based on their age. New objects are allocated in the “young” generation, and if they survive a certain number of garbage collection cycles, they are promoted to the “old” generation.

The garbage collector in JavaScript works transparently in the background, automatically reclaiming memory that is no longer in use. Developers do not need to explicitly free memory as it is managed by the JavaScript runtime environment.

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

Describe Garbage Collection Marking

A

The garbage collector traverses the entire object graph starting from the root objects (global objects, objects on the stack, etc.) and marks all the objects that are reachable or in use.

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

Describe Garbage Collection Sweeping

A

After marking, the garbage collector sweeps through the memory, deallocating or freeing the memory occupied by the objects that are not marked as reachable.

These objects are considered no longer needed and can be safely removed from memory.

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

Describe Garbage Collection Memory Compaction

A

Some garbage collectors may include an additional step of memory compaction, where the live objects are moved together to reduce memory fragmentation and optimize memory usage.

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

What is the purpose of the Proxy object in JavaScript?

A

The Proxy object in JavaScript is used to define custom behavior for fundamental operations (e.g., property access, assignment, function invocation) on an object.

It allows you to intercept and customize the default behavior of an object, providing a powerful mechanism for creating proxies with controlled access to underlying objects.

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

What are the steps of the event driven architecture as implemented in JavaScript?

A

Event Registration

Event Triggering

Event Loop

Event Handling

Repeat

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

Event Registration

A

JavaScript code registers event listeners or event handlers on specific elements or objects to listen for specific events. For example, adding a click event listener to a button.

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

Event Triggering

A

When an event occurs (e.g., a button is clicked, a timer expires, an HTTP request completes), the event is added to the event queue.

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

Event Loop

A

The event loop continuously checks the event queue for pending events. If there is an event in the queue, it fetches the event and invokes the corresponding event handler or callback function associated with that event.

22
Q

Event Handling

A

The event handler executes the code associated with the event, performing the desired actions or invoking other functions.

23
Q

Repeat

A

The event loop keeps iterating, handling events as they occur and ensuring that other code can execute alongside event-driven operations.

24
Q

What are the different techniques for optimizing JavaScript code

A

Minification

Bundling

Code Splitting

Caching

Optimized Loops

Avoiding Global Variables

Debouncing & Throttling

Useing Efficient Data Structures and Algorithms

25
Q

Minification

A

Minification reduces the size of JavaScript code by removing unnecessary characters like whitespaces, comments, and renaming variables.

This improves loading times.

26
Q

What are tools that can be used for Minification

A

UglifyJS

Terser

27
Q

Bundling

A

Bundling combines multiple JavaScript files into a single file, reducing the number of HTTP requests required to fetch scripts.

28
Q

What are tools that can be used for Bundling

A

Webpack

Rollup.js

29
Q

Code Splitting

A

Code splitting allows you to split your JavaScript code into smaller chunks, and load only the required code when needed. This can improve initial page load times.

30
Q

Caching

A

Caching involves storing frequently used or static data in memory or local storage to avoid repetitive calculations or network requests.

This can be achieved using techniques like memoization or leveraging browser caching mechanisms.

31
Q

Optimized Loops

A

Optimizing loops by reducing unnecessary computations, avoiding excessive function calls, and minimizing DOM interactions can improve performance.

Techniques like loop unrolling or loop inversion can be used to optimize loops.

32
Q

Explain the concept of function composition in JavaScript?

A

Function composition is a technique in JavaScript where two or more functions are combined to create a new function.

The output of one function becomes the input of the next, allowing for the creation of complex and reusable code by chaining together simpler functions.

In JavaScript, function composition can be achieved using higher-order functions, which are functions that take one or more functions as arguments and/or return a new function.

For Example:

function add(a, b) {
return a + b;
}

function multiply(a, b) {
return a * b;
}

function subtract(a, b) {
return a - b;
}

// Function composition using higher-order functions
function compose(…functions) {
return function (x, y) {
return functions.reduce(function (result, fn) {
return fn(result[0], result[1]);
}, [x, y]);
};
}

const calculate = compose(add, multiply, subtract);

console.log(calculate(4, 2)); // Output: 6

When calculate(4, 2) is called, the arguments (4 and 2) are passed through the composed functions in the order of composition: subtract(4, 2) -> multiply(2, 2) -> add(2, 4), resulting in the output 6.

33
Q

Why would you use functional composition?

A

Function composition enables code reusability, modularity, and the creation of more expressive and declarative code by breaking down complex operations into smaller, composable functions.

It promotes code maintainability and encourages functional programming principles in JavaScript.

34
Q

What are Web Workers in JavaScript and how do they enable multithreading?

A

Web Workers are a feature in JavaScript that enable concurrent execution of code in a separate background thread, allowing for true multithreading in web applications.

They provide a way to perform computationally intensive or time-consuming tasks without blocking the main thread, which is responsible for rendering the user interface and responding to user interactions.

Web Workers allow you to create new JavaScript threads, called worker threads, that run parallel to the main thread.

These worker threads can execute JavaScript code independently and communicate with the main thread using message passing.

35
Q

What are the different ways to handle authentication and authorization in JavaScript applications?

A

Session-based Authentication

Token-based Authentication

OAuth and OpenID Connect

Single Sign-On (SSO)

Social Authentication

36
Q

Session-based Authentication

A

the server creates a session for each authenticated user and stores session data on the server.

The client receives a session ID in a cookie or token, which is sent with each subsequent request to the server for authentication and authorization.

37
Q

Token-based Authentication

A

Token-based authentication involves issuing a token (e.g., JSON Web Token or JWT) to the client upon successful authentication.

The token is then included in the headers of subsequent requests for authorization.

The server verifies the token to grant access to protected resources.

38
Q

OAuth and OpenID Connect

A

OAuth is a widely used protocol for authorization, enabling users to grant access to their resources on one website to another website without sharing their credentials.

OpenID Connect builds on OAuth and provides authentication services on top of it, allowing users to authenticate using third-party identity providers like Google or Facebook.

39
Q

Single Sign-On (SSO)

A

SSO enables users to authenticate once and access multiple applications without re-entering credentials.

SSO solutions like SAML (Security Assertion Markup Language) and OpenID Connect facilitate secure authentication across different domains.

40
Q

Social Authentication

A

Social authentication allows users to authenticate using their social media accounts (e.g., Facebook, Google, Twitter).

JavaScript libraries like Firebase Authentication provide easy integration with popular social login providers.

41
Q

What are Pure Functions?

A

Pure functions are the foundation of functional programming.

They take input arguments and return a value without modifying external state.

Pure functions have no side effects, making them predictable and easier to reason about.

For Example:

function add(a, b) {
return a + b;
}

const result = add(2, 3); // Returns 5

42
Q

What is Immutable Data in functional programming?

A

Immutable data cannot be modified once created, making it easier to reason about and enabling efficient change detection.

For Example:

const person = { name: “Alice”, age: 25 };

// Updating the age using object spread syntax (immutably)
const updatedPerson = { …person, age: 26 };
// person is unchanged, updatedPerson is a new object with updated age

43
Q

What are reasons why you would code using functional programming?

A

Functional programming encourages writing code that is declarative, modular, and composable.

It promotes the use of pure functions, immutability, and higher-order functions, leading to more maintainable, testable, and scalable code.

44
Q

What are the different methods for manipulating the DOM in JavaScript?

A

getElementById

getElementsByClassName

getElementsByTagName

getElementsByClassName

querySelector

querySelectorAll

45
Q

getElementById

A

This method retrieves an element from the document by its unique ID.

It is the fastest method for accessing an element because it relies on the browser’s internal lookup mechanism.

46
Q

getElementsByClassName

A

This method retrieves a collection of elements that have a specific class name.

It is slower than getElementById as it needs to traverse the DOM tree to find matching elements.

47
Q

getElementsByTagName

A

This method retrieves a collection of elements that have a specific tag name (e.g., div, p, span).

It is similar to getElementsByClassName in terms of performance.

48
Q

querySelector

A

This method allows selecting elements using CSS selector syntax. It returns the first matching element.

It is slower than getElementById but provides more flexibility in element selection.

49
Q

querySelectorAll

A

This method returns a static NodeList containing all the elements that match the specified CSS selector.

It is slower than the previous methods but useful for selecting multiple elements.

50
Q

Explain the concept of reactive programming

A

Reactive programming is a programming paradigm that focuses on the propagation of changes and automatic handling of data dependencies.

It involves expressing the dynamic behavior of a system using reactive data streams, where changes to data are automatically propagated to dependent components or functions.

In reactive programming, data streams, also known as observables or streams, represent values over time. These streams can emit new values, be transformed, combined, and consumed by observers.

Observers subscribe to streams and react to changes by executing functions or updating UI components.

51
Q

When can Memory leaks can occur in JavaScript applications

A

when objects are unintentionally kept in memory, preventing them from being garbage collected.