DEV Community

Cover image for 16+ JavaScript snippets to save your time
Posandu
Posandu

Posted on • Originally published at tronic247.com

16+ JavaScript snippets to save your time

I made some JavaScript snippets to save you some time. See them below and let me know your thoughts!

Detect if dark mode

This snippet detects if the user is in dark mode. And if so, it returns true.

const isDarkMode = () =>
    globalThis.matchMedia?.("(prefers-color-scheme:dark)").matches ?? false;

// Usage
isDarkMode();
Enter fullscreen mode Exit fullscreen mode

Copy to clipboard

This snippet copies the given text to the clipboard.

const copyToClipboard = (text) =>
    navigator?.clipboard?.writeText(text) ?? false;

// Usage
copyToClipboard("Hello World!");
Enter fullscreen mode Exit fullscreen mode

Make items in an array unique

This snippet makes items in an array unique.

const uniqueArray = (array) => [...new Set(array)];

// Usage
uniqueArray([1, 2, 3, 4, 5, 1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Get random number

const getRandomNumber = (min, max) => ~~(Math.random() * (max - min + 1)) + min;

// Usage
getRandomNumber(1, 10); // Random number between 1 and 10
Enter fullscreen mode Exit fullscreen mode

Get random hex color

This snippet returns a random hex color. It first generates a random number between 0 and 255, then converts it to hex.

const getRandomHexColor = () =>
    "#" + ((Math.random() * 0xffffff) << 0).toString(16);

// Usage
getRandomHexColor(); // Random hex color
Enter fullscreen mode Exit fullscreen mode

Shuffle array

This snippet shuffles an array.

const shuffleArray = (array) => array.sort(() => Math.random() - 0.5);

// Usage
shuffleArray([1, 2, 3, 4, 5]); // Randomly shuffled array
Enter fullscreen mode Exit fullscreen mode

Loop a function x times

This snippet loops a function x times. Useful if you have many loops.

const loop = (x, fn) => [...Array(x)].forEach(fn);

// Usage
loop(10, () => console.log("Hello World!"));
Enter fullscreen mode Exit fullscreen mode

Get random element from array

This snippet returns a random element from an array.

const getRandomElement = (array) => array[~~(Math.random() * array.length)];

// Usage
getRandomElement([1, 2, 3, 4, 5]); // Random element from array
Enter fullscreen mode Exit fullscreen mode

Get random string

This snippet returns a random string.

const getRandomString = (length) =>
    [...Array(length)]
        .map(() => String.fromCharCode(~~(Math.random() * 26) + 97))
        .join("");

// Usage
getRandomString(10); // Random string with 10 characters
Enter fullscreen mode Exit fullscreen mode

Get random boolean

This snippet returns a random boolean.

const getRandomBoolean = () => Math.random() >= 0.5;

// Usage
getRandomBoolean(); // Random boolean
Enter fullscreen mode Exit fullscreen mode

Get random number between two numbers

This snippet returns a random number between two numbers.

const getRandomNumberBetween = (min, max) =>
    ~~(Math.random() * (max - min + 1)) + min;

// Usage
getRandomNumberBetween(1, 10); // Random number between 1 and 10
Enter fullscreen mode Exit fullscreen mode

Get cookie

This snippet returns the value of a cookie.

const getCookie = (name) =>
    ("; " + document.cookie).split(`; ${name}=`).pop().split(";")[0];

// Usage
getCookie("name"); // Value of cookie "name"
Enter fullscreen mode Exit fullscreen mode

Clear all cookies

const clearCookies = () =>
    document.cookie
        .split(";")
        .forEach(
            (c) =>
                (document.cookie = c
                    .replace(/^ +/, "")
                    .replace(/=.*/, "=;expires=Thu, 01 Jan 1970 00:00:00 UTC"))
        );

// Usage
clearCookies(); // Clear all cookies
Enter fullscreen mode Exit fullscreen mode

Scroll to top of element

const scrollToTop = (element) => element.scrollIntoView({ behavior: "smooth" });

// Usage
scrollToTop(document.querySelector("#element"));
Enter fullscreen mode Exit fullscreen mode

Get average of numbers

const avg = (...numbers) => numbers.reduce((a, b) => a + b, 0) / numbers.length;

// Usage
avg(1, 2, 3, 4, 5); // 3
Enter fullscreen mode Exit fullscreen mode

Validate email

This snippet validates an email using a regex.

const validateEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

// Usage
validateEmail("obama@gmail.com"); // true
Enter fullscreen mode Exit fullscreen mode

Validate object

This snippet validates an object using a rules object.

const validateObject = (object, rules) =>
    Object.keys(rules).every((key) => rules[key](object[key]));

// Usage
const rules = {
    name: (name) => name.length > 0,
    email: (email) => validateEmail(email),
    password: (password) => password.length > 0,
};

validateObject({ name: "", email: "", password: "" }, rules); // false
Enter fullscreen mode Exit fullscreen mode

Chunk array

Chunks the array into x length chunks.

const chunkArray = (array, chunkSize) =>
    [...Array(Math.ceil(array.length / chunkSize))].map((_, index) =>
        array.slice(index * chunkSize, (index + 1) * chunkSize)
    );

// Usage
chunkArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3); // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
Enter fullscreen mode Exit fullscreen mode

RGB to HEX

const rgbToHex = (r, g, b) =>
    "#" + ((r << 16) + (g << 8) + b).toString(16).padStart(6, "0");

// Usage
rgbToHex(255, 0, 0); // #ff0000
Enter fullscreen mode Exit fullscreen mode

Raw String to normal string

This is useful if you're having a situation like this:

formatFn("string") + formatFn("string");
Enter fullscreen mode Exit fullscreen mode

Instead of doing that, you can use the power of ES6's raw string syntax:

const f = (...args) => String.raw(...args); // This returns a normal string

formatFn(f`string` + f`string`);
Enter fullscreen mode Exit fullscreen mode

Compare two objects

const compareObjects = (obj1, obj2) => {
    const c = Object.keys(obj1),
        n = Object.keys(obj2);
    return c.length === n.length && c.every((c) => obj1[c] === obj2[c]);
};

// Usage
compareObjects({ a: 1, b: 2 }, { a: 1, b: 2 }); // true
Enter fullscreen mode Exit fullscreen mode

Get selected text

const getSelectedText = () => window.getSelection().toString();

// Usage
getSelectedText(); // Selected text
Enter fullscreen mode Exit fullscreen mode

Get object of query params in the url

const getQueryParams = (url) => new URLSearchParams(url.split("?")[1]);

// Usage
getQueryParams("https://example.com?a=1&b=2"); // { a: "1", b: "2" }
Enter fullscreen mode Exit fullscreen mode

Convert number to word

Converts large numbers like 1000000 to "1M".

const numToWord = (number) =>
    number.toLocaleString("en-US", { notation: "compact" });

// Usage
numToWord(1000000); // "1M"
Enter fullscreen mode Exit fullscreen mode

Count number of duplicates in array

Returns an object with the number of duplicates in the array.

const countDuplicates = (c) => {
    const t = {};
    return c.forEach((c) => (t[c] = (t[c] || 0) + 1)), t;
};

// Usage
countDuplicates([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); // { 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1 }
Enter fullscreen mode Exit fullscreen mode

Generate tree from depth

If you need some testing JSON, you can use this snippet to generate a tree of depth depth.

const generateTree = (depth) =>
    [...Array(depth)].map(() => ({ tree: generateTree(depth - 1) }));

// Usage
generateTree(3); // [{ tree: [{ tree: [{ tree: [] }, { tree: [] }] }, { tree: [{ tree: [] }, { tree: [] }] }] }, { tree: [{ tree: [] }, { tree: [] }] }]
Enter fullscreen mode Exit fullscreen mode

Conclusion

That's all folks! I hope you find this useful.

Find me on GitHub and Twitter.

Top comments (0)