Untitled Document
Untitled Document
- Data privacy
# JavaScript Core Concepts - Function factories
- Partial application
## 1. Hoisting - Maintaining state in async operations
**Q: What is hoisting in JavaScript?**
A: Hoisting is JavaScript's default behavior of moving ## 3. Promises
declarations to the top of their scope during the **Q: What are Promises and how do they work?**
creation phase of the execution context. A: A Promise is an object representing the eventual
completion (or failure) of an asynchronous operation.
Example:
javascript States:
console.log(x); // undefined - Pending: Initial state
var x = 5; - Fulfilled: Operation completed successfully
- Rejected: Operation failed
// The above code is interpreted as:
var x; Example:
console.log(x); javascript
x = 5; const fetchData = () => {
return new Promise((resolve, reject) => {
// Async operation
Key points: if (success) {
- Only declarations are hoisted, not initializations resolve(data);
- Function declarations are hoisted completely } else {
- let and const are hoisted but not initialized (Temporal reject(error);
Dead Zone) }
});
## 2. Closure };
**Q: Explain closures in JavaScript**
A: A closure is the combination of a function bundled fetchData()
together with references to its surrounding state .then(data => console.log(data))
(lexical environment). It gives you access to an outer .catch(error => console.error(error));
function's scope from an inner function.
Use cases:
2. CSRF Protection - Complex calculations
3. Proper authentication - Preventing unnecessary re-renders
4. Secure data transmission - Performance optimization for expensive operations
5. Input validation
6. Dependencies audit ## 3. Features of React
Key features include:
## 10. Memory Leaks - Virtual DOM for efficient updates
**Q: How to prevent and detect memory leaks in - Component-based architecture
React?** - JSX syntax
A: Common sources and solutions: - Unidirectional data flow
- Rich ecosystem
1. Cleanup in useEffect - React Native for mobile development
javascript - Server-side rendering capabilities
useEffect(() => { - Strong community support
const subscription = subscribe(); - Developer tools and debugging
- Performance optimizations 4. componentDidMount()
## 8. Fragments in React
Benefits: Fragments let you group multiple children elements
- Familiar syntax for defining UI without adding extra nodes to the DOM.
- Full power of JavaScript
- Compile-time error checking return (
- Type safety when used with TypeScript <React.Fragment>
<ChildA />
## 5. What is DOM? <ChildB />
The Document Object Model (DOM) is a </React.Fragment>
programming interface for HTML and XML );
documents. It represents the page as a tree structure
where each node represents a part of the document // Short syntax
(elements, attributes, text). return (
<>
Key aspects: <ChildA />
- Hierarchical structure <ChildB />
- Platform/language-independent </>
- Dynamic manipulation );
- Event handling
State:
## 11. Package.json vs Package-lock.json - Managed within component
package.json: - Can be changed
- Project metadata and configuration - Asynchronous updates
- Dependencies with version ranges - Controlled by component
- Scripts definitions
- Project information Props:
- External data
package-lock.json: - Read-only
- Exact versions of dependencies - Passed from parent
- Ensures consistent installs - Controlled by parent
- Full dependency tree
- Generated and updated automatically ## 16. Props Drilling
Props drilling occurs when props are passed through
## 12. Client-side vs Server-side Rendering multiple intermediate components that don't need the
data but only pass it down.
Client-side Rendering (CSR):
- Initial HTML is minimal // Example of props drilling
- JavaScript loads and renders content function GrandParent({ data }) {
- Better for interactive applications return <Parent data={data} />;
- Faster subsequent navigation }
- Higher client-side resource usage
function Parent({ data }) {
Server-side Rendering (SSR): return <Child data={data} />;
- Full HTML delivered from server }
- Better SEO
- Faster initial page load function Child({ data }) {
- Lower client-side resource usage return <div>{data}</div>;
- Better for static content }
// Usage
## 33. Context API Usage Example function Counter() {
const { count, increment, decrement } =
useCounter(0);
// Create context return (
const UserContext = React.createContext(); <div>
<button onClick={decrement}>-</button>
// Provider component <span>{count}</span>
function UserProvider({ children }) { <button onClick={increment}>+</button>
const [user, setUser] = useState(null); </div>
);
return ( }
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider> ## 36. Class Lifecycle Methods vs useEffect
); Mapping of lifecycle methods to useEffect:
}
- componentDidMount: useEffect(() => {}, [])
// Consumer component - componentDidUpdate: useEffect(() => {})
function UserProfile() { - componentWillUnmount: useEffect(() => { return ()
const { user } = useContext(UserContext); => {} }, [])
return <div>{user.name}</div>;
} ## 37. Strict Mode
StrictMode is a development tool that:
- Identifies unsafe lifecycles
## 34. setState Callback Function - Warns about legacy API usage
The setState callback function is called after the state - Detects unexpected side effects
update is completed and the component is - Ensures reusable state
re-rendered.
<React.StrictMode>
this.setState({ count: this.state.count + 1 }, () => { <App />
</React.StrictMode> // Child
const Child = forwardRef((props, ref) => {
const [data, setData] = useState('Child data');
## 38. Child to Parent Data Communication
Methods to pass data from child to parent: useImperativeHandle(ref, () => ({
1. Callback functions getData: () => data
2. Refs }));
3. Context API
4. State management libraries return <div>{data}</div>;
5. Custom events });
useEffect(() => {
import PropTypes from 'prop-types'; const handleMouseMove = (event) => {
setPosition({ x: event.clientX, y: event.clientY });
function User({ name, age, email }) { };
return (
<div> window.addEventListener('mousemove',
<h1>{name}</h1> handleMouseMove);
<p>Age: {age}</p>
return () =>
window.removeEventListener('mousemove',
handleMouseMove); React.cloneElement(element, { className: 'new' });
}, []);
// Usage
cloneElement: <Routes>
- Clones and returns new element <Route
- Merges new props with existing path="/dashboard"
- Preserves ref and key element={
<ProtectedRoute> - Non-blocking I/O operations
<Dashboard /> - Key components:
</ProtectedRoute> * Memory Heap: Where memory allocation happens
} * Call Stack: Where code execution is tracked
/> * Event Queue (Callback Queue): Where callbacks
</Routes> wait to be executed
* Microtask Queue: Special queue for Promises
* Web APIs (in browsers) / C++ APIs (in Node.js):
## 54. React Router For async operations
React Router is a standard routing library for React:
### 2. Call Stack
The call stack is where function execution is tracked.
import { BrowserRouter, Routes, Route, Link } from It follows LIFO (Last In, First Out) principle.
'react-router-dom';
Example:
function App() { javascript
return ( function first() {
<BrowserRouter> second();
<nav> console.log('First');
<Link to="/">Home</Link> }
<Link to="/about">About</Link>
</nav> function second() {
console.log('Second');
<Routes> }
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} /> first();
<Route path="*" element={<NotFound />} />
</Routes> // Output:
</BrowserRouter> // Second
); // First
}
Promise.resolve()
.then(() => console.log('Promise 1')) // 3 ### 2. DOM Event Handling
.then(() => console.log('Promise 2')); // 4 javascript
document.addEventListener('click', () => {
setTimeout(() => { console.log('Click event fired');
console.log('Timeout 2'); // 6
}, 0); Promise.resolve().then(() => {
console.log('Promise in click handler');
console.log('End'); // 2 });
3. **Resource Management**
- Clear timeouts and intervals when no longer needed
- Remove event listeners when components unmount
- Be mindful of memory leaks in callbacks
## Debugging Tips