<?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: Ahsan Iftikhar</title>
    <description>The latest articles on DEV Community by Ahsan Iftikhar (@ahsaniftikhar99).</description>
    <link>https://dev.to/ahsaniftikhar99</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%2F1315391%2F8ab39a33-0f72-4c61-93f5-5d028591dd41.JPEG</url>
      <title>DEV Community: Ahsan Iftikhar</title>
      <link>https://dev.to/ahsaniftikhar99</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ahsaniftikhar99"/>
    <language>en</language>
    <item>
      <title>10+ Essential JavaScript Functions to Streamline Your Code | JavaScript Guide</title>
      <dc:creator>Ahsan Iftikhar</dc:creator>
      <pubDate>Fri, 31 May 2024 12:20:32 +0000</pubDate>
      <link>https://dev.to/ahsaniftikhar99/10-essential-javascript-functions-to-streamline-your-code-javascript-guide-28mo</link>
      <guid>https://dev.to/ahsaniftikhar99/10-essential-javascript-functions-to-streamline-your-code-javascript-guide-28mo</guid>
      <description>&lt;p&gt;JavaScript is a versatile language that heavily relies on functions, making it essential for both beginners and experienced developers to master them. Functions in JavaScript help you encapsulate reusable code, making your programming more efficient and organized. Here are some examples of handy JavaScript functions that can simplify your code and improve your development workflow:&lt;/p&gt;

&lt;h2&gt;
  
  
  Regular function
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function subtract(a, b) {
  return a - b;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Function expression
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const sum = function (a, b) {
  return a + b;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Arrow function
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const subtract= (a, b) =&amp;gt; {
  return a - b;
};
// OR
const subtract= (a, b) =&amp;gt; a - b;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Generator function
&lt;/h2&gt;

&lt;p&gt;Generator functions in JavaScript provide a powerful way to work with iterators and allow you to pause and resume execution at various points. They are especially useful for handling sequences of data and can be a valuable tool in your coding arsenal. Let's explore the basics of generator functions and see some examples.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is a Generator Function?&lt;/strong&gt;&lt;br&gt;
A generator function is defined using the function* syntax (with an asterisk). Unlike regular functions, generator functions can yield multiple values over time, allowing you to iterate through them one by one.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function* indexGenerator() {
  let index = 0;
  while (true) {
    yield index++;
  }
}
const g = indexGenerator();
console.log(g.next().value); // =&amp;gt; 0
console.log(g.next().value); // =&amp;gt; 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Generate random number
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const random = (min, max) =&amp;gt; Math.floor(Math.random() * (max - min + 1)) + min;
console.log(random(1, 10)); 
// This will generate a random number between a min and max range
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Convert array to object
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const toObject = (arr) =&amp;gt; ({ ...arr });
console.log(toObject(["a", "b"])); // { 0: 'a', 1: 'b' }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Debounce Function
&lt;/h2&gt;

&lt;p&gt;Limits the rate at which a function can fire.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export function debounce(func, wait) {
  // Declare a variable to keep track of the timeout ID
  let timeout;

  // Return a new function that wraps the original function
  return function(...args) {
    // Clear the previous timeout, if it exists
    clearTimeout(timeout);

    // Set a new timeout to invoke the function after the specified wait time
    timeout = setTimeout(() =&amp;gt; {
      // Use apply to call the original function with the correct `this` context and arguments
      func.apply(this, args);
    }, wait);
  };
}

---
import React, { useState, useCallback } from 'react';
import axios from 'axios';
import { debounce } from './utils/debounce';

function Search() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);

  const fetchResults = async (query) =&amp;gt; {
    if (!query) {
      setResults([]);
      return;
    }
    try {
      const response = await axios.get(`https://api.example.com/search?q=${query}`);
      setResults(response.data);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  // Create a debounced version of the fetchResults function
  const debouncedFetchResults = useCallback(debounce(fetchResults, 300), []);

  const handleInputChange = (event) =&amp;gt; {
    const newQuery = event.target.value;
    setQuery(newQuery);
    debouncedFetchResults(newQuery);
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;input
        type="text"
        value={query}
        onChange={handleInputChange}
        placeholder="Search..."
      /&amp;gt;
      &amp;lt;ul&amp;gt;
        {results.map((result, index) =&amp;gt; (
          &amp;lt;li key={index}&amp;gt;{result.name}&amp;lt;/li&amp;gt;
        ))}
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}


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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Throttle Function
&lt;/h2&gt;

&lt;p&gt;Ensures a function is only called at most once in a given period.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function throttle(func, limit) {
  // Variables to track the last function call and the time it was last run
  let lastFunc;
  let lastRan;

  // Return a new function that wraps the original function
  return function(...args) {
    // If the function hasn't been run yet, call it and record the time
    if (!lastRan) {
      func.apply(this, args);
      lastRan = Date.now();
    } else {
      // Clear any previously scheduled function calls
      clearTimeout(lastFunc);

      // Schedule a new function call
      lastFunc = setTimeout(() =&amp;gt; {
        // If the time since the last function call is greater than or equal to the limit, call the function
        if ((Date.now() - lastRan) &amp;gt;= limit) {
          func.apply(this, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan));
    }
  };
}

// Example usage of the throttle function

// A function that will be throttled
function logMessage(message) {
  console.log(message);
}

// Create a throttled version of the logMessage function with a limit of 2000 milliseconds (2 seconds)
const throttledLogMessage = throttle(logMessage, 2000);

// Simulate calling the throttled function multiple times
setInterval(() =&amp;gt; {
  throttledLogMessage('Hello, World!');
}, 500);

// This example will log "Hello, World!" to the console at most once every 2 seconds, even though the function is called every 500 milliseconds.

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Clone Object
&lt;/h2&gt;

&lt;p&gt;Creates a deep copy of an object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function cloneObject(obj) {
  return JSON.parse(JSON.stringify(obj));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Get Unique Values from Array
&lt;/h2&gt;

&lt;p&gt;Returns an array with unique values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getUniqueValues(array) {
  return [...new Set(array)];
}

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Safe JSON Parse
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function safeJSONParse(jsonString) {
  try {
    return JSON.parse(jsonString);
  } catch (e) {
    return null;
  }
}

// Dummy JSON strings for testing
const validJSON = '{"name": "John", "age": 30, "city": "New York"}';
const invalidJSON = '{"name": "John", "age": 30, "city": "New York"';

// Calling the function with a valid JSON string
const parsedValidJSON = safeJSONParse(validJSON);
console.log(parsedValidJSON); // Output: { name: 'John', age: 30, city: 'New York' }

// Calling the function with an invalid JSON string
const parsedInvalidJSON = safeJSONParse(invalidJSON);
console.log(parsedInvalidJSON); // Output: null
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Reverse String
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const reverseString = (str) =&amp;gt; str.split("").reverse().join("");
console.log(reverseString("hello")); // olleh
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Array Chunking
&lt;/h2&gt;

&lt;p&gt;Splits an array into chunks of a specified size&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function chunkArray(array, size) {
  // Initialize an empty array to hold the chunks
  const result = [];

  // Loop through the input array in increments of 'size'
  for (let i = 0; i &amp;lt; array.length; i += size) {
    // Use the slice method to create a chunk of 'size' elements
    // starting from the current index 'i' and push it to the result array
    result.push(array.slice(i, i + size));
  }

  // Return the array of chunks
  return result;
}

// Example usage:
const sampleArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunkSize = 3;

const chunkedArray = chunkArray(sampleArray, chunkSize);
console.log(chunkedArray);
// Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>tutorial</category>
      <category>node</category>
    </item>
  </channel>
</rss>
