50 Javascript Q&A-1
50 Javascript Q&A-1
function outer() {
let count = 0;
function inner() {
count++;
console.log(count);
}
return inner;
}
Example:
function bankAccount(initialBalance) {
let balance = initialBalance;
return {
deposit: function(amount) {
Javascript Q & A 1
balance += amount;
},
getBalance: function() {
return balance;
}
};
}
function outer() {
const name = "John";
function inner() {
console.log(name); // Accesses name from outer scope
}
inner();
}
outer();
function createPerson(name) {
let age = 0;
return {
getName: () => name,
Javascript Q & A 2
getAge: () => age,
setAge: (newAge) => age = newAge
};
}
let and const: Block scope; accessible only within the block they're
declared.
Example:
function scopeTest() {
if (true) {
var a = 10; // Function scope
let b = 20; // Block scope
const c = 30; // Block scope
}
console.log(a); // 10
console.log(b); // ReferenceError
console.log(c); // ReferenceError
}
scopeTest();
Javascript Q & A 3
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, current) => accumulator + curr
ent, 0);
console.log(sum); // 10
Example:
Javascript Q & A 4
Example:
Example:
fetchData
.then(data => console.log(data)) // "Data fetched successfully!"
.catch(error => console.error(error));
Javascript Q & A 5
Example:
class CustomPromise {
constructor(executor) {
this.state = "pending";
this.value = undefined;
this.callbacks = [];
executor(resolve, reject);
}
then(onFulfilled) {
if (this.state === "fulfilled") {
onFulfilled(this.value);
} else {
this.callbacks.push(onFulfilled);
}
}
}
// Example usage:
const promise = new CustomPromise((resolve, reject) => {
setTimeout(() => resolve("Custom Promise Resolved!"), 1000);
Javascript Q & A 6
});
Example:
Example:
Javascript Q & A 7
Promise.finally() is used to execute code after a Promise is settled (resolved or
rejected), regardless of the outcome.
Example:
fetch("https://api.example.com/data")
.then(response => console.log("Data fetched"))
.catch(error => console.error("Error occurred"))
.finally(() => console.log("Cleanup actions"));
Example:
const obj = {
name: "Alice",
greet: function() {
console.log(this.name);
}
};
obj.greet(); // "Alice"
Example:
function greet() {
console.log(this.name);
}
Javascript Q & A 8
const person = { name: "Alice" };
greet.call(person); // "Alice"
Example:
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
}
function higherOrder(fn) {
return function(x) {
return fn(x) * 2;
};
}
Javascript Q & A 9
Arrow functions do not have their own this . Instead, they inherit this from their
surrounding lexical scope.
Example:
const obj = {
name: "Alice",
greet: () => console.log(this.name)
};
Object-Oriented JavaScript
Example:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
Javascript Q & A 10
Prototypal inheritance allows objects to inherit properties and methods from
other objects via the prototype chain.
Example:
const animal = {
speak: function() {
console.log(`${this.name} makes a noise.`);
}
};
class Animal {}
const dog = new Animal();
console.log(dog instanceof Animal); // true
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
Javascript Q & A 11
set name(newName) {
this._name = newName;
}
}
Event Handling
Example:
Javascript Q & A 12
28. Explain the event loop.
The event loop is a mechanism that handles asynchronous operations by
continuously checking the call stack and the task queue.
Bubble phase: Event propagates from the target back to the root.
DOM Manipulation
Javascript Q & A 13
with the real DOM (diffing) and applying minimal changes.
Example:
Javascript Q & A 14
const parent = document.getElementById("parent");
const firstChild = parent.firstChild;
const nextSibling = firstChild.nextSibling;
console.log(nextSibling);
Design Patterns
Example:
Javascript Q & A 15
class Subject {
constructor() {
this.observers = [];
}
subscribe(observer) {
this.observers.push(observer);
}
notify(data) {
this.observers.forEach(observer => observer(data));
}
}
Example:
Javascript Q & A 16
39. Explain the Factory pattern.
The Factory pattern provides a way to create objects without specifying their
exact class.
Example:
function CarFactory() {
this.createCar = function (make, model) {
return new Car(make, model);
};
}
Example:
const PubSub = {
events: {},
subscribe: function (event, callback) {
if (!this.events[event]) this.events[event] = [];
this.events[event].push(callback);
},
publish: function (event, data) {
if (this.events[event]) {
this.events[event].forEach(callback => callback(data));
}
}
Javascript Q & A 17
};
Error Handling
Example:
try {
throw new Error("Something went wrong!");
} catch (error) {
console.error(error.message);
}
Example:
function testThrow() {
throw new Error("Error thrown!");
}
function testReturn() {
return "Function returned!";
}
try {
testThrow();
} catch (error) {
console.error(error.message);
}
Javascript Q & A 18
console.log(testReturn());
try {
throw new CustomError("This is a custom error!");
} catch (error) {
console.error(error.name, error.message);
}
Javascript Q & A 19
45. How do you handle uncaught exceptions?
Use process.on("uncaughtException") in Node.js or window.onerror in browsers.
Example (Node.js):
Performance
Javascript Q & A 20
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
49. What are memory leaks and how do you prevent them?
Memory leaks occur when objects are no longer needed but are not garbage
collected. Prevent them by:
Javascript Q & A 21
observer.observe(document.querySelector("#scroll-anchor"));
Javascript Q & A 22