Top 10 Advanced JS Interview QnA
Below are 10 advanced JavaScript interview questions along with detailed explanations and examples:
1. Explain Closures in JavaScript. Provide an Example.
Answer: When a function is created within another function, it can access variables from the enclosing environment, even after the outer function has finished executing. This "remembering" of variables from the outer scope is what creates a closure.
Example:
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log('Outer Variable:', outerVariable);
console.log('Inner Variable:', innerVariable);
};
}
const newFunction = outerFunction('outside');
newFunction('inside'); // Outer Variable: outside, Inner Variable: inside
In this example, innerFunction
forms a closure. It retains access to outerVariable
even after outerFunction
has finished executing.
2. What is the Event Loop in JavaScript? How does it work?
Answer: The event loop is a mechanism that allows JavaScript to perform non-blocking operations by offloading operations to the system kernel whenever possible.
Example:
console.log('Start');
setTimeout(() => {
console.log('Timeout callback');
}, 0);
Promise.resolve().then(() => {
console.log('Promise callback');
});
console.log('End');
Output:
Start
End
Promise callback
Timeout callback
In this example, setTimeout
and Promise
callbacks are handled by the event loop. The Promise
callback is executed before the setTimeout
callback due to microtask queue prioritization.
3. Describe Prototypal Inheritance. How does it differ from Classical Inheritance?
Answer: Prototypal inheritance is a feature in JavaScript where objects inherit properties and methods from other objects via a prototype chain.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person1 = new Person('Alice');
person1.sayHello(); // Hello, my name is Alice
In classical inheritance, classes inherit from other classes. Prototypal inheritance, on the other hand, is based on prototypes (objects) and is more flexible and dynamic.
4. What are Promises in JavaScript? How do you use them?
Answer: Promises are used to handle asynchronous operations in JavaScript. They represent a value that may be available now, in the future, or never.
Example:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Success!');
}, 1000);
});
myPromise.then((value) => {
console.log(value); // Success!
}).catch((error) => {
console.error(error);
});
In this example, myPromise
resolves after 1 second, and the .then
method handles the resolved value.
5. Explain Async/Await. How is it different from Promises?
Answer: async
/await
is syntactic sugar built on top of Promises, making asynchronous code easier to write and read.
Example:
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function asyncFunction() {
console.log('Start');
await delay(1000);
console.log('End');
}
asyncFunction();
In this example, await
pauses the execution of asyncFunction
until the Promise returned by delay
resolves.
6. What is the difference between ==
and ===
in JavaScript?
Answer: ==
is the equality operator that performs type coercion, while ===
is the strict equality operator that checks for both value and type.
Example:
console.log(5 == '5'); // true
console.log(5 === '5'); // false
In this example, 5 == '5'
is true because of type coercion, whereas 5 === '5'
is false because the types are different.
7. Explain the concept of this
in JavaScript. How is it determined?
Answer: this
refers to the object context in which a function is executed. Its value is determined by how a function is called.
Example:
const person = {
name: 'Alice',
sayHello: function() {
console.log(this.name);
}
};
person.sayHello(); // Alice
const sayHello = person.sayHello;
sayHello(); // undefined (or global object in non-strict mode)
In the first call, this
refers to person
object. In the second call, this
refers to the global object (or undefined
in strict mode).
8. What is Debouncing in JavaScript? Provide an Example.
Answer: Debouncing is a technique to limit the rate at which a function is executed. It ensures a function is not called too often.
Example:
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
window.addEventListener('resize', debounce(() => {
console.log('Resize event!');
}, 200));
In this example, the resize
event listener will log to the console at most once every 200 milliseconds, regardless of how frequently the resize
event is fired.
9. Describe the call
, apply
, and bind
methods. Provide examples.
Answer: call
, apply
, and bind
are methods to explicitly set the value of this
for a function.
Example:
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'Alice' };
greet.call(person, 'Hello', '!'); // Hello, Alice!
greet.apply(person, ['Hi', '?']); // Hi, Alice?
const boundGreet = greet.bind(person, 'Hey');
boundGreet('.'); // Hey, Alice.
call
invokes the function immediately with arguments passed individually.apply
invokes the function immediately with arguments passed as an array.bind
returns a new function with a boundthis
and preset arguments.
10. What are Generators in JavaScript? How do they work?
Answer: Generators are functions that can be paused and resumed, producing a sequence of values using the yield
keyword.
Example:
function* generatorFunction() {
yield 'First';
yield 'Second';
yield 'Third';
}
const generator = generatorFunction();
console.log(generator.next().value); // First
console.log(generator.next().value); // Second
console.log(generator.next().value); // Third
In this example, the generator function generatorFunction
produces values one at a time, pausing after each yield
statement until the next call to next
.
These questions and answers should give you a solid foundation for tackling advanced JavaScript topics in an interview setting.
Read in more details(Advanced JavaScript Concepts: 2024)
=============================+ Thank You !!!+==============================
Note: Don't forget to follow and give 50 claps.π π π