Advertisement
satishfrontenddev5

Untitled

Feb 18th, 2024 (edited)
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Sure, here are the requested code snippets and practice questions:
  2.  
  3. ### Code Snippets:
  4. directly paste in dev-tool console:
  5.  
  6. 1. **Promises with setTimeout:**
  7.    ```javascript
  8.    const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
  9.    
  10.    console.log('Start');
  11.    delay(2000).then(() => console.log('After 2 seconds'));
  12.    console.log('End');
  13.    ```
  14.  
  15. 2. **Hoisting Example:**
  16.    ```javascript
  17.    console.log(x); // undefined
  18.    var x = 5;
  19.    console.log(x); // 5
  20.    ```
  21.  
  22. 3. **React Hooks (Counter):**
  23.    ```javascript
  24.    import React, { useState } from 'react';
  25.  
  26.    const Counter = () => {
  27.      const [count, setCount] = useState(0);
  28.  
  29.      const increment = () => setCount(count + 1);
  30.      const decrement = () => setCount(count - 1);
  31.  
  32.      return (
  33.        <div>
  34.          <p>Count: {count}</p>
  35.          <button onClick={increment}>Increment</button>
  36.          <button onClick={decrement}>Decrement</button>
  37.        </div>
  38.      );
  39.    };
  40.  
  41.    export default Counter;
  42.    ```
  43.  
  44. ### Practice Questions:
  45.  
  46. #### Promises with setTimeout:
  47. 1. **Question:** Explain how the above code snippet works.
  48.    **Answer:**
  49.    - The `delay` function returns a Promise that resolves after a specified time (in milliseconds).
  50.    - The `console.log('Start')` is executed immediately.
  51.    - Then, the `delay(2000)` Promise is invoked, which schedules the next line (`console.log('End')`) after a 2-second delay.
  52.    - Finally, `console.log('End')` is executed, and after 2 seconds, the `console.log('After 2 seconds')` is executed.
  53.  
  54. 2. **Question:** What would happen if we change the delay time in the `delay` function to 0 milliseconds?
  55.    **Answer:** The behavior would remain the same because Promises with `setTimeout` are asynchronous, so even with 0 milliseconds, the next line would still be scheduled to execute after the current execution context finishes.
  56.  
  57. 3. **Question:** How would you modify the code to execute a function after both `console.log` statements?
  58.    **Answer:** You can use Promise chaining or `async/await` syntax to achieve this. For example:
  59.    ```javascript
  60.    delay(2000)
  61.      .then(() => {
  62.        console.log('After 2 seconds');
  63.        return delay(2000);
  64.      })
  65.      .then(() => console.log('After another 2 seconds'));
  66.    ```
  67.  
  68. 4. **Question:** Is there any difference between using `setTimeout` directly and using it within a Promise?
  69.    **Answer:** Yes, using `setTimeout` directly is synchronous, meaning the code after it will execute immediately, whereas using it within a Promise allows for better control over asynchronous behavior and chaining of actions.
  70.  
  71. 5. **Question:** How would you handle errors in the Promise returned by the `delay` function?
  72.    **Answer:** You can add a `.catch` method to the Promise chain to handle any errors that occur during execution.
  73.  
  74. #### Hoisting:
  75. 1. **Question:** Explain the output of the hoisting example provided.
  76.    **Answer:**
  77.    - Before variable `x` is declared and initialized, its value is `undefined` due to hoisting.
  78.    - Therefore, the first `console.log(x)` prints `undefined`.
  79.    - After `x` is assigned the value `5`, the second `console.log(x)` prints `5`.
  80.  
  81. 2. **Question:** Does hoisting apply to both `let` and `const` declarations?
  82.    **Answer:** No, `let` and `const` declarations are hoisted, but they are not initialized, so trying to access them before declaration results in a ReferenceError.
  83.  
  84. 3. **Question:** What is the difference between function hoisting and variable hoisting?
  85.    **Answer:** Function declarations are hoisted along with their definitions, meaning you can call a function before it's declared. Variable declarations are hoisted, but only the variable name is hoisted, not its value or assignment.
  86.  
  87. 4. **Question:** How does hoisting impact the scope of variables and functions?
  88.   **Answer:** Hoisting can lead to unexpected behavior if not understood properly, especially when variables and functions are declared inside different scopes. It's important to understand that hoisting applies differently to variables and functions.
  89.  
  90. 5. **Question:** Is it recommended to rely on hoisting in JavaScript code?
  91.    **Answer:** It's generally not recommended to rely on hoisting for code readability and maintainability. It's better to declare variables and functions at the beginning of their scope to avoid confusion.
  92.  
  93. #### React Hooks (Counter):
  94. 1. **Question:** Explain how the `useState` hook works in the provided `Counter` component.
  95.    **Answer:**
  96.    - `useState` is a React hook used to add state variables to functional components.
  97.    - In the `Counter` component, `const [count, setCount] = useState(0)` declares a state variable `count` initialized to 0 and a function `setCount` to update the `count` state.
  98.    - The `useState` hook returns an array with the current state value (`count`) and a function (`setCount`) to update the state.
  99.  
  100. 2. **Question:** How would you modify the `Counter` component to start the count from 10 instead of 0?
  101.    **Answer:** Change `useState(0)` to `useState(10)` to initialize the `count` state variable with a value of 10.
  102.  
  103. 3. **Question:** What is the purpose of the `increment` and `decrement` functions in the `Counter` component?
  104.    **Answer:**
  105.    - The `increment` function increments the `count` state variable by 1 when called.
  106.    - The `decrement` function decrements the `count` state variable by 1 when called.
  107.  
  108. 4. **Question:** How would you add a button to reset the counter to 0 in the `Counter` component?
  109.    **Answer:** Add a button element with an
  110.  
  111.  `onClick` handler that calls a `resetCount` function, which sets the `count` state variable to 0.
  112.  
  113. 5. **Question:** Can you explain the purpose of the `useState` hook in React functional components?
  114.    **Answer:** The `useState` hook allows functional components to have state variables, enabling them to store and update component state without using class-based components. It simplifies state management in functional components by providing a way to declare and initialize state variables within the component's function body.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement