<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: nikhilkalariya</title>
    <description>The latest articles on DEV Community by nikhilkalariya (@nikhilkalariya).</description>
    <link>https://dev.to/nikhilkalariya</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F936346%2Ff3b8fcf9-f711-4699-9d54-218e0c2fb36e.png</url>
      <title>DEV Community: nikhilkalariya</title>
      <link>https://dev.to/nikhilkalariya</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/nikhilkalariya"/>
    <language>en</language>
    <item>
      <title>React Js hooks</title>
      <dc:creator>nikhilkalariya</dc:creator>
      <pubDate>Tue, 30 Jul 2024 13:16:46 +0000</pubDate>
      <link>https://dev.to/nikhilkalariya/react-js-hooks-366c</link>
      <guid>https://dev.to/nikhilkalariya/react-js-hooks-366c</guid>
      <description>&lt;p&gt;&lt;strong&gt;1. useState Hook&lt;br&gt;
Example: Counter Component&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';

const Counter = () =&amp;gt; {
  const [count, setCount] = useState(0);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Count: {count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setCount(count + 1)}&amp;gt;Increment&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Counter;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. useEffect Hook&lt;br&gt;
Example: Fetch Data from an API&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
import React, { useState, useEffect } from 'react';

const DataFetcher = () =&amp;gt; {
  const [data, setData] = useState([]);

  useEffect(() =&amp;gt; {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response =&amp;gt; response.json())
      .then(data =&amp;gt; setData(data));
  }, []);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;Fetched Data&amp;lt;/h1&amp;gt;
      &amp;lt;ul&amp;gt;
        {data.map(item =&amp;gt; (
          &amp;lt;li key={item.id}&amp;gt;{item.title}&amp;lt;/li&amp;gt;
        ))}
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default DataFetcher;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. useContext Hook&lt;br&gt;
Example: Theme Context&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');

const ThemedComponent = () =&amp;gt; {
  const theme = useContext(ThemeContext);
  return &amp;lt;div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}&amp;gt;Themed Component&amp;lt;/div&amp;gt;;
};

const App = () =&amp;gt; {
  return (
    &amp;lt;ThemeContext.Provider value="dark"&amp;gt;
      &amp;lt;ThemedComponent /&amp;gt;
    &amp;lt;/ThemeContext.Provider&amp;gt;
  );
};

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. useReducer Hook&lt;br&gt;
Example: Counter with Reducer&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
import React, { useReducer } from 'react';

const initialState = { count: 0 };

const reducer = (state, action) =&amp;gt; {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
};

const CounterWithReducer = () =&amp;gt; {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Count: {state.count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch({ type: 'increment' })}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch({ type: 'decrement' })}&amp;gt;Decrement&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default CounterWithReducer;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. useCallback Hook&lt;br&gt;
Example: Memoized Callback&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
import React, { useState, useCallback } from 'react';

const Button = React.memo(({ onClick }) =&amp;gt; {
  console.log('Button rendered');
  return &amp;lt;button onClick={onClick}&amp;gt;Click me&amp;lt;/button&amp;gt;;
});

const App = () =&amp;gt; {
  const [count, setCount] = useState(0);
  const handleClick = useCallback(() =&amp;gt; {
    setCount(prevCount =&amp;gt; prevCount + 1);
  }, []);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Count: {count}&amp;lt;/p&amp;gt;
      &amp;lt;Button onClick={handleClick} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6. useMemo Hook&lt;br&gt;
Example: Memoized Value&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState, useMemo } from 'react';

const ExpensiveCalculation = ({ count }) =&amp;gt; {
  const calculatedValue = useMemo(() =&amp;gt; {
    console.log('Calculating...');
    return count * 2;
  }, [count]);

  return &amp;lt;div&amp;gt;Calculated Value: {calculatedValue}&amp;lt;/div&amp;gt;;
};

const App = () =&amp;gt; {
  const [count, setCount] = useState(0);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setCount(count + 1)}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;ExpensiveCalculation count={count} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;7. useRef Hook&lt;br&gt;
Example: Focus Input&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useRef } from 'react';

const FocusInput = () =&amp;gt; {
  const inputRef = useRef(null);

  const handleClick = () =&amp;gt; {
    inputRef.current.focus();
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;input ref={inputRef} type="text" /&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Focus Input&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default FocusInput;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;8. useLayoutEffect Hook&lt;br&gt;
Example: Measure DOM Element&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState, useLayoutEffect, useRef } from 'react';

const MeasureComponent = () =&amp;gt; {
  const [width, setWidth] = useState(0);
  const divRef = useRef(null);

  useLayoutEffect(() =&amp;gt; {
    setWidth(divRef.current.offsetWidth);
  }, []);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;div ref={divRef} style={{ width: '50%' }}&amp;gt;Measured Div&amp;lt;/div&amp;gt;
      &amp;lt;p&amp;gt;Width: {width}px&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default MeasureComponent;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;9. useImperativeHandle Hook&lt;br&gt;
Example: Custom Input with Forwarded Ref&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useRef, useImperativeHandle, forwardRef } from 'react';

const CustomInput = forwardRef((props, ref) =&amp;gt; {
  const inputRef = useRef(null);

  useImperativeHandle(ref, () =&amp;gt; ({
    focus: () =&amp;gt; {
      inputRef.current.focus();
    }
  }));

  return &amp;lt;input ref={inputRef} type="text" /&amp;gt;;
});

const App = () =&amp;gt; {
  const inputRef = useRef(null);

  const handleClick = () =&amp;gt; {
    inputRef.current.focus();
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;CustomInput ref={inputRef} /&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Focus Input&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;10. useDebugValue Hook&lt;br&gt;
Example: Custom Hook with Debug Value&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState, useEffect, useDebugValue } from 'react';

const useCount = (initialValue) =&amp;gt; {
  const [count, setCount] = useState(initialValue);

  useEffect(() =&amp;gt; {
    const interval = setInterval(() =&amp;gt; {
      setCount(prevCount =&amp;gt; prevCount + 1);
    }, 1000);
    return () =&amp;gt; clearInterval(interval);
  }, []);

  useDebugValue(count &amp;gt; 5 ? 'High' : 'Low');

  return count;
};

const App = () =&amp;gt; {
  const count = useCount(0);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Count: {count}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Palindrome Number in Javascript</title>
      <dc:creator>nikhilkalariya</dc:creator>
      <pubDate>Sun, 21 Jul 2024 10:47:07 +0000</pubDate>
      <link>https://dev.to/nikhilkalariya/palindrome-number-in-javascript-1ejo</link>
      <guid>https://dev.to/nikhilkalariya/palindrome-number-in-javascript-1ejo</guid>
      <description>&lt;p&gt;&lt;strong&gt;Method 1: String Conversion and Reversal&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function isPalindrome(number) {
    const str = number.toString();
    const reversedStr = str.split('').reverse().join('');
    return str === reversedStr;
}

// Example usage
console.log(isPalindrome(121)); // true
console.log(isPalindrome(123)); // false
console.log(isPalindrome(1331)); // true

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Method 2: Using a Loop&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function isPalindrome(number) {
    const str = number.toString();
    const len = str.length;

    for (let i = 0; i &amp;lt; len / 2; i++) {
        if (str[i] !== str[len - 1 - i]) {
            return false;
        }
    }
    return true;
}

// Example usage
console.log(isPalindrome(121)); // true
console.log(isPalindrome(123)); // false
console.log(isPalindrome(1331)); // true

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Method 3: Mathematical Approach&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;This approach avoids string conversion and operates directly on the number.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function isPalindrome(number) {
    if (number &amp;lt; 0) return false; // Negative numbers are not palindromes
    let reversed = 0;
    let original = number;

    while (original &amp;gt; 0) {
        const digit = original % 10;
        reversed = reversed * 10 + digit;
        original = Math.floor(original / 10);
    }

    return number === reversed;
}

// Example usage
console.log(isPalindrome(121)); // true
console.log(isPalindrome(123)); // false
console.log(isPalindrome(1331)); // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Method 4: Using Recursion&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function isPalindromeHelper(str, start, end) {
    if (start &amp;gt;= end) return true;
    if (str[start] !== str[end]) return false;
    return isPalindromeHelper(str, start + 1, end - 1);
}

function isPalindrome(number) {
    const str = number.toString();
    return isPalindromeHelper(str, 0, str.length - 1);
}

// Example usage
console.log(isPalindrome(121)); // true
console.log(isPalindrome(123)); // false
console.log(isPalindrome(1331)); // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Method 5: Using Regular Expressions&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function isPalindrome(number) {
    const str = number.toString();
    const reversedStr = str.replace(/[\W_]/g, '').split('').reverse().join('');
    return str === reversedStr;
}

// Example usage
console.log(isPalindrome(121)); // true
console.log(isPalindrome(123)); // false
console.log(isPalindrome(1331)); // true

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>JavaScript Array Coding question</title>
      <dc:creator>nikhilkalariya</dc:creator>
      <pubDate>Sat, 20 Jul 2024 06:41:01 +0000</pubDate>
      <link>https://dev.to/nikhilkalariya/javascript-array-coding-question-2827</link>
      <guid>https://dev.to/nikhilkalariya/javascript-array-coding-question-2827</guid>
      <description>&lt;p&gt;&lt;strong&gt;Finding the Missing Number in an Array from 1 to 100:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findMissingNumber(nums) {
    const n = 100;
    const expectedSum = (n * (n + 1)) / 2;
    const actualSum = nums.reduce((acc, num) =&amp;gt; acc + num, 0);
    return expectedSum - actualSum;
}

console.log(findMissingNumber([...Array(100).keys()].map(n =&amp;gt; n + 1).filter(n =&amp;gt; n !== 50))); // Example where 50 is missing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Duplicate Number in an Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function findDuplicate(nums) {
    const seen = new Set();
    for (const num of nums) {
        if (seen.has(num)) {
            return num;
        }
        seen.add(num);
    }
    return -1; // If no duplicate found
}

console.log(findDuplicate([1, 2, 3, 4, 4])); // Example with duplicate 4

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Largest and Smallest Number in an Unsorted Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findMinMax(nums) {
    let min = nums[0];
    let max = nums[0];
    for (const num of nums) {
        if (num &amp;lt; min) min = num;
        if (num &amp;gt; max) max = num;
    }
    return { min, max };
}

console.log(findMinMax([3, 5, 1, 2, 4])); // Example output: { min: 1, max: 5 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding All Pairs of an Integer Array Whose Sum Equals a Given Number:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findPairsWithSum(nums, target) {
    const pairs = [];
    const seen = new Set();
    for (const num of nums) {
        const complement = target - num;
        if (seen.has(complement)) {
            pairs.push([complement, num]);
        }
        seen.add(num);
    }
    return pairs;
}

console.log(findPairsWithSum([1, 2, 3, 4, 3], 6)); // Example output: [[3, 3], [2, 4]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding Duplicate Numbers in an Array if It Contains Multiple Duplicates&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findDuplicates(nums) {
    const seen = new Set();
    const duplicates = new Set();
    for (const num of nums) {
        if (seen.has(num)) {
            duplicates.add(num);
        }
        seen.add(num);
    }
    return Array.from(duplicates);
}

console.log(findDuplicates([1, 2, 3, 4, 3, 2])); // Example output: [2, 3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Starting and Ending Position of a Given Value in a Sorted Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

function searchRotatedArray(nums, target) {
    let left = 0, right = nums.length - 1;
    while (left &amp;lt;= right) {
        const mid = Math.floor((left + right) / 2);
        if (nums[mid] === target) return mid;
        if (nums[left] &amp;lt;= nums[mid]) {
            if (nums[left] &amp;lt;= target &amp;amp;&amp;amp; target &amp;lt; nums[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        } else {
            if (nums[mid] &amp;lt; target &amp;amp;&amp;amp; target &amp;lt;= nums[right]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
    }
    return -1;
}

console.log(searchRotatedArray([4, 5, 6, 7, 0, 1, 2], 0)); // Example output: 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Length of the Longest Consecutive Elements Sequence in an Unsorted Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function longestConsecutive(nums) {
    const numSet = new Set(nums);
    let longestStreak = 0;
    for (const num of nums) {
        if (!numSet.has(num - 1)) {
            let currentNum = num;
            let currentStreak = 1;
            while (numSet.has(currentNum + 1)) {
                currentNum += 1;
                currentStreak += 1;
            }
            longestStreak = Math.max(longestStreak, currentStreak);
        }
    }
    return longestStreak;
}

console.log(longestConsecutive([100, 4, 200, 1, 3, 2])); // Example output: 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Sorting an Integer Array In-Place Using the Quicksort Algorithm:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// javascript
function quicksort(arr, left = 0, right = arr.length - 1) {
    if (left &amp;gt;= right) return;
    const pivot = arr[Math.floor((left + right) / 2)];
    const index = partition(arr, left, right, pivot);
    quicksort(arr, left, index - 1);
    quicksort(arr, index, right);
}

function partition(arr, left, right, pivot) {
    while (left &amp;lt;= right) {
        while (arr[left] &amp;lt; pivot) left++;
        while (arr[right] &amp;gt; pivot) right--;
        if (left &amp;lt;= right) {
            [arr[left], arr[right]] = [arr[right], arr[left]];
            left++;
            right--;
        }
    }
    return left;
}

const arr = [3, 6, 8, 10, 1, 2, 1];
quicksort(arr);
console.log(arr); // Example output: [1, 1, 2, 3, 6, 8, 10]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;*&lt;em&gt;Removing Duplicates from an Array In-Place:&lt;br&gt;
*&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// javascript
function removeDuplicates(nums) {
    let index = 1;
    for (let i = 1; i &amp;lt; nums.length; i++) {
        if (nums[i] !== nums[i - 1]) {
            nums[index] = nums[i];
            index++;
        }
    }
    return nums.slice(0, index);
}

console.log(removeDuplicates([1, 1, 2, 2, 3, 4, 4])); // Example output: [1, 2, 3, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Reversing an Array In-Place in Java:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

function reverseArray(arr) {
    let left = 0;
    let right = arr.length - 1;
    while (left &amp;lt; right) {
        const temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        left++;
        right--;
    }
}

const arr = [1, 2, 3, 4, 5];
reverseArray(arr);
console.log(arr); // Example output: [5, 4, 3, 2, 1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Removing Duplicates from an Array Without Using Any Library&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function removeDuplicates(arr) {
    const uniqueElements = [];
    for (let i = 0; i &amp;lt; arr.length; i++) {
        if (!uniqueElements.includes(arr[i])) {
            uniqueElements.push(arr[i]);
        }
    }
    return uniqueElements;
}

const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = removeDuplicates(arrayWithDuplicates);
console.log(uniqueArray); // Example output: [1, 2, 3, 4, 5]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Removing Duplicates from an Array Without Using Any Library second&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function removeDuplicates(arr) {
    const unique = [];
    for (const num of arr) {
        if (!unique.includes(num)) {
            unique.push(num);
        }
    }
    return unique;
}

console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // Example output: [1, 2, 3, 4, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Converting a Byte Array to String:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// javascript
function byteArrayToString(bytes) {
    return String.fromCharCode(...bytes);
}

console.log(byteArrayToString([104, 101, 108, 108, 111])); // Example output: "hello"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Difference Between an Array and a Linked List:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

// text
// Arrays:
// - Fixed size (in many languages).
// - Contiguous memory allocation.
// - O(1) access time for elements via index.
// - O(n) time complexity for insertion and deletion (in the worst case).

// Linked Lists:
// - Dynamic size.
// - Non-contiguous memory allocation.
// - O(n) access time for elements (sequential access).
// - O(1) time complexity for insertion and deletion at the beginning or end.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Binary Search in a Given Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// javascript
function binarySearch(arr, target) {
    let left = 0, right = arr.length - 1;
    while (left &amp;lt;= right) {
        const mid = Math.floor((left + right) / 2);
        if (arr[mid] === target) return mid;
        if (arr[mid] &amp;lt; target) left = mid + 1;
        else right = mid - 1;
    }
    return -1; // If the target is not found
}

console.log(binarySearch([1, 2, 3, 4, 5, 6], 4)); // Example output: 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Median of Two Sorted Arrays:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findMedianSortedArrays(nums1, nums2) {
    const merged = mergeSortedArrays(nums1, nums2);
    const n = merged.length;
    if (n % 2 === 0) {
        return (merged[Math.floor((n - 1) / 2)] + merged[Math.floor(n / 2)]) / 2;
    } else {
        return merged[Math.floor(n / 2)];
    }
}

function mergeSortedArrays(arr1, arr2) {
    const merged = [];
    let i = 0, j = 0;
    while (i &amp;lt; arr1.length &amp;amp;&amp;amp; j &amp;lt; arr2.length) {
        if (arr1[i] &amp;lt; arr2[j]) {
            merged.push(arr1[i]);
            i++;
        } else {
            merged.push(arr2[j]);
            j++;
        }
    }
    while (i &amp;lt; arr1.length) merged.push(arr1[i++]);
    while (j &amp;lt; arr2.length) merged.push(arr2[j++]);
    return merged;
}

console.log(findMedianSortedArrays([1, 3], [2])); // Example output: 2
console.log(findMedianSortedArrays([1, 2], [3, 4])); // Example output: 2.5

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;** Rotating an Array Left and Right by a Given Number K:**&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function rotateArrayLeft(arr, k) {
    k = k % arr.length;
    return arr.slice(k).concat(arr.slice(0, k));
}

function rotateArrayRight(arr, k) {
    k = k % arr.length;
    return arr.slice(-k).concat(arr.slice(0, -k));
}

console.log(rotateArrayLeft([1, 2, 3, 4, 5], 2)); // Example output: [3, 4, 5, 1, 2]
console.log(rotateArrayRight([1, 2, 3, 4, 5], 2)); // Example output: [4, 5, 1, 2, 3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding Duplicates from an Unsorted Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

function findDuplicates(nums) {
    const seen = new Set();
    const duplicates = new Set();
    for (const num of nums) {
        if (seen.has(num)) {
            duplicates.add(num);
        } else {
            seen.add(num);
        }
    }
    return Array.from(duplicates);
}

console.log(findDuplicates([1, 2, 3, 4, 3, 2, 1])); // Example output: [1, 2, 3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Starting and Ending Position of a Given Value in a Sorted Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function searchRange(nums, target) {
    const result = [-1, -1];
    result[0] = findBound(nums, target, true);
    if (result[0] !== -1) {
        result[1] = findBound(nums, target, false);
    }
    return result;
}

function findBound(nums, target, isFirst) {
    let left = 0, right = nums.length - 1;
    while (left &amp;lt;= right) {
        const mid = Math.floor((left + right) / 2);
        if (nums[mid] === target) {
            if (isFirst) {
                if (mid === left || nums[mid - 1] !== target) {
                    return mid;
                }
                right = mid - 1;
            } else {
                if (mid === right || nums[mid + 1] !== target) {
                    return mid;
                }
                left = mid + 1;
            }
        } else if (nums[mid] &amp;lt; target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return -1;
}

console.log(searchRange([5, 7, 7, 8, 8, 10], 8)); // Example output: [3, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Contiguous Subarray with the Largest Sum:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;function maxSubArray(nums) {&lt;br&gt;
    let maxSoFar = nums[0];&lt;br&gt;
    let maxEndingHere = nums[0];&lt;br&gt;
    for (let i = 1; i &amp;lt; nums.length; i++) {&lt;br&gt;
        maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);&lt;br&gt;
        maxSoFar = Math.max(maxSoFar, maxEndingHere);&lt;br&gt;
    }&lt;br&gt;
    return maxSoFar;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // Example output: 6&lt;/p&gt;

</description>
    </item>
    <item>
      <title>JavaScript Array Coding question</title>
      <dc:creator>nikhilkalariya</dc:creator>
      <pubDate>Thu, 27 Jun 2024 10:04:29 +0000</pubDate>
      <link>https://dev.to/nikhilkalariya/javascript-array-coding-question-5702</link>
      <guid>https://dev.to/nikhilkalariya/javascript-array-coding-question-5702</guid>
      <description>&lt;p&gt;&lt;strong&gt;Finding the Missing Number in an Array from 1 to 100:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findMissingNumber(nums) {
    const n = 100;
    const expectedSum = (n * (n + 1)) / 2;
    const actualSum = nums.reduce((acc, num) =&amp;gt; acc + num, 0);
    return expectedSum - actualSum;
}

console.log(findMissingNumber([...Array(100).keys()].map(n =&amp;gt; n + 1).filter(n =&amp;gt; n !== 50))); // Example where 50 is missing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Duplicate Number in an Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function findDuplicate(nums) {
    const seen = new Set();
    for (const num of nums) {
        if (seen.has(num)) {
            return num;
        }
        seen.add(num);
    }
    return -1; // If no duplicate found
}

console.log(findDuplicate([1, 2, 3, 4, 4])); // Example with duplicate 4

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Largest and Smallest Number in an Unsorted Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findMinMax(nums) {
    let min = nums[0];
    let max = nums[0];
    for (const num of nums) {
        if (num &amp;lt; min) min = num;
        if (num &amp;gt; max) max = num;
    }
    return { min, max };
}

console.log(findMinMax([3, 5, 1, 2, 4])); // Example output: { min: 1, max: 5 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding All Pairs of an Integer Array Whose Sum Equals a Given Number:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findPairsWithSum(nums, target) {
    const pairs = [];
    const seen = new Set();
    for (const num of nums) {
        const complement = target - num;
        if (seen.has(complement)) {
            pairs.push([complement, num]);
        }
        seen.add(num);
    }
    return pairs;
}

console.log(findPairsWithSum([1, 2, 3, 4, 3], 6)); // Example output: [[3, 3], [2, 4]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding Duplicate Numbers in an Array if It Contains Multiple Duplicates&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findDuplicates(nums) {
    const seen = new Set();
    const duplicates = new Set();
    for (const num of nums) {
        if (seen.has(num)) {
            duplicates.add(num);
        }
        seen.add(num);
    }
    return Array.from(duplicates);
}

console.log(findDuplicates([1, 2, 3, 4, 3, 2])); // Example output: [2, 3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Starting and Ending Position of a Given Value in a Sorted Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

function searchRotatedArray(nums, target) {
    let left = 0, right = nums.length - 1;
    while (left &amp;lt;= right) {
        const mid = Math.floor((left + right) / 2);
        if (nums[mid] === target) return mid;
        if (nums[left] &amp;lt;= nums[mid]) {
            if (nums[left] &amp;lt;= target &amp;amp;&amp;amp; target &amp;lt; nums[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        } else {
            if (nums[mid] &amp;lt; target &amp;amp;&amp;amp; target &amp;lt;= nums[right]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
    }
    return -1;
}

console.log(searchRotatedArray([4, 5, 6, 7, 0, 1, 2], 0)); // Example output: 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Length of the Longest Consecutive Elements Sequence in an Unsorted Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function longestConsecutive(nums) {
    const numSet = new Set(nums);
    let longestStreak = 0;
    for (const num of nums) {
        if (!numSet.has(num - 1)) {
            let currentNum = num;
            let currentStreak = 1;
            while (numSet.has(currentNum + 1)) {
                currentNum += 1;
                currentStreak += 1;
            }
            longestStreak = Math.max(longestStreak, currentStreak);
        }
    }
    return longestStreak;
}

console.log(longestConsecutive([100, 4, 200, 1, 3, 2])); // Example output: 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Sorting an Integer Array In-Place Using the Quicksort Algorithm:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function quicksort(arr, left = 0, right = arr.length - 1) {
    if (left &amp;gt;= right) return;
    const pivot = arr[Math.floor((left + right) / 2)];
    const index = partition(arr, left, right, pivot);
    quicksort(arr, left, index - 1);
    quicksort(arr, index, right);
}

function partition(arr, left, right, pivot) {
    while (left &amp;lt;= right) {
        while (arr[left] &amp;lt; pivot) left++;
        while (arr[right] &amp;gt; pivot) right--;
        if (left &amp;lt;= right) {
            [arr[left], arr[right]] = [arr[right], arr[left]];
            left++;
            right--;
        }
    }
    return left;
}

const arr = [3, 6, 8, 10, 1, 2, 1];
quicksort(arr);
console.log(arr); // Example output: [1, 1, 2, 3, 6, 8, 10]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Reversing an Array In-Place in Java:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function reverseArray(arr) {
    let left = 0;
    let right = arr.length - 1;
    while (left &amp;lt; right) {
        const temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        left++;
        right--;
    }
}

const arr = [1, 2, 3, 4, 5];
reverseArray(arr);
console.log(arr); // Example output: [5, 4, 3, 2, 1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Converting a Byte Array to String:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function byteArrayToString(bytes) {
    return String.fromCharCode(...bytes);
}

console.log(byteArrayToString([104, 101, 108, 108, 111])); // Example output: "hello"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;*&lt;em&gt;Difference Between an Array and a Linked List:&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;// text&lt;br&gt;
// Arrays:&lt;br&gt;
// - Fixed size (in many languages).&lt;br&gt;
// - Contiguous memory allocation.&lt;br&gt;
// - O(1) access time for elements via index.&lt;br&gt;
// - O(n) time complexity for insertion and deletion (in the worst case).&lt;/p&gt;

&lt;p&gt;// Linked Lists:&lt;br&gt;
// - Dynamic size.&lt;br&gt;
// - Non-contiguous memory allocation.&lt;br&gt;
// - O(n) access time for elements (sequential access).&lt;br&gt;
// - O(1) time complexity for insertion and deletion at the beginning or end.&lt;br&gt;
&lt;strong&gt;Binary Search in a Given Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function binarySearch(arr, target) {
    let left = 0, right = arr.length - 1;
    while (left &amp;lt;= right) {
        const mid = Math.floor((left + right) / 2);
        if (arr[mid] === target) return mid;
        if (arr[mid] &amp;lt; target) left = mid + 1;
        else right = mid - 1;
    }
    return -1; // If the target is not found
}

console.log(binarySearch([1, 2, 3, 4, 5, 6], 4)); 
// Example output: 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Median of Two Sorted Arrays:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findMedianSortedArrays(nums1, nums2) {
    const merged = mergeSortedArrays(nums1, nums2);
    const n = merged.length;
    if (n % 2 === 0) {
        return (merged[Math.floor((n - 1) / 2)] + merged[Math.floor(n / 2)]) / 2;
    } else {
        return merged[Math.floor(n / 2)];
    }
}

function mergeSortedArrays(arr1, arr2) {
    const merged = [];
    let i = 0, j = 0;
    while (i &amp;lt; arr1.length &amp;amp;&amp;amp; j &amp;lt; arr2.length) {
        if (arr1[i] &amp;lt; arr2[j]) {
            merged.push(arr1[i]);
            i++;
        } else {
            merged.push(arr2[j]);
            j++;
        }
    }
    while (i &amp;lt; arr1.length) merged.push(arr1[i++]);
    while (j &amp;lt; arr2.length) merged.push(arr2[j++]);
    return merged;
}

console.log(findMedianSortedArrays([1, 3], [2])); // Example output: 2
console.log(findMedianSortedArrays([1, 2], [3, 4])); // Example output: 2.5

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;** Rotating an Array Left and Right by a Given Number K:**&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function rotateArrayLeft(arr, k) {
    k = k % arr.length;
    return arr.slice(k).concat(arr.slice(0, k));
}

function rotateArrayRight(arr, k) {
    k = k % arr.length;
    return arr.slice(-k).concat(arr.slice(0, -k));
}

console.log(rotateArrayLeft([1, 2, 3, 4, 5], 2)); // Example output: [3, 4, 5, 1, 2]
console.log(rotateArrayRight([1, 2, 3, 4, 5], 2)); // Example output: [4, 5, 1, 2, 3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding Duplicates from an Unsorted Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

function findDuplicates(nums) {
    const seen = new Set();
    const duplicates = new Set();
    for (const num of nums) {
        if (seen.has(num)) {
            duplicates.add(num);
        } else {
            seen.add(num);
        }
    }
    return Array.from(duplicates);
}

console.log(findDuplicates([1, 2, 3, 4, 3, 2, 1])); // Example output: [1, 2, 3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Starting and Ending Position of a Given Value in a Sorted Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function searchRange(nums, target) {
    const result = [-1, -1];
    result[0] = findBound(nums, target, true);
    if (result[0] !== -1) {
        result[1] = findBound(nums, target, false);
    }
    return result;
}

function findBound(nums, target, isFirst) {
    let left = 0, right = nums.length - 1;
    while (left &amp;lt;= right) {
        const mid = Math.floor((left + right) / 2);
        if (nums[mid] === target) {
            if (isFirst) {
                if (mid === left || nums[mid - 1] !== target) {
                    return mid;
                }
                right = mid - 1;
            } else {
                if (mid === right || nums[mid + 1] !== target) {
                    return mid;
                }
                left = mid + 1;
            }
        } else if (nums[mid] &amp;lt; target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return -1;
}

console.log(searchRange([5, 7, 7, 8, 8, 10], 8)); // Example output: [3, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finding the Contiguous Subarray with the Largest Sum:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function maxSubArray(nums) {
    let maxSoFar = nums[0];
    let maxEndingHere = nums[0];
    for (let i = 1; i &amp;lt; nums.length; i++) {
        maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
        maxSoFar = Math.max(maxSoFar, maxEndingHere);
    }
    return maxSoFar;
}

console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // Example output: 6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Duplicate Number</title>
      <dc:creator>nikhilkalariya</dc:creator>
      <pubDate>Thu, 27 Jun 2024 10:04:23 +0000</pubDate>
      <link>https://dev.to/nikhilkalariya/duplicate-number-1gk8</link>
      <guid>https://dev.to/nikhilkalariya/duplicate-number-1gk8</guid>
      <description>&lt;p&gt;&lt;strong&gt;Find duplicate number with filter&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = [1, 2, 3, 2, 4, 5, 4, 5];
const duplicates1 = array.filter((item, index) =&amp;gt; array.indexOf(item) !== index);

console.log(duplicates1); // Output: [2, 4, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Find duplicate number with  Nested For In Loop&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = [1, 2, 3, 2, 4, 5, 4, 5];
let duplicates = [];

for (let i in array) {
    for (let j in array) {
        if (array[i] === array[j] &amp;amp;&amp;amp; i !== j) {
            // Check if the found duplicate is already in the duplicates array
            if (!duplicates.includes(array[i])) {
                duplicates.push(array[i]);
                break; // To avoid adding the same duplicate multiple times
            }
        }
    }
}

console.log(duplicates);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Find duplicate number with Foreach&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr = [1, 2, 3, 4, 5, 2, 6, 3, 7, 8, 8];
let duplicates = [];

arr.forEach(function (value, index, array) {
    if (array.indexOf(value, index + 1) !== -1
        &amp;amp;&amp;amp; duplicates.indexOf(value) === -1) {
        duplicates.push(value);
    }
});
console.log(duplicate)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Find duplicate number Using Set() object and has() Method&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = [1, 2, 3, 2, 4, 5, 4, 5];
const uniqueElements = new Set();
const duplicates = [];

array.forEach(item =&amp;gt; {
  if (uniqueElements.has(item)) {
    duplicates.push(item);
  } else {
    uniqueElements.add(item);
  }
});

console.log(duplicates); // Output: [2, 4, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Removing Duplicates from an Array In-Place:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function removeDuplicates(nums) {
    let index = 1;
    for (let i = 1; i &amp;lt; nums.length; i++) {
        if (nums[i] !== nums[i - 1]) {
            nums[index] = nums[i];
            index++;
        }
    }
    return nums.slice(0, index);
}

console.log(removeDuplicates([1, 1, 2, 2, 3, 4, 4])); // Example output: [1, 2, 3, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Removing Duplicates from an Array Without Using Any Library&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function removeDuplicates(arr) {
    const uniqueElements = [];
    for (let i = 0; i &amp;lt; arr.length; i++) {
        if (!uniqueElements.includes(arr[i])) {
            uniqueElements.push(arr[i]);
        }
    }
    return uniqueElements;
}

const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = removeDuplicates(arrayWithDuplicates);
console.log(uniqueArray); // Example output: [1, 2, 3, 4, 5]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Removing Duplicates from an Array Without Using Any Library second&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function removeDuplicates(arr) {
    const unique = [];
    for (const num of arr) {
        if (!unique.includes(num)) {
            unique.push(num);
        }
    }
    return unique;
}

console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // Example output: [1, 2, 3, 4, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Example 1:

Input: nums = [1,2,3,1]
Output: true
Input: nums = [2,3,1]
Output: false

function containsDuplicate(nums) {
    const uniqueElements = new Set();

    for (let num of nums) {
        if (uniqueElements.has(num)) {
            return true;
        }
        uniqueElements.add(num);
    }

    return false;
}
const arr = [1, 2, 1, 4, 3, 4, 5, 6];
console.log(containsDuplicate(arr)); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Missing Number</title>
      <dc:creator>nikhilkalariya</dc:creator>
      <pubDate>Thu, 27 Jun 2024 09:18:41 +0000</pubDate>
      <link>https://dev.to/nikhilkalariya/missing-number-225n</link>
      <guid>https://dev.to/nikhilkalariya/missing-number-225n</guid>
      <description>&lt;p&gt;&lt;strong&gt;with using sort method to solve&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1, 2, 3, 4, 5, 6, 8, 9, 10];
function findMissingNumber(arr) {
    arr.sort((a, b) =&amp;gt; a - b);
    for (let i = 0; i &amp;lt; arr.length; i++) {
        if (arr[i] !== i + 1) {
            return i + 1;
        }
    }
    return arr.length + 1;
}


const missingNumber = findMissingNumber(numbers);
console.log("The missing number is:", missingNumber);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Missing number using for loop&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function test(nums) {
  for (let n = 1; n&amp;lt;= nums.length + 1; n++) {
    if (nums.indexOf(n) === -1) 
      return n;
  }
}

nums = [1,3,5,6,7]
console.log("nums = "+nums)
console.log("Missing number of the said array: "+test(nums));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Without  using any built in method&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//third way to find missng number
const arr1 = [1, 2, 3, 5];
const N = arr1.length;
function getMissingNo(arr1, n) {
    // The range is [1, N]
    const N = n + 1;
    // Calculate the sum of the range
    const totalSum = (N * (N + 1)) / 2;

    // Sum of elements in the array
    let arraySum = 0;
    for (let i = 0; i &amp;lt; n; i++) {
        arraySum += arr1[i];
    }

    // The missing number
    return totalSum - arraySum;
}

// Driver code

console.log(getMissingNo(arr1, N));

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;With using reduce method  to solve&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const arr = [1, 2, 4, 5, 6];
//second way find missing job
function findMissingNumber(arr) {
  // Calculate the length of the array + 1 (since one number is missing)
  const n = arr.length + 1;

  // Calculate the expected sum of numbers from 1 to n
  const expectedSum = (n * (n + 1)) / 2;

  // Calculate the sum of numbers in the given array
  const actualSum = arr.reduce((acc, num) =&amp;gt; acc + num, 0);

  // The difference between expectedSum and actualSum is the missing number
  const missingNumber = expectedSum - actualSum;

  console.log("The missing number is:", missingNumber);
  return missingNumber;
}

// Example usage

findMissingNumber(arr);  // Output will be: The missing number is: 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Find all missing first to last element between&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const arr1 = [1, 3, 5, 7];

// Find the minimum and maximum values in the array
const min = Math.min(...arr1);
const max = Math.max(...arr1);

// Initialize an array to hold the missing numbers
const missingNumbers = [];

// Loop through the range from min to max
for (let i = min; i &amp;lt;= max; i++) {
  // If the current number is not in the array, add it to the missing numbers
  if (!arr1.includes(i)) {
    missingNumbers.push(i);
  }
}

console.log(missingNumbers); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>React interview questions</title>
      <dc:creator>nikhilkalariya</dc:creator>
      <pubDate>Tue, 19 Mar 2024 09:50:45 +0000</pubDate>
      <link>https://dev.to/nikhilkalariya/react-interview-qusetion-58hg</link>
      <guid>https://dev.to/nikhilkalariya/react-interview-qusetion-58hg</guid>
      <description>&lt;p&gt;&lt;strong&gt;1. What is React?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;React is an open-source front-end JavaScript library that is used for building composable user interfaces, especially for single-page applications. It is used for handling view layer for web and mobile apps based on components in a declarative approach.&lt;/p&gt;

&lt;p&gt;React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook's News Feed in 2011 and on Instagram in 2012&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. How is React different from Angular or Vue?&lt;/strong&gt;&lt;br&gt;
When comparing React, Angular, and Vue.js, a few key differentiators stand out.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Core Philosophy&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;React: Focuses on UI components. You need other libraries for state management, routing, etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Angular: Provides a more comprehensive solution out of the box, often called "batteries included."&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Vue.js: A good balance of providing core libraries and flexibility for integration with third-party tools.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Learning Curve&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;React: Initially simpler to learn due to its focused nature, but can become complex as you add more external libraries.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Angular: Steeper learning curve because of its complete ecosystem, including modules, services, and complex directives.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Vue.js: Known for its gentle learning curve and clear, concise documentation.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Community and Ecosystem&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;React: Enjoys an enormous community, and users can pick and choose from a vast array of third-party libraries to complement its core features.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Angular: Boasts a comprehensive ecosystem that's well-managed by its developers and is known for its enterprise support.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Vue.js: While the newest of these frameworks, it has been growing rapidly, with a dedicated team and a flourishing community.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Performance&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;React: Focuses on efficient rendering and offers built-in tools for performance optimization.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Angular: Optimizes performance through features like Ahead-Of-Time (AOT) compilation and Zone.js, which prevents unnecessary digest cycles.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Vue.js: Also optimized for performance, with a small bundle size and features like lazy-loading components.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3. How do you create a component in React?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Creating a React component involves defining its structure, behavior, and sometimes lifecycle methods for dynamic updates. Components can be functional or class-based.&lt;/p&gt;

&lt;p&gt;Code Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;`Here's a Class-based component:

import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return &amp;lt;h1&amp;gt;Hello, {this.props.name}!&amp;lt;/h1&amp;gt;;
  }
}
And here's a Functional one:

import React from 'react';`

const Greeting = ({ name }) =&amp;gt; &amp;lt;h1&amp;gt;Hello, {name}!&amp;lt;/h1&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Both examples showcase a basic greeting component that takes in a prop name and displays a greeting message.&lt;/p&gt;

&lt;p&gt;Linters and JSX&lt;br&gt;
Many modern text editors and IDEs support JSX and JavaScript syntax, especially when integrated with linters like ESLint. This setup provides real-time feedback on errors and formatting issues.&lt;/p&gt;

&lt;p&gt;Code Styling with AirBNB and Prettier&lt;br&gt;
It's common to see code bases following the Airbnb style guide, often coupled with Prettier for consistent and automated code formatting.&lt;/p&gt;

&lt;p&gt;In the context of component creation, these standards can dictate whether to use single or double quotes for JSX attributes and the method for defining components.&lt;/p&gt;

&lt;p&gt;Key Takeaways&lt;br&gt;
JSX offers a natural, HTML-like syntax for building components in React.&lt;br&gt;
Components can be function-based or class-based.&lt;br&gt;
Use modern editing tools and linters for improved code consistency and spotting potential issues in real-time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Functional vs Class-Based Components&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Here is the React code:
// Functional Component with useState hook
import React, { useState } from 'react';

export default function Button() {
  const [count, setCount] = useState(0);
  return (
    &amp;lt;button onClick={() =&amp;gt; setCount(count + 1)}&amp;gt;
      Clicked {count} times
    &amp;lt;/button&amp;gt;
  );
}


// Class-based Component


import React, { Component } from 'react';

export default class Button extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return (
      &amp;lt;button onClick={() =&amp;gt; this.setState({ count: this.state.count + 1 })}&amp;gt;
        Clicked {this.state.count} times
      &amp;lt;/button&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Can you explain the virtual DOM in React?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Virtual DOM is a key concept in React, responsible for its high performance. It efficiently manages the DOM setup, minimizes updates, and then syncs them to the actual DOM tree.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;How the Virtual DOM Works&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Initial Rendering&lt;/strong&gt;: When the application starts, React creates a simplified in-memory representation of the DOM, called the Virtual DOM.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tree Comparison:&lt;/strong&gt; During each state change, React builds a new Virtual DOM representation. It then compares this updated representation against the previous one to identify what has changed. This process is often called "reconciliation".&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Selective Rendering:&lt;/strong&gt; React determines the most minimal set of changes needed to keep the Virtual DOM in sync with the actual DOM. This approach, known as "reconciliation", is a performance booster as it reduces unnecessary updates.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Batched Updates:&lt;/strong&gt; React performs the actual DOM updates in a batch, typically during the next animation frame or when no more updates are being made. This batching leads to optimized DOM operations, further enhancing performance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;One-Way Sync:&lt;/strong&gt; After the in-memory Virtual DOM and the actual DOM have been reconciled and the necessary updates identified, React syncs these changes in a one-way process, from the Virtual DOM to the actual DOM. This approach helps prevent unnecessary visual glitches and performance hits.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Asynchronous Handling:&lt;/strong&gt; React schedules state changes, ensuring performance by bundling multiple changes that can be processed together. This aids in avoiding unnecessary Virtual DOM updates and ensures efficient tree comparisons.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Preventing Direct DOM Manipulation&lt;/strong&gt;: React applications typically avoid manual DOM manipulation. Instead, all changes are made through React, which then uses its Virtual DOM mechanism to batch and apply these changes to the actual DOM.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Support for Cross-Platform Environments:&lt;/strong&gt; The Virtual DOM gives sturdy cross-platform capabilities, enabling consistent and optimized performance irrespective of the underlying operating system or hardware.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. What are props and state in React? Explain React state and props&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The props in React are the inputs to a component of React. They can be single-valued or objects having a set of values that will be passed to components of React during creation by using a naming convention that almost looks similar to HTML-tag attributes. We can say that props are the data passed from a parent component into a child component.&lt;/p&gt;

&lt;p&gt;The main purpose of props is to provide different component functionalities such as:&lt;/p&gt;

&lt;p&gt;Passing custom data to the React component.&lt;br&gt;
Using through this.props.reactProp inside render() method of the component.&lt;br&gt;
Triggering state changes.&lt;br&gt;
For example, consider we are creating an element with reactProp property as given below: &lt;br&gt;
This reactProp name will be considered as a property attached to the native props object of React which already exists on each component created with the help of React library: props.reactProp;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Props&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Immutable &lt;/li&gt;
&lt;li&gt;Has better performance
&lt;/li&gt;
&lt;li&gt;Can be passed to child components&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;State&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Owned by its component&lt;/li&gt;
&lt;li&gt;Locally scoped&lt;/li&gt;
&lt;li&gt;Writeable/Mutable&lt;/li&gt;
&lt;li&gt;has setState() method to modify properties&lt;/li&gt;
&lt;li&gt;Changes to state can be asynchronous&lt;/li&gt;
&lt;li&gt;can only be passed as props&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;How to declare a state object?&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Car extends React.Component{
constructor(props){
  super(props);
  this.state = {
    brand: "BMW",
    color: "black"
  }
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How to use and update the state object?&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
class Car extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    brand: "BMW",
    color: "Black"
  };
}
changeColor() {
  this.setState(prevState =&amp;gt; {
    return { color: "Red" };
  });
}
render() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; this.changeColor()}&amp;gt;Change Color&amp;lt;/button&amp;gt;
      &amp;lt;p&amp;gt;{this.state.color}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As one can see in the code above, we can use the state by calling this.state.propertyName and we can change the state object property using setState method.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;React Props&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Every React component accepts a single object argument called props (which stands for “properties”).  These props can be passed to a component using HTML attributes and the component accepts these props as an argument.&lt;/p&gt;

&lt;p&gt;Using props, we can pass data from one component to another.&lt;/p&gt;

&lt;p&gt;Passing props to a component:&lt;/p&gt;

&lt;p&gt;While rendering a component, we can pass the props as an HTML attribute:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Car brand="Mercedes"/&amp;gt;
The component receives the props:

In Class component:

class Car extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    brand: this.props.brand,
    color: "Black"
  };
}
}
In Functional component:

function Car(props) {
let [brand, setBrand] = useState(props.brand);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What Is ‘State’ in ReactJS?&lt;/p&gt;

&lt;p&gt;The state is a built-in React object that is used to contain data or information about the component. A component’s state can change over time; whenever it changes, the component re-renders. The change in state can happen as a response to user action or system-generated events and these changes determine the behavior of the component and how it will render.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;React State&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A state can be modified based on user action or network changes&lt;br&gt;
Every time the state of an object changes, React re-renders the component to the browser&lt;/p&gt;

&lt;p&gt;The state object is initialized in the constructor&lt;br&gt;
The state object can store multiple properties&lt;br&gt;
this.setState() is used to change the value of the state object&lt;br&gt;
setState() function performs a shallow merge between the new and the previous state&lt;/p&gt;

&lt;p&gt;The setState() Method&lt;br&gt;
State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.&lt;/p&gt;

&lt;p&gt;Always use the setState() method to change the state object, since it will ensure that the component knows it’s been updated and calls the render() method&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Greetings extends React.Component {
  state = {
    name: "World"
  };

  updateName() {
    this.setState({ name: "Simplilearn" });
  }

  render() {
      return(
          &amp;lt;div&amp;gt;
              {this.state.name}
          &amp;lt;/div&amp;gt;
      )
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;7. Explain the lifecycle methods of components&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A React Component can go through four stages of its life as follows. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Initialization:&lt;/strong&gt; This is the stage where the component is constructed with the given Props and default state. This is done in the constructor of a Component Class.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mounting:&lt;/strong&gt; Mounting is the stage of rendering the JSX returned by the render method itself.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Updating:&lt;/strong&gt; Updating is the stage when the state of a component is updated and the application is repainted.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Unmounting:&lt;/strong&gt; As the name suggests Unmounting is the final step of the component lifecycle where the component is removed from the page.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;8. What is prop drilling in React?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Sometimes while developing React applications, there is a need to pass data from a component that is higher in the hierarchy to a component that is deeply nested. To pass data between such components, we pass props from a source component and keep passing the prop to the next component in the hierarchy till we reach the deeply nested component.&lt;/p&gt;

&lt;p&gt;The disadvantage of using prop drilling is that the components that should otherwise be not aware of the data have access to the data&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;9. How do you handle events in React?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;React simplifies the process of managing and handling events through its use of synthetic events.&lt;/p&gt;

&lt;p&gt;Handling Events in React&lt;br&gt;
Synthetic Events&lt;br&gt;
React abstracts browser events into what are known as synthetic events. This ensures a consistent interface across different browsers.&lt;/p&gt;

&lt;p&gt;Event Subscription&lt;br&gt;
When handling events, React behaves consistently across all elements, not just form elements.&lt;/p&gt;

&lt;p&gt;React events use camelCase, unlike HTML, which is helpful for both consistency and avoiding reserved words in JavaScript.&lt;/p&gt;

&lt;p&gt;Use boolean attributes in JSX for default browser events.&lt;/p&gt;

&lt;p&gt;Special Event Handling&lt;br&gt;
React provides special interfaces for certain types of events: input components benefit from the value attribute, while media components make use of src or other similar attributes specific to their type.&lt;/p&gt;

&lt;p&gt;Code Example: Event Handling&lt;br&gt;
Here is the JavaScript code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: '' };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      &amp;lt;form onSubmit={this.handleSubmit}&amp;gt;
        &amp;lt;label&amp;gt;
          Name:
          &amp;lt;input type="text" value={this.state.value} onChange={this.handleChange} /&amp;gt;
        &amp;lt;/label&amp;gt;
        &amp;lt;input type="submit" value="Submit" /&amp;gt;
      &amp;lt;/form&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;10. What is React Hooks? Explain React Hooks.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;React Hooks are the built-in functions that permit developers for using the state and lifecycle methods within React components. These are newly added features made available in React 16.8 version. Each lifecycle of a component is having 3 phases which include mount, unmount, and update. Along with that, components have properties and states. Hooks will allow using these methods by developers for improving the reuse of code with higher flexibility navigating the component tree.&lt;/p&gt;

&lt;p&gt;Using Hook, all features of React can be used without writing class components. For example, before React version 16.8, it required a class component for managing the state of a component. But now using the useState hook, we can keep the state in a functional component.&lt;/p&gt;

&lt;p&gt;What are Hooks? Hooks are functions that let us “hook into” React state and lifecycle features from a functional component.&lt;/p&gt;

&lt;p&gt;React Hooks cannot be used in class components. They let us write components without class.&lt;/p&gt;

&lt;p&gt;Why were Hooks introduced in React?&lt;/p&gt;

&lt;p&gt;React hooks were introduced in the 16.8 version of React. Previously, functional components were called stateless components. Only class components were used for state management and lifecycle methods. The need to change a functional component to a class component, whenever state management or lifecycle methods were to be used, led to the development of Hooks.&lt;/p&gt;

&lt;p&gt;Example of a hook: useState hook:&lt;/p&gt;

&lt;p&gt;In functional components, the useState hook lets us define a state for a component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Person(props) {
// We are declaring a state variable called name.
// setName is a function to update/change the value of name
let [name, setName] = useState('');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The state variable “name” can be directly used inside the HTML. &lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
