0% found this document useful (0 votes)
9 views16 pages

Untitled Document

The document covers essential JavaScript and React concepts, including hoisting, promises, closures, and execution context, as well as React-specific topics like hooks, memoization, and component lifecycle. It explains key features, advantages, and use cases for various programming techniques and patterns in both JavaScript and React. Additionally, it addresses best practices for performance optimization, security considerations, and state management in React applications.

Uploaded by

cloudiit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views16 pages

Untitled Document

The document covers essential JavaScript and React concepts, including hoisting, promises, closures, and execution context, as well as React-specific topics like hooks, memoization, and component lifecycle. It explains key features, advantages, and use cases for various programming techniques and patterns in both JavaScript and React. Additionally, it addresses best practices for performance optimization, security considerations, and state management in React applications.

Uploaded by

cloudiit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

​ Use cases:

​ - 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.

Example: ## 4. Function Currying


javascript **Q: What is function currying and what are its
function createCounter() { benefits?**
let count = 0; A: Currying is the process of transforming a function
return { that takes multiple arguments into a series of
increment: function() { functions that each take a single argument.
count++;
return count; Example:
}, javascript
getCount: function() { // Normal function
return count; function add(a, b, c) {
} return a + b + c;
}; }
}
// Curried version
const counter = createCounter(); const curriedAdd = a => b => c => a + b + c;
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2 console.log(curriedAdd(1)(2)(3)); // 6
Benefits: useEffect(() => {
- Partial application of functions document.title = `Count: ${count}`;
- Enhanced code reusability }, [count]);
- Better function composition
- More readable code in functional programming // useCallback
const memoizedCallback = useCallback(
## 5. Execution Context () => {
**Q: Explain execution context in JavaScript** doSomething(count);
A: An execution context is an environment where },
JavaScript code is executed. It consists of: [count]
);
1. Variable Environment
- var declarations // useMemo
- function declarations const memoizedValue = useMemo(
- arguments object () => computeExpensiveValue(count),
[count]
2. Lexical Environment );
- let and const declarations
- Reference to outer environment
Advantages:
3. This Binding - Reuse stateful logic
- Value of 'this' keyword - Cleaner code organization
- Better code composition
Types: - Avoid class complexity
- Global Execution Context
- Function Execution Context ## 3. Class vs Functional Components
- Eval Execution Context **Q: Compare class and functional components**
A:
# React Concepts
Class Components:
## 1. Reconciliation javascript
**Q: What is React's reconciliation process?** class Welcome extends React.Component {
A: Reconciliation is the process React uses to update constructor(props) {
the DOM efficiently. It compares the virtual DOM with super(props);
the actual DOM and makes minimal necessary this.state = { count: 0 };
changes. }

Key concepts: render() {


- Virtual DOM diffing return <h1>Hello, {this.props.name}</h1>;
- Key prop importance }
- Component lifecycle during updates }
- Batch updates

## 2. Hooks Functional Components:


**Q: Explain React Hooks and their advantages** javascript
A: Hooks are functions that allow you to use state and function Welcome(props) {
other React features in functional components. const [count, setCount] = useState(0);
return <h1>Hello, {props.name}</h1>;
Common hooks: }
javascript
// useState
const [count, setCount] = useState(0); Key differences:
- Syntax and boilerplate
// useEffect - State management
- Lifecycle methods vs hooks const EnhancedComponent =
- 'this' binding withLogging(MyComponent);
- Code organization
Use cases:
## 4. Memoization - Code reuse
**Q: How does memoization work in React?** - Adding additional props
A: Memoization in React prevents unnecessary - State or behavior abstraction
re-renders by caching component outputs and values. - Cross-cutting concerns

Tools: ## 6. Performance Optimization


1. React.memo **Q: How can you optimize React application
javascript performance?**
const MemoizedComponent = React.memo(function
MyComponent(props) { Key strategies:
return <div>{props.value}</div>; 1. Code Splitting
}); javascript
const MyComponent = React.lazy(() =>
import('./MyComponent'));
2. useMemo
javascript
const memoizedValue = useMemo(() => 2. Proper key usage in lists
computeExpensive(props.value), [props.value]); 3. Memoization techniques
4. Virtualization for long lists
5. Image optimization
3. useCallback 6. Bundle size optimization
javascript 7. Tree shaking
const memoizedCallback = useCallback(
() => { ## 7. React Router
doSomething(props.value); **Q: Explain React Router and its core concepts**
}, A: React Router is a standard library for routing in
[props.value] React applications.
);
Key concepts:
javascript
## 5. Higher-Order Components (HOC) import { BrowserRouter, Route, Switch } from
**Q: What are HOCs and their use cases?** 'react-router-dom';
A: HOCs are functions that take a component and
return a new enhanced component. function App() {
return (
Example: <BrowserRouter>
javascript <Switch>
function withLogging(WrappedComponent) { <Route exact path="/" component={Home}
return function WithLoggingComponent(props) { />
useEffect(() => { <Route path="/about" component={About}
console.log('Component mounted'); />
return () => console.log('Component <Route path="/users/:id" component={User}
unmounted'); />
}, []); </Switch>
</BrowserRouter>
return <WrappedComponent {...props} />; );
} }
}
Features:
- Dynamic routing
- Nested routes return () => subscription.unsubscribe();
- Route parameters }, []);
- Route guards
- History management
2. Event listener cleanup
## 8. Caching 3. Clearing intervals/timeouts
**Q: How can you implement caching in React 4. Proper unsubscribing from observables
applications?** 5. Cancelling network requests
A: Several caching strategies:
Tools for detection:
1. React Query - React DevTools
javascript - Chrome DevTools Memory tab
const { data, isLoading } = useQuery('todos', - Performance profiler
fetchTodos); # Comprehensive React Guide

2. Local Storage ## 1. What is React?


javascript React is a JavaScript library for building user
const [data, setData] = useState(() => { interfaces, developed and maintained by Facebook
const cached = localStorage.getItem('myData'); (now Meta). It allows developers to create large web
return cached ? JSON.parse(cached) : null; applications that can change data without reloading
}); the page. React's main features include:
- Component-based architecture
- Virtual DOM for efficient rendering
3. Memory cache using useMemo - Unidirectional data flow
4. Service Worker caching - JSX syntax
5. HTTP caching headers - Rich ecosystem and community

## 9. Security ## 2. What is useMemo?


**Q: What are the key security considerations in useMemo is a React hook that memoizes expensive
React?** computations to optimize performance. It returns a
memoized value that only changes when one of its
Best practices: dependencies changes.
1. XSS Prevention
javascript javascript
// Avoid dangerouslySetInnerHTML const memoizedValue = useMemo(() =>
const sanitizedHTML = computeExpensiveValue(a, b), [a, b]);
DOMPurify.sanitize(userInput);

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()

## 4. What is JSX? Updating:


JSX (JavaScript XML) is a syntax extension for 1. static getDerivedStateFromProps()
JavaScript, recommended by React. It allows you to 2. shouldComponentUpdate()
write HTML structures in the same file as your 3. render()
JavaScript code. 4. getSnapshotBeforeUpdate()
5. componentDidUpdate()
Example:
Unmounting:
const element = <h1>Hello, {name}</h1>; 1. componentWillUnmount()

## 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

## 6. What is Virtual DOM? ## 9. Props in React


Virtual DOM is a lightweight copy of the actual DOM Props (properties) are inputs that components receive
in memory. React uses it to improve performance by: from their parent. They are read-only and help make
1. Creating a virtual representation of UI components reusable.
2. When state changes, creating a new virtual DOM
3. Comparing new virtual DOM with previous version
(diffing) function Welcome(props) {
4. Only updating actual DOM where necessary return <h1>Hello, {props.name}</h1>;
}
Benefits:
- Improved performance // Usage
- Cross-platform compatibility <Welcome name="John" />
- Predictable state management
- Efficient updates
## 10. Synthetic Events in React
## 7. Component Lifecycle (Class Components) Synthetic events are React's cross-browser wrapper
Class component lifecycle methods: around the browser's native events. They:
- Pool events for performance
Mounting: - Have consistent behavior across browsers
1. constructor() - Follow W3C spec regardless of browser
2. static getDerivedStateFromProps()
3. render()
function handleClick(e) { - Can be any JavaScript value
e.preventDefault(); - Updated from parent component
console.log('Button clicked');
} ## 15. State vs Props

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 }

## 13. State in React ## 17. Avoiding Props Drilling


State is a built-in object that stores property values Solutions to avoid props drilling:
belonging to a component. When state changes, the 1. Context API
component re-renders. 2. Redux or other state management
3. Component composition
const [count, setCount] = useState(0); 4. Custom hooks
5. React Query for server state
// Class component
class Example extends React.Component { ## 18. Pure Components
state = { Pure components automatically implement
count: 0 shouldComponentUpdate with a shallow prop and
}; state comparison. Benefits:
} - Performance optimization
- Predictable behavior
## 14. Props - Automatic rendering optimization
Props are properties passed to components from their
parent: ## 19. Refs in React
- Read-only Refs provide a way to access DOM nodes or React
- Help create reusable components elements directly. Use cases:
- Managing focus console.log('Component mounted');
- Text selection }
- Media playback
- Animations render() {
- Third-party DOM libraries return <WrappedComponent {...this.props} />;
}
const inputRef = useRef(); };
// Later };
inputRef.current.focus();

## 23. Controlled vs Uncontrolled Components

## 20. Forward Ref Controlled Components:


forwardRef lets components forward refs they receive - Form data controlled by React state
to child components: - More predictable
- Immediate access to form data
const FancyButton = React.forwardRef((props, ref) => - Better validation control
(
<button ref={ref} className="fancy">
{props.children} function ControlledInput() {
</button> const [value, setValue] = useState('');
)); return <input value={value} onChange={e =>
setValue(e.target.value)} />;
}
## 21. Error Boundaries
Error boundaries are components that catch
JavaScript errors in child components, log errors, and Uncontrolled Components:
display fallback UI. - Form data handled by DOM
- Less code
- Better performance
class ErrorBoundary extends React.Component { - Use refs to access values
state = { hasError: false };

static getDerivedStateFromError(error) { function UncontrolledInput() {


return { hasError: true }; const inputRef = useRef();
} return <input ref={inputRef} />;
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>; ## 24. useCallback
} useCallback is a hook that returns a memoized
return this.props.children; version of a callback that only changes if
} dependencies change.
}

const memoizedCallback = useCallback(


## 22. Higher Order Components (HOC) () => {
HOCs are functions that take a component and return doSomething(a, b);
a new component with additional props or behavior. },
[a, b],
);
const withLogger = (WrappedComponent) => {
return class extends React.Component {
componentDidMount() { ## 25. useMemo vs useCallback
useMemo:
- Memoizes computed values function useWindowSize() {
- Returns memoized value const [size, setSize] = useState({ width: 0, height: 0
- Used for expensive calculations });

useCallback: useEffect(() => {


- Memoizes functions function updateSize() {
- Returns memoized function setSize({ width: window.innerWidth, height:
- Used for preventing unnecessary re-renders window.innerHeight });
}
## 26. Keys in React window.addEventListener('resize', updateSize);
Keys help React identify which items have changed, updateSize();
been added, or been removed in lists. return () => window.removeEventListener('resize',
updateSize);
}, []);
const items = list.map(item =>
<li key={item.id}>{item.text}</li> return size;
); }

Best practices: ## 30. useReducer Hook


- Use stable IDs useReducer is a hook for managing complex state
- Avoid index as key logic in React applications.
- Keys must be unique among siblings

## 27. Lazy Loading in React const [state, dispatch] = useReducer(reducer,


Lazy loading allows you to split your code into smaller initialState);
chunks and load them on demand.
// Reducer function
function reducer(state, action) {
const OtherComponent = React.lazy(() => switch (action.type) {
import('./OtherComponent')); case 'increment':
return {count: state.count + 1};
function MyComponent() { case 'decrement':
return ( return {count: state.count - 1};
<Suspense fallback={<Loading />}> default:
<OtherComponent /> throw new Error();
</Suspense> }
); }
}

## 31. Portals in React


## 28. Suspense in React Portals provide a way to render children into a DOM
Suspense lets components "wait" for something node that exists outside the parent component's
before rendering, such as: hierarchy.
- Code splitting
- Data fetching
- Image loading ReactDOM.createPortal(
- Other asynchronous operations children,
document.getElementById('modal-root')
## 29. Custom Hooks );
Custom hooks are JavaScript functions that use
React hooks and can be reused across components.
Use cases: console.log('State updated:', this.state.count);
- Modals });
- Tooltips
- Floating menus
- Widgets ## 35. Custom Counter Hook Example

## 32. Context in React


Context provides a way to pass data through the function useCounter(initialValue = 0) {
component tree without passing props manually at const [count, setCount] = useState(initialValue);
every level.
const increment = () => setCount(prev => prev + 1);
const decrement = () => setCount(prev => prev - 1);
const ThemeContext = React.createContext('light'); const reset = () => setCount(initialValue);

function App() { return {


return ( count,
<ThemeContext.Provider value="dark"> increment,
<ThemedButton /> decrement,
</ThemeContext.Provider> reset
); };
} }

// 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 });

## 39. Child to Parent Using Callbacks


## 41. React Application Optimization
Optimization techniques:
// Parent 1. Code splitting
function Parent() { 2. Lazy loading
const handleChildData = (data) => { 3. Memoization (useMemo, useCallback)
console.log('Data from child:', data); 4. Pure components
}; 5. Virtual list for long lists
6. Proper key usage
return <Child onDataSend={handleChildData} />; 7. Avoiding unnecessary renders
} 8. Bundle size optimization
9. Image optimization
// Child 10. Performance monitoring
function Child({ onDataSend }) {
return ( ## 42. Consuming REST API in React
<button onClick={() => onDataSend('Hello from
child!')}> function UserList() {
Send Data const [users, setUsers] = useState([]);
</button> const [loading, setLoading] = useState(true);
);
} useEffect(() => {
fetch('https://api.example.com/users')
.then(response => response.json())
## 40. Child to Parent Using useRef .then(data => {
setUsers(data);
// Parent setLoading(false);
function Parent() { });
const childRef = useRef(); }, []);

const getDataFromChild = () => { if (loading) return <div>Loading...</div>;


const data = childRef.current.getData();
console.log('Child data:', data); return (
}; <ul>
{users.map(user => (
return ( <li key={user.id}>{user.name}</li>
<> ))}
<Child ref={childRef} /> </ul>
<button onClick={getDataFromChild}>Get Child );
Data</button> }
</>
);
} ## 43. React Design Patterns
Common React design patterns:
<p>Email: {email}</p>
1. Container/Presentational Pattern </div>
);
// Container }
function UserListContainer() {
const [users, setUsers] = useState([]); User.propTypes = {
// Data fetching and business logic name: PropTypes.string.isRequired,
return <UserList users={users} />; age: PropTypes.number,
} email: PropTypes.string.isRequired,
friends: PropTypes.arrayOf(PropTypes.string),
// Presentational address: PropTypes.shape({
function UserList({ users }) { street: PropTypes.string,
return <ul>{users.map(user => city: PropTypes.string
<li>{user.name}</li>)}</ul>; })
} };

2. Compound Components Pattern ## 46. React Mixins


3. Render Props Pattern Mixins are a way to reuse code between components,
4. Higher-Order Components (HOC) but they are deprecated in modern React. Instead,
5. Custom Hooks Pattern use:
6. Provider Pattern - Custom Hooks
- Higher-Order Components
- Render Props
## 44. Context API vs Redux - Composition

Context API: ## 47. Common React Hooks


- Built into React Frequently used hooks:
- Simple setup 1. useState - State management
- Good for low-frequency updates 2. useEffect - Side effects
- Best for small-medium apps 3. useContext - Context consumption
- No middleware support 4. useRef - DOM references
- Limited dev tools 5. useMemo - Value memoization
6. useCallback - Function memoization
Redux: 7. useReducer - Complex state
- External library 8. useLayoutEffect - Synchronous effects
- More complex setup 9. Custom hooks - Reusable logic
- Better for frequent updates
- Best for large apps ## 48. Render Props
- Rich middleware ecosystem Render Props is a pattern where a component
- Excellent dev tools receives a function prop that returns a React element:

## 45. PropTypes in React


PropTypes provide runtime type checking for React function MouseTracker({ render }) {
props: const [position, setPosition] = useState({ x: 0, y: 0 });

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' });
}, []);

return render(position); ## 51. useState vs useReducer


}
Use useState when:
// Usage - Managing simple state
<MouseTracker - Few state updates
render={({ x, y }) => ( - Independent state items
<div>Mouse position: {x}, {y}</div> - Small applications
)}
/> Use useReducer when:
- Complex state logic
- Related state transitions
## 49. Types of Exports/Imports - Multiple state updates
- Need for state history
Named Exports/Imports:
## 52. flushSync in React
// Export flushSync forces React to flush pending work and
export const MyComponent = () => {}; update the DOM synchronously:
export const helper = () => {};

// Import import { flushSync } from 'react-dom';


import { MyComponent, helper } from
'./MyComponent'; function handleClick() {
flushSync(() => {
setCounter(c => c + 1);
Default Exports/Imports: });
// DOM is updated here
// Export }
export default MyComponent;

// Import ## 53. Protected Routes


import MyComponent from './MyComponent'; Protected Routes control access to certain routes
based on authentication:

## 50. createElement vs cloneElement


function ProtectedRoute({ children }) {
createElement: const { isAuthenticated } = useAuth();
- Creates new elements
- Takes type, props, and children if (!isAuthenticated) {
- Used by JSX internally return <Navigate to="/login" />;
}

React.createElement('div', { className: 'test' }, return children;


'Hello'); }

// 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
}

Stack execution order:


Key features: 1. first() is pushed to stack
- Declarative routing 2. second() is pushed to stack
- Nested routes 3. second() executes and pops
- Route parameters 4. first() continues, logs, and pops
- Navigation hooks
- History management ## Event Loop Process

# JavaScript Event Loop - Complete Guide ### 1. Macrotasks (Regular Tasks)


These include:
## Introduction - setTimeout
The JavaScript Event Loop is a fundamental - setInterval
mechanism that enables non-blocking (asynchronous) - setImmediate (Node.js)
operations despite JavaScript being single-threaded. - requestAnimationFrame
This guide covers everything you need to know about - I/O operations
the Event Loop, from basic concepts to advanced - UI rendering
patterns.
Example:
## Core Components javascript
console.log('Start');
### 1. JavaScript Runtime Environment setTimeout(() => console.log('Timeout'), 0);
- Single-threaded execution (one call stack) console.log('End');
// Promise 1
// Output: // Promise 2
// Start // Timeout 1
// End // Timeout 2
// Timeout

## Event Loop Steps in Detail


### 2. Microtasks 1. Execute all synchronous code in the call stack
These include: 2. Once call stack is empty, check microtask queue
- Promise callbacks 3. Execute ALL microtasks in queue
- process.nextTick (Node.js) 4. If there are new microtasks added while executing,
- queueMicrotask they also get executed
- MutationObserver 5. After microtask queue is empty, take ONE
macrotask from queue
Example: 6. Execute that macrotask
javascript 7. Return to step 2
console.log('Start'); 8. Continue this cycle
Promise.resolve().then(() => console.log('Promise'));
setTimeout(() => console.log('Timeout'), 0); ## Real-world Scenarios
console.log('End');
### 1. Handling API Calls
// Output: javascript
// Start async function fetchData() {
// End console.log('Start fetch'); // 1
// Promise
// Timeout try {
const response = await
fetch('https://api.example.com/data');
## Execution Priority console.log('Response received'); // 3
1. All synchronous code (in Call Stack)
2. All microtasks (Promise callbacks) const data = await response.json();
3. One macrotask at a time console.log('Data processed'); // 4
} catch (error) {
## Comprehensive Example console.error('Error:', error);
javascript }
console.log('Start'); // 1 }

setTimeout(() => { console.log('Before fetch'); // 2


console.log('Timeout 1'); // 5 fetchData();
}, 0); console.log('After fetch call'); // 5

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 });

// Output: setTimeout(() => {


// Start console.log('Timeout in click handler');
// End }, 0);
}); ### 2. Proper Error Handling
javascript
Promise.resolve()
### 3. Multiple Promises .then(() => {
javascript throw new Error('Something went wrong');
Promise.resolve() })
.then(() => { .catch(error => {
console.log('Promise 1'); console.error('Caught:', error);
return Promise.resolve(); })
}) .finally(() => {
.then(() => { console.log('Cleanup operations');
console.log('Promise 2'); });
return Promise.resolve();
})
.then(() => { ### 3. Managing Multiple Async Operations
console.log('Promise 3'); javascript
}); // Using Promise.all for parallel execution
async function fetchMultipleData() {
setTimeout(() => { try {
console.log('Timeout 1'); const results = await Promise.all([
}, 0); fetch('url1'),
fetch('url2'),
// Output: fetch('url3')
// Promise 1 ]);
// Promise 2 console.log('All requests completed');
// Promise 3 } catch (error) {
// Timeout 1 console.error('One or more requests failed:',
error);
}
## Best Practices }

### 1. Avoiding Long-running Tasks // Using Promise.race for timeout


javascript function fetchWithTimeout(url, timeout) {
// Bad practice - blocks the event loop return Promise.race([
function heavyOperation() { fetch(url),
for(let i = 0; i < 1000000; i++) { new Promise((_, reject) =>
// Heavy computation setTimeout(() => reject(new Error('Timeout')),
} timeout)
} )
]);
// Good practice - chunks the operation }
function chunkedOperation(start, end, chunk) {
setTimeout(() => {
for(let i = start; i < Math.min(end, start + chunk); ## Common Gotchas and Solutions
i++) {
// Process chunk ### 1. Callback Hell
} javascript
if (start + chunk < end) { // Bad practice
chunkedOperation(start + chunk, end, chunk); fetchData(function(data) {
} processData(data, function(processed) {
}, 0); saveData(processed, function(result) {
} console.log('Done');
});
});
});
setTimeout(() => {
// Good practice - using async/await console.log('Timeout');
async function handleData() { }, 0);
try {
const data = await fetchData(); Promise.resolve().then(() => {
const processed = await processData(data); console.log('Promise');
const result = await saveData(processed); });
console.log('Done');
} catch (error) { console.log('Sync 2');
console.error('Error:', error); }
}
}
2. **Chrome DevTools**
- Use Performance tab to visualize task timing
### 2. Race Conditions - Use async stack traces in Console
javascript - Monitor long tasks in Performance insights
// Potential race condition
let data; ## Event Loop in Different Environments
fetch('url').then(response => {
data = response; ### Browser
}); - Has Web APIs
console.log(data); // undefined - Includes rendering tasks
- Handles user interactions
// Better approach - Manages DOM updates
async function getData() {
const data = await fetch('url'); ### Node.js
console.log(data); - Has C++ APIs
} - Includes additional queues (check, close)
- process.nextTick has highest priority
## Performance Considerations - No rendering concerns

1. **Microtask Queue Management** ## Conclusion


- Don't create infinite loops of microtasks Understanding the Event Loop is crucial for:
- Be cautious with recursive Promise chains - Writing performant JavaScript code
- Consider using macrotasks for CPU-intensive - Handling asynchronous operations correctly
operations - Debugging timing issues
- Managing application state
2. **Task Scheduling** - Optimizing application responsiveness
- Use requestAnimationFrame for animations
- Use requestIdleCallback for non-critical tasks
- Break up long tasks into smaller chunks

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

1. **Visualizing the Event Loop**


javascript
function debugEventLoop() {
console.log('Sync 1');

You might also like