10+ Essential JavaScript Functions to Streamline Your Code | JavaScript Guide
Ahsan Iftikhar
Posted on May 31, 2024
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:
Regular function
function subtract(a, b) {
return a - b;
Function expression
const sum = function (a, b) {
return a + b;
};
Arrow function
const subtract= (a, b) => {
return a - b;
};
// OR
const subtract= (a, b) => a - b;
Generator function
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.
What is a Generator Function?
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.
function* indexGenerator() {
let index = 0;
while (true) {
yield index++;
}
}
const g = indexGenerator();
console.log(g.next().value); // => 0
console.log(g.next().value); // => 1
Generate random number
const random = (min, max) => 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
Convert array to object
const toObject = (arr) => ({ ...arr });
console.log(toObject(["a", "b"])); // { 0: 'a', 1: 'b' }
Debounce Function
Limits the rate at which a function can fire.
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(() => {
// 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) => {
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) => {
const newQuery = event.target.value;
setQuery(newQuery);
debouncedFetchResults(newQuery);
};
return (
<div>
<input
type="text"
value={query}
onChange={handleInputChange}
placeholder="Search..."
/>
<ul>
{results.map((result, index) => (
<li key={index}>{result.name}</li>
))}
</ul>
</div>
);
}
Throttle Function
Ensures a function is only called at most once in a given period.
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(() => {
// If the time since the last function call is greater than or equal to the limit, call the function
if ((Date.now() - lastRan) >= 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(() => {
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.
Clone Object
Creates a deep copy of an object.
function cloneObject(obj) {
return JSON.parse(JSON.stringify(obj));
}
Get Unique Values from Array
Returns an array with unique values.
function getUniqueValues(array) {
return [...new Set(array)];
}
Safe JSON Parse
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
Reverse String
const reverseString = (str) => str.split("").reverse().join("");
console.log(reverseString("hello")); // olleh
Array Chunking
Splits an array into chunks of a specified size
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 < 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]]
Posted on May 31, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.