-
Notifications
You must be signed in to change notification settings - Fork 0
Quick Read (Interview Question)
Certainly! Let's go through each of these concepts with explanations and example programs.
A closure is a function that retains access to its lexical scope even when the function is executed outside that scope.
Example:
function makeCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3Debouncing is a technique to limit the rate at which a function is executed. It ensures that a function is only called once after a certain amount of time has passed since the last time it was invoked.
Example:
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
const log = debounce(() => console.log('Function executed!'), 300);
window.addEventListener('resize', log);A promise is an object representing the eventual completion or failure of an asynchronous operation.
Example:
function asyncTask() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Task completed');
}, 1000);
});
}
asyncTask().then(result => console.log(result)).catch(error => console.error(error));Example:
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope.
Example:
console.log(myVar); // undefined
var myVar = 5;call and bind are methods to set the this context for a function.
Example:
const obj = { name: 'Alice' };
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
}
greet.call(obj, 'Hello'); // Hello, Alice
const boundGreet = greet.bind(obj);
boundGreet('Hi'); // Hi, AliceThe 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');
}, 0);
console.log('End');Arrow functions provide a concise syntax and do not have their own this, arguments, super, or new.target.
Example:
// Normal Function
function add(a, b) {
return a + b;
}
// Arrow Function
const add = (a, b) => a + b;Differences:
- Syntax: Arrow functions are shorter.
-
thisbinding: Arrow functions do not have their ownthis.
Interceptors are used in libraries like Axios to modify requests or responses before they are handled by then or catch.
Example with Axios:
axios.interceptors.request.use(request => {
request.headers['Authorization'] = 'Bearer token';
return request;
});State Management refers to the management of the state of an application.
useEffect is a React hook for performing side effects in function components.
Example:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}Creating a complete CRUD application involves several steps. Here is a simplified version:
Example:
import React, { useState } from 'react';
function App() {
const [items, setItems] = useState([]);
const [input, setInput] = useState('');
const addItem = () => {
setItems([...items, input]);
setInput('');
};
const deleteItem = index => {
setItems(items.filter((item, i) => i !== index));
};
return (
<div>
<input value={input} onChange={e => setInput(e.target.value)} />
<button onClick={addItem}>Add</button>
<ul>
{items.map((item, index) => (
<li key={index}>
{item} <button onClick={() => deleteItem(index)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
export default App;Redux is a state management library for JavaScript applications. Middleware is software that provides common services and capabilities to applications outside of what's offered by the operating system.
Example with Redux Middleware (Thunk):
// store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
export default store;useContext is a React hook that allows you to use the context API to share values between components without passing props manually.
Example:
import React, { useContext } from 'react';
const MyContext = React.createContext();
function ChildComponent() {
const value = useContext(MyContext);
return <div>{value}</div>;
}
function ParentComponent() {
return (
<MyContext.Provider value="Hello from context">
<ChildComponent />
</MyContext.Provider>
);
}These explanations and examples should help you understand the concepts and their implementations in JavaScript and React. If you need more details or specific examples, feel free to ask!