JavaScript Closures
JavaScript Closures
A closure is a function that retains access to its lexical scope, even when the function is executed
outside that scope.
Example:
javascript
Copy code
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log('Outer Variable:', outerVariable);
console.log('Inner Variable:', innerVariable);
};
}
Memoization in JavaScript
Memoization is an optimization technique that stores the results of expensive function calls and
returns the cached result when the same inputs occur again.
Example:
javascript
Copy code
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) {
return cache[key];
}
const result = fn(...args);
cache[key] = result;
return result;
};
}
console.log(factorial(5)); // 120
console.log(factorial(5)); // Cached 120
Q: Explain the difference between the event loop and the call stack in JavaScript.
Event Loop: Manages asynchronous operations by checking the call stack and callback queue.
Example:
javascript
Copy code
console.log('Start');
setTimeout(() => {
console.log('Callback');
}, 0);
console.log('End');
Explanation: 'Start' and 'End' are logged first due to synchronous execution. 'Callback' is
executed last, managed by the event loop.
Generators in JavaScript
Example:
javascript
Copy code
function* generatorFunction() {
yield 'Hello';
yield 'World';
}
Example:
javascript
Copy code
const obj = {
name: 'Alice',
getName: function() {
return this.name;
}
};
console.log(obj.getName()); // 'Alice'
Web Workers
Q: What are Web Workers in JavaScript, and how do they enable multi-threading in web
applications?
Example:
javascript
Copy code
// worker.js
self.onmessage = function(e) {
self.postMessage(e.data * 2);
};
// main.js
const worker = new Worker('worker.js');
worker.onmessage = function(e) {
console.log(e.data); // Output from worker
};
worker.postMessage(10);
Example:
javascript
Copy code
// Callback Hell
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log(finalResult);
});
});
});
// Promises
doSomething()
.then(result => doSomethingElse(result))
.then(newResult => doThirdThing(newResult))
.then(finalResult => console.log(finalResult))
.catch(error => console.error(error));
Module Pattern
Q: Explain the “module pattern” in JavaScript and how it facilitates encapsulation and
modularity.
Example:
javascript
Copy code
const Module = (function() {
let privateVar = 'secret';
function privateMethod() {
console.log(privateVar);
}
return {
publicMethod: function() {
privateMethod();
}
};
})();
Module.publicMethod(); // 'secret'
Q: What are “rest” and “spread” operators in JavaScript, and how do they work?
Rest Operator: Collects arguments into an array. Spread Operator: Expands array into
individual elements.
Example:
javascript
Copy code
// Rest
function sum(...args) {
return args.reduce((acc, val) => acc + val, 0);
}
console.log(sum(1, 2, 3)); // 6
// Spread
const arr = [1, 2, 3];
const newArr = [...arr, 4, 5];
console.log(newArr); // [1, 2, 3, 4, 5]
Prototype Chain
Q: What is the “prototype chain” in JavaScript, and how does it relate to inheritance?
Example:
javascript
Copy code
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log('Hello, ' + this.name);
};
Q: What is the Event Loop in JavaScript, and how does it enable asynchronous operations?
Event Loop: Manages execution of code, handling events, and executing queued sub-tasks.
Example:
javascript
Copy code
console.log('Start');
setTimeout(() => {
console.log('Callback');
}, 0);
console.log('End');
Explanation: 'Start' and 'End' log first. 'Callback' logs after, managed by the event loop.
Hoisting in JavaScript
Q: Explain the concept of “Hoisting” in JavaScript. How does it affect variable and
function declarations?
Example:
javascript
Copy code
console.log(a); // undefined
var a = 5;
Explanation: var is hoisted, initialized to undefined. let is not accessible before declaration.
Example:
javascript
Copy code
const obj = {
value: 10,
regularFunction: function() {
console.log(this.value); // 10
},
arrowFunction: () => {
console.log(this.value); // undefined
}
};
obj.regularFunction();
obj.arrowFunction();
Currying in JavaScript
Q: Explain the concept of “currying” in JavaScript and how it can be used to transform a
function into a series of unary functions.
Currying: Transforms a function into a sequence of functions, each with a single argument.
Example:
javascript
Copy code
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args);
} else {
return function(...nextArgs) {
return curried(...args, ...nextArgs);
};
}
};
}
function add(a, b) {
return a + b;
}
Observer Pattern
Q: What is the “Observer” pattern in JavaScript, and how can it be used to implement the
Publish-Subscribe model for handling events?
Example:
javascript
Copy code
class Subject {
constructor() {
this.observers = [];
}
subscribe(observer) {
this.observers.push(observer);
}
unsubscribe(observer) {
this.observers = this.observers.filter(obs => obs !== observer);
}
notify(data) {
this.observers.forEach(observer => observer.update(data));
}
}
class Observer {
update(data) {
console.log('Received data:', data);
}
}
subject.subscribe(observer);
subject.notify('Hello World'); // 'Received data: Hello World'
Q: How does JavaScript handle memory management, and what are some best practices to
avoid memory leaks?
Best Practices:
Example:
javascript
Copy code
let data = {};
function processData() {
let local = {};
data.local = local;
}
processData();
data = null; // Clear reference to allow GC
localStorage vs sessionStorage
Q: What are the key differences between the “localStorage” and “sessionStorage” in web
storage for storing data in the browser?
localStorage: Persistent data across sessions. sessionStorage: Data per session, cleared on tab
close.
Example:
javascript
Copy code
// localStorage
localStorage.setItem('key', 'value');
console.log(localStorage.getItem('key')); // 'value'
// sessionStorage
sessionStorage.setItem('key', 'value');
console.log(sessionStorage.getItem('key')); // 'value'
Q: Explain how the “prototype” property is used in JavaScript for inheritance and how it
differs from the “constructor” property.
prototype: Shared properties/methods for instances. constructor: Reference to the function that
created the instance.
Example:
javascript
Copy code
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log('Hello, ' + this.name);
};
Proxy in JavaScript
Q: What is a “proxy” in JavaScript, and how can it be used to intercept and control access
to objects?
Example:
javascript
Copy code
const target = {
message: 'Hello'
};
const handler = {
get: function(target, property) {
return property in target ? target[property] : 'Property not found';
}
};
Destructuring Assignment
javascript
Copy code
// Destructuring
const [a, b] = [1, 2];
const {name, age} = {name: 'Alice', age: 25};
// Spread
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4];
// Rest
function sum(...args) {
return args.reduce((acc, val) => acc + val, 0);
}
console.log(a, b); // 1 2
console.log(name, age); // 'Alice' 25
console.log(arr2); // [1, 2, 3, 4]
console.log(sum(1, 2, 3)); // 6
Explanation: Destructuring extracts values. Spread expands arrays. Rest collects arguments.
Promises in JavaScript
Example:
javascript
Copy code
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Success!');
}, 1000);
});
promise
.then(result => console.log(result)) // 'Success!'
.catch(error => console.error(error));
Explanation: Promise handles async operation, allows chaining with then and catch.
Q: What is “lazy loading” in JavaScript, and how can it improve web performance?
Lazy Loading: Defers loading of resources until needed.
Example:
javascript
Copy code
// Lazy load image
const img = document.createElement('img');
img.src = 'path/to/image.jpg';
document.body.appendChild(img);
document.addEventListener('scroll', () => {
if (img.getBoundingClientRect().top < window.innerHeight) {
img.src = 'path/to/high-resolution-image.jpg';
}
});
Q: Explain the “singleton pattern” in JavaScript and its use in ensuring a single instance of
a class is created.
Example:
javascript
Copy code
class Singleton {
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
this.value = 'Hello';
Singleton.instance = this;
}
}
Q: What is the “Revealing Module Pattern” in JavaScript, and how does it help create
modular and maintainable code?
Revealing Module Pattern: Encapsulates, exposes public methods/variables.
Example:
javascript
Copy code
const Module = (function() {
let privateVar = 'secret';
function privateMethod() {
console.log(privateVar);
}
function publicMethod() {
privateMethod();
}
return {
publicMethod: publicMethod
};
})();
Module.publicMethod(); // 'secret'
Q: How does JavaScript handle “hoisting” with “let” and “const” compared to “var,” and
what are the implications for variable declarations?
Example:
javascript
Copy code
console.log(a); // undefined
var a = 5;
const c = 5;
c = 6; // TypeError: Assignment to constant variable.
Example:
javascript
Copy code
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) {
return cache[key];
}
const result = fn(...args);
cache[key] = result;
return result;
};
}
console.log(fibonacci(10)); // 55
Immutability in JavaScript
Q: Explain the concept of “immutability” in JavaScript and how it can lead to more
predictable and maintainable code.
Example:
javascript
Copy code
const person = {
name: 'Alice',
age: 25
};
// Shallow copy
const newPerson = Object.assign({}, person);
newPerson.age = 26;
console.log(person.age); // 25
console.log(newPerson.age); // 26
console.log(person.age); // 25
console.log(deepCopy.age); // 27
Callbacks: Functions passed as arguments for async tasks. Promises: Objects representing
future completion of async tasks.
Example:
javascript
Copy code
// Callback
function fetchData(callback) {
setTimeout(() => {
callback('Data received');
}, 1000);
}
// Promise
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data received');
}, 1000);
});
}
Explanation: Callbacks can lead to callback hell. Promises flatten async code, handle errors.
Q: Explain the “garbage collection” process in JavaScript and how it manages memory
resources.
javascript
Copy code
let data = { name: 'Alice' };
data = null; // GC can reclaim memory
Q: What is the “Temporal Dead Zone” in JavaScript, and how does it relate to variable
declarations with “let” and “const”?
Example:
javascript
Copy code
console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a = 5;
const b = 10;
console.log(b); // 10
Closure in JavaScript
Q: What is a “closure” in JavaScript, and how does it impact variable scope and memory
management?
Example:
javascript
Copy code
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log('Outer Variable:', outerVariable);
console.log('Inner Variable:', innerVariable);
};
}
Asynchronous Generators
Q: What are “asynchronous generators” in JavaScript, and how can they simplify
asynchronous code?
Example:
javascript
Copy code
async function* asyncGenerator() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(3);
}
(async () => {
for await (let value of asyncGenerator()) {
console.log(value);
}
})();
Flyweight Pattern
Q: Explain the “Flyweight Pattern” in JavaScript and how it optimizes memory usage by
sharing common parts of objects.
Example:
javascript
Copy code
class Flyweight {
constructor(sharedState) {
this.sharedState = sharedState;
}
}
class FlyweightFactory {
constructor() {
this.flyweights = {};
}
getFlyweight(sharedState) {
if (!this.flyweights[sharedState]) {
this.flyweights[sharedState] = new Flyweight(sharedState);
}
return this.flyweights[sharedState];
}
}
requestAnimationFrame
Example:
javascript
Copy code
function animate() {
let start = null;
function step(timestamp) {
if (!start) start = timestamp;
let progress = timestamp - start;
// Update animation state
if (progress < 2000) { // Run for 2 seconds
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
}
animate();
Q: Explain the concept of “throttling” and “debouncing” in JavaScript and how they are
used to control the frequency of function calls.
Throttling: Limits function calls to a fixed interval. Debouncing: Delays function calls until
after a delay.
Example:
javascript
Copy code
// Throttle
function throttle(func, limit) {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// Debounce
function debounce(func, delay) {
let timeout;
return function() {
const args = arguments;
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), delay);
};
}
Explanation: throttle controls call frequency. debounce delays call until idle.
Q: What is the “reduce” function in JavaScript, and how can it be used to accumulate
values from an array into a single result?
Example:
javascript
Copy code
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator +
currentValue, 0);
console.log(sum); // 15
Q: Explain the concept of “Promise chaining” in JavaScript and how it simplifies handling
multiple asynchronous operations.
Example:
javascript
Copy code
function fetchData() {
return new Promise(resolve => setTimeout(() => resolve('Data received'),
1000));
}
fetchData()
.then(result => {
console.log(result); // 'Data received'
return fetchData();
})
.then(result => {
console.log(result); // 'Data received'
})
.catch(error => console.error(error));
WebSockets
Example:
javascript
Copy code
const socket = new WebSocket('ws://example.com/socket');
socket.onopen = function() {
console.log('Connection opened');
socket.send('Hello Server');
};
socket.onmessage = function(event) {
console.log('Received:', event.data);
};
socket.onclose = function() {
console.log('Connection closed');
};
Q: What is “map”, “filter”, and “reduce” in JavaScript, and how do they compare in terms
of array manipulation?
map: Transforms array elements. filter: Filters array elements. reduce: Accumulates array
elements.
Example:
javascript
Copy code
const numbers = [1, 2, 3, 4, 5];
// map
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]
// reduce
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
Web Components
Q: What are “Web Components” in JavaScript, and how do they enhance code reusability
and encapsulation in web development?
Example:
javascript
Copy code
class MyComponent extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = '<p>Hello World</p>';
}
}
customElements.define('my-component', MyComponent);
document.body.appendChild(new MyComponent());
Explanation: Web Components create reusable custom elements with encapsulated styles and
behavior.
Q: Explain the concepts of “memoization” and “caching” in JavaScript and how they are
used to optimize function performance.
Example:
javascript
Copy code
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) {
return cache[key];
}
const result = fn(...args);
cache[key] = result;
return result;
};
}
console.log(factorial(5)); // 120