Frontend Developer Interview Questions and Answers
Experienced / Expert level questions & answers
Ques 1. Explain the concept of closures in JavaScript.
Closures allow a function to access variables from its outer (enclosing) scope even after the outer function has finished executing. They help in creating private variables and methods.
Example:
```javascript
function outer() {
let x = 10;
function inner() {
console.log(x);
}
return inner;
}
const closureExample = outer();
closureExample(); // Outputs 10
```
Ques 2. How does CSS specificity work?
Specificity is a set of rules that determines which style declarations are applied to an element. It is based on the importance, specificity, and source order of CSS rules.
Example:
```css
#id-selector {
color: red; /* higher specificity */
}
.class-selector {
color: blue;
}
```
Ques 3. Explain the concept of event delegation in JavaScript.
Event delegation involves attaching a single event listener to a common ancestor rather than individual elements. It leverages event bubbling to handle events on multiple child elements.
Example:
```javascript
// HTML:
- Item 1
- Item 2
const list = document.getElementById('myList');
list.addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
console.log('Clicked on:', event.target.textContent);
}
});
```
Ques 4. What is the Virtual DOM, and how does it improve performance in frameworks like React?
The Virtual DOM is a lightweight copy of the actual DOM. React uses it to optimize updates by comparing the virtual DOM with the real DOM and making minimal changes. This reduces the number of manipulations needed on the actual DOM, improving performance.
Ques 5. What is a closure in the context of JavaScript's event handling?
In the context of event handling, a closure allows a function to retain access to variables in its lexical scope even after the outer function has finished executing. This is often used to maintain state across multiple event callbacks.
Example:
```javascript
function createCounter() {
let count = 0;
return function() {
console.log(count++);
};
}
const counter = createCounter();
counter(); // Outputs: 0
counter(); // Outputs: 1
```
Ques 6. Explain the 'callback hell' phenomenon in JavaScript and how to mitigate it.
'Callback hell' occurs when multiple nested callbacks make the code hard to read and maintain. Mitigate it by using named functions, promises, or async/await syntax to improve code readability and maintainability.
Most helpful rated by users: