JS Interview Questions-1
JS Interview Questions-1
Disadvantages of Javascript:
1. Security Concerns: Being executed on the client side exposes it to
security vulnerabilities. Developers need to be cautious to prevent
issues like Cross-Site Scripting (XSS).
2. Browser Dependency: Different browsers may interpret JavaScript
code differently, leading to potential compatibility issues.
3. Client-Side Limitations: As a client-side scripting language,
JavaScript's capabilities are limited by the client's resources and
processing power.
4. Single-threaded: While asynchronous operations help, JavaScript
remains single-threaded, which can lead to performance bottlenecks
for complex tasks.
5. Learning Curve: For beginners, JavaScript's loose typing and
asynchronous nature might pose a learning curve compared to more
structured languages.
// Object spread
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // Creates a new object { a: 1, b:
2, c: 3 }
console.log(deepCopy); // Outputs { a: 1, b: { c: 2 } }
// Modifying the nested object in the deep copy does not affect the
original object
deepCopy.b.c = 999;
console.log(originalObject); // Outputs { a: 1, b: { c: 2 } }
// Modifying the nested array in the shallow copy also affects the
original array
shallowCopy[2][0] = 999;
console.log(originalArray); // Outputs [1, 2, [999, 4]]
Q6. What is Promise, Callback function, async await in Javascript.
Ans:
1. Promise: A promise in JavaScript is an object that represents the
eventual completion or failure of an asynchronous operation and its
resulting value. It's a way to handle asynchronous code more cleanly
and avoid callback hell.
A promise has three states:
1. Pending: The initial state; the promise is neither fulfilled nor
rejected.
2. Fulfilled: The operation completed successfully, and the promise
has a resulting value.
3. Rejected: The operation failed, and the promise has a reason for
the failure.
E.g.
const myPromise = new Promise((resolve, reject) => {
// Some asynchronous operation
const success = true;
if (success) {
resolve("Operation succeeded!"); // Fulfilled
} else {
reject("Operation failed!"); // Rejected
}
});
function handleData(data) {
console.log(data);
}
fetchData();
Q7. Disadvantages of Callback Function.
Ans:
1. Callback Hell (Pyramid of Doom): When multiple asynchronous
operations are nested within each other, it can lead to callback hell,
also known as the pyramid of doom. This makes the code hard to read
and maintain.
E.g.
fetchData(function (data) {
process1(function (result1) {
process2(function (result2) {
// More nested callbacks...
});
});
});
b. Promise:
fetchData()
.then(process1)
.then(process2)
.catch(handleError);
2. Error Handling:
a. Callback:
fetchData(function (data) {
if (data.error) {
handleError(data.error);
} else {
processData(data);
}
});
b. Promise:
fetchData()
.then(processData)
.catch(handleError);
3. Composition:
a. Callback: Composing asynchronous operations using callbacks
can be challenging and may result in deeply nested functions.
b. Promise: Promises allow for better composition of asynchronous
operations using .then() and .catch() methods, providing a
cleaner and more modular code structure.
1. Event Bubbling: In event bubbling, the event starts from the target
element and bubbles up through its ancestors in the DOM hierarchy.
The innermost element's event handler is executed first, followed by
its parent element's event handler, and so on, until the outermost
ancestor is reached. This is the default behavior for most modern
browsers.
E.g.
<div id="parent">
<button id="child">Click me</button>
</div>
<script>
document.getElementById('parent').addEventListener('click',
function() {
console.log('Parent div clicked');
});
document.getElementById('child').addEventListener('click',
function() {
console.log('Button clicked');
});
</script>
2. Event Capturing: In event capturing (also known as trickling), the event starts
from the outermost ancestor and trickles down to the target element. The
outermost ancestor's event handler is executed first, followed by its child
element's event handler, and so on, until the target element is reached.
E.g.
<div id="parent">
<button id="child">Click me</button>
</div>
<script>
document.getElementById('parent').addEventListener('click',
function() {
console.log('Parent div clicked (capturing phase)');
}, true); // The 'true' parameter enables event capturing.
document.getElementById('child').addEventListener('click',
function() {
console.log('Button clicked');
});
</script>
fetchData((result) => {
console.log(result);
});
Q12. How does Promise works and different stages of Promise.
Ans:
if (success) {
resolve("Operation completed successfully");
} else {
reject("Operation failed");
}
}, 2000); // Simulating a 2-second delay
});
// Handling the Promise
myPromise
.then((result) => {
console.log("Fulfilled:", result); // Will be called if the
promise is fulfilled
})
.catch((error) => {
console.error("Rejected:", error); // Will be called if the
promise is rejected
})
.finally(() => {
console.log("Finally: This block will be executed regardless of
the promise's state");
});
2. Object Constructor:
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function () {
console.log(`Hello, my name is ${this.name} and I'm
${this.age} years old.`);
};
}
4. Class Syntax:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I'm
${this.age} years old.`);
}
}
5. Factory Function:
function createPerson(name, age) {
return {
name: name,
age: age,
greet: function () {
console.log(`Hello, my name is ${this.name} and I'm
${this.age} years old.`);
}
};
}
E.g.
function Animal(type) {
this.type = type;
}
Animal.prototype.sound = function () {
console.log("Some generic sound");
};
Object.seal(person);
Map Set
weakMap.set(obj, "ok");
2. WeakSet: WeakSet is Set -like collection that stores only objects and
removes them once they become inaccessible by other means.
E.g.
let visitedSet = new WeakSet();
2. Local Storage:
a. Scope: Persists even after the browser is closed and reopened. It
is available across browser sessions and tabs.
b. Lifespan: Long-term, persists until explicitly cleared by the user
or the web application.
E.g.
// Store data in localStorage
localStorage.setItem("key", "value");
3. Cookies:
a. Scope: Cookies can have different scopes depending on their
attributes. They can be set to expire when the session ends
(session cookies) or persist for a specified duration (persistent
cookies).
b. Lifespan: Can be set to expire when the session ends or have a
specified expiration date. They can persist even after the browser
is closed if they are persistent cookies.
E.g.
function outerFunction() {
let outerVariable = 'I am from the outer function';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
const closureExample = outerFunction();
closureExample(); // Outputs: "I am from the outer function"
Q28. What is hoisting in Javascript.
Ans: Hoisting is a behavior in JavaScript where variable and function
declarations are moved to the top of their containing scope during the
compilation phase.
E.g.
// Original function with multiple parameters
function add(x, y, z) {
return x + y + z;
}
console.log(result); // Outputs: 6
E.g.
// Select the target node
const targetNode = document.getElementById('target-element');
// Later, you can disconnect the observer when it's no longer needed
// observer.disconnect();
E.g.
function memoizedAdd() {
// Initialize a cache object
const cache = {};
console.log('Calculating result');
return result;
}
};
}