JavaScript - Advanced Flashcards
call()
The call() method invokes a function with a specified this value and arguments provided individually.
For Example:
function greet(name) {
console.log(Hello, ${name}!
);
}
greet.call(null, ‘John’);
apply()
The apply() method is similar to call(), but it accepts arguments as an array or an array-like object.
For Example:
function greet(name) {
console.log(Hello, ${name}!
);
}
greet.apply(null, [‘John’]);
bind()
The bind() method creates a new function with a specified this value and partially applies arguments.
For Example:
function greet(name) {
console.log(Hello, ${name}!
);
}
const greetJohn = greet.bind(null, ‘John’);
greetJohn();
Lexical Scope
Lexical scoping means that the scope of a variable is determined by its location within the source code.
Variables are accessible within their containing functions or blocks.
Dynamic Scope
Dynamic scoping, on the other hand, determines the scope of a variable based on the flow of the program during runtime.
The scope depends on the call stack.
Explain the concept of memoization in JavaScript
Memoization is a technique to cache the results of expensive function calls and return the cached result when the same inputs occur again.
For Example:
function memoize(fn) {
const cache = {};
return function(…args) {
const key = JSON.stringify(args);
if (cache[key]) {
return cache[key];
}
const result = fn.apply(this, args); cache[key] = result; return result; }; }
const fibonacci = memoize(function(n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
});
console.log(fibonacci(5)); // Returns 5
console.log(fibonacci(10)); // Returns 55
How does Memoization improve performance?
It improves performance by avoiding unnecessary computations.
What is the process that JavaScript follows for Memory Management and Garbage Collection?
Allocation
Use
Deallocation
Garbage Collection
Garbage Collection Allocation
When objects are created, memory is allocated to store them.
Garbage Collection Use
Objects are used and referenced by variables or other objects.
Garbage Collection Deallocation
When objects are no longer needed, memory is deallocated to free up resources.
Garbage Collection Step
JavaScript’s garbage collector periodically identifies and removes objects that are no longer reachable, i.e., not referenced by any variables or objects.
Different techniques for optimizing JavaScript code
Minification
Bundling
Caching
Debouncing
Memoization
Minification
Removing unnecessary characters (whitespace, comments) to reduce file size.
Bundling
Combining multiple JavaScript files into a single file to reduce network requests.
Explain the concept of function composition in JavaScript
Function composition is the process of combining multiple functions to create a new function that performs multiple operations.
For Example:
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;
const pipe = (…fns) => (x) => fns.reduce((y, fn) => fn(y), x);
const addAndMultiply = pipe(add, multiply);
console.log(addAndMultiply(2, 3)); // Returns 10 (2 + 3 = 5, 5 * 2 = 10)
What are Web Workers in JavaScript
Web Workers are a browser feature that enables JavaScript code to run in the background on separate worker threads, separate from the main UI thread.
Explain the concept of the prototype chain in JavaScript’s object-oriented programming model.
In JavaScript’s object-oriented programming model, each object has an internal property called the prototype.
The prototype is another object that the current object can inherit properties and methods from.
If a property or method is not found on the current object, JavaScript looks for it in the prototype chain, traversing up the chain until it finds the property or reaches the end (null prototype).
What are the different ways to handle authentication and authorization in JavaScript applications?
JSON Web Tokens (JWT)
OAuth
Session-based authentication
Role-based access control (RBAC)
JSON Web Tokens (JWT)
Storing user authentication information as digitally signed tokens.
OAuth
Delegating user authentication to third-party providers like Google or Facebook.
Session-based authentication
Storing session data on the server and using cookies or session tokens to identify authenticated users.
Role-based access control (RBAC)
Assigning roles to users and granting permissions based on those roles.
What is functional programming, and how can it be applied in JavaScript?
Functional programming is a programming paradigm that emphasizes the use of pure functions, immutability, and higher-order functions.
In JavaScript, functional programming can be applied by using functions as first-class citizens, avoiding side effects, and using higher-order functions for composition and abstraction.
For Example:
// Using map and filter higher-order functions for transformation and filtering
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((n) => n * 2); // [2, 4, 6, 8, 10]
const evenNumbers = numbers.filter((n) => n % 2 === 0); // [2, 4]
// Using reduce to calculate the sum of an array
const sum = numbers.reduce((acc, n) => acc + n, 0); // 15
Explain the concept of lazy loading in JavaScript
Lazy loading is a technique that defers loading non-critical or off-screen resources until they are actually needed.
In web applications, lazy loading can be applied to images, scripts, or other assets that are not immediately visible or required for initial page rendering.
What are the benefits of LazyLoading?
Benefits of lazy loading include reduced initial page load time, improved performance, and bandwidth savings, especially for larger or media-rich websites.
What are the different techniques for handling memory leaks in JavaScript applications?
Properly managing event listeners by adding and removing them when necessary.
Clearing intervals and timeouts when they are no longer needed.
Releasing references to objects that are no longer needed.
Using a memory profiling tool to identify potential memory leaks and investigate their causes.
How does JavaScript handle data storage and retrieval in the browser?
Cookies
Web Storage API
IndexedDB
Cookies for data storage and retrieval
Small text files that can be used to store limited amounts of data.
Web Storage API
Consists of the localStorage and sessionStorage objects, allowing key-value pair storage with larger capacity than cookies.
IndexedDB
A NoSQL database built into the browser for storing larger amounts of structured data.
Please describe the JS event loop
The JavaScript event loop is a mechanism that enables JavaScript to handle asynchronous operations and event-driven programming.
It manages the execution of code by keeping track of pending tasks, such as timers, network requests, and user interactions, and schedules their execution in an efficient manner.
What are the steps taken in how the event loop works?
Call Stack
Web API’s
Callback Queue
Event Loop
Task Execution
Execution
Repeat
Event Loop: Call Stack
The event loop starts with a call stack, which is a data structure that keeps track of the currently executing functions. Any code that needs to be executed is pushed onto the call stack.
Event Loop: Web API’s
JavaScript provides various APIs like timers (setTimeout, setInterval), network requests (XMLHttpRequest, fetch), and DOM manipulation methods.
When code using these APIs is executed, the corresponding tasks are offloaded to the browser’s Web APIs for execution.
These tasks are handled separately from the main JavaScript thread.
Event Loop: Callback Queue
When a Web API task completes or an event occurs (e.g., a user clicks a button), a callback associated with that task or event is placed in the callback queue.
Event Loop: Event Loop
The event loop continuously monitors the call stack and the callback queue. If the call stack is empty, it checks if there are any callbacks in the callback queue.
Event Loop: Task Execution
If there are callbacks in the callback queue, the event loop takes the oldest callback and pushes it onto the call stack for execution.
The callback is then removed from the callback queue.
Event Loop: Execution
The callback function is executed, and any synchronous code inside it is processed.
If there are additional asynchronous tasks within the callback, such as timer callbacks or AJAX callbacks, they are registered for future execution.
Event Loop: Repeat
The event loop repeats this process, continuously monitoring the call stack and the callback queue, ensuring that tasks are executed in the order they were added.