• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Top JavaScript Utility Snippets Every Developer Should Bookmark

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Hello my frontend developer friends, today i will be sharing some useful utilities to avoid repeating code and boost productivity. These snippets are often used in many projects and saves a lots of time doing the same thing again and again in multiple files.

  • I'll be creating my code snippets on

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

    first, which is a fantastic platform that allows you to run a JavaScript Notebook, Online Compiler, and Editor without the need for manual setup.
  • Additionally, I am including a

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

    to code snippets that includes all of the code examples so you can open the snippet and run it yourself to see the results.
  • I will be using scrib.show from scribbler.live, it is equivalent to console.log

Lets dive in...
Table of contents

  • Generate a random integer between min and max
  • Get time ago (e.g., "4 hours ago")
  • Format date to YYYY-MM-DD
  • Remove duplicates
  • Flatten nested arrays
  • Shuffle array
  • Get the intersection of two arrays
  • Capitalize first letter
  • Slugify a string to create a hyphenated url slug
  • Truncate a string
  • Validating an email
  • Check if an object is empty
  • Get query params from URL
  • Serialize object to query string
  • Checking for leap year
  • Remove Falsy Values
  • Count Occurrences in Array
  • Find Duplicates in Array
  • Check if Value is Numeric
  • Pick specific keys from an object


1. Generate a random integer between min and max


It is useful if you want to create a random id for some object in the data.


// 1. Generate a random integer between min and max
const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
scrib.show(randomInt(100,100000))


2. Get time ago (e.g., "4 hours ago")


It is useful to show when a person was online in a chat app or could be used to show when a file was last updated.


// 2. Get time ago (e.g., "4 hours ago")
const timeAgo = date => {
const diff = (new Date() - new Date(date)) / 1000;
const units = [
['year', 31536000], ['month', 2592000],
['day', 86400], ['hour', 3600],
['minute', 60], ['second', 1]
];
for (let [unit, sec] of units) {
const val = Math.floor(diff / sec);
if (val >= 1) return `${val} ${unit}${val > 1 ? 's' : ''} ago`;
}
return 'just now';
};
scrib.show(timeAgo("2025/05/12"))


3. Format date to YYYY-MM-DD


It is useful to convert the date coming from an api to yyyy-mm-dd format for UI.


// 3. Format date to YYYY-MM-DD
const formatDate = date => new Date(date).toISOString().split('T')[0];
scrib.show(formatDate("2025/05/12"))


4. Remove duplicates


It could be used to remove duplicate values from an array to make it valid and corrected.


// 4. Remove duplicates
const unique = arr => [...new Set(arr)];
scrib.show(unique([1,1,2,2,2,3,4,5,5,9]))


5. Flatten nested arrays


It could be used to flatten a multi dimensional array to single level array to map over its values.


// 5. Flatten nested arrays
const flatten = arr => arr.flat(Infinity);
scrib.show(flatten([1,1,[2,2,2],[3,4,[5]],5,9]))


6. Shuffle array


It could be used to shuffle the UI list every time a user visit the page.


// 6. Shuffle array
const shuffle = arr => arr.sort(() => Math.random() - 0.5);
scrib.show(shuffle([1,1,2,2,2,3,4,5,5,9]))


7. Get the intersection of two arrays


It could be used to compare 2 lists for a difference.


// 7. Get the intersection of two arrays
const intersect = (a, b) => a.filter(x => b.includes(x));
scrib.show(intersect([1,2,3,4],[1,3,4,5]))


8. Capitalize first letter


Captilizing the first letter of the word in UI


// 8. Capitalize first letter
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
scrib.show(capitalize("mysterio"))


9. Slugify a string to create a hyphenated url slug


Creating a hyphenated slug for the url from strings.


// 9. Slugify a string to create a hyphenated url slug
const slugify = str => str.toLowerCase().trim().replace(/\s+/g, '-').replace(/[^\w\-]+/g, '');
scrib.show(slugify("products and services")) // products-and-services


10. Truncate a string


It could be used for adding elipsis in UI after a speicific word count reaches in the content


// 10. Truncate a string
const truncate = (str, len) => str.length > len ? str.slice(0, len) + '...' : str;
scrib.show(truncate("Web development has many frameworks", 25))


11. Validating an email


It could be used to validate an email and return a boolean whether the text passes the validation


// 11. Validating an email
const isEmail = str => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str); // replace regex with your regex
scrib.show(isEmail("mysterio09@gmail.com"))


12. Check if an object is empty


It could be used to add a conditional to check for the empty objects before proceeding with the actual logic.


// 12. Check if an object is empty
const isEmptyObject = obj => Object.keys(obj).length === 0;
scrib.show(isEmptyObject({})) // true
scrib.show(isEmptyObject({ name: "Mysterio" })) // false


13. Get query params from URL


Extracting out query params from url to an object


// 13. Get query params from URL
const getQueryParams = url => Object.fromEntries(new URL(url).searchParams.entries());
const url = "

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

";
scrib.show(getQueryParams(url)) // { "name": "mysterio", "age": "24", "country": "India" }


14. Serialize object to query string


This is the opposite of above example, here we create a query param from an object.


// 14. Serialize object to query string
const toQueryString = obj => new URLSearchParams(obj).toString();
const person = { "name": "mysterio", "age": "24", "country": "India" }
scrib.show(`

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

{toQueryString(person)}`)


15. Checking for leap year


It could be used in the logic where we are applying conditions based on number days like a discount.


// 15. Checking for leap year
const isLeapYear = year => new Date(year, 1, 29).getDate() === 29;
scrib.show(isLeapYear("2025-05-15"))


16. Remove Falsy Values


Removing falsy values like false, undefined, 0, null, "", etc.


// 16. Remove Falsy Values
const compact = arr => arr.filter(Boolean);
scrib.show(compact([false, undefined, null, 0, 1, 2, 3]))


17. Count Occurrences in Array


Categorising values in an array for more than 1 occurence.


// 17. Count Occurrences in Array
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
scrib.show(countOccurrences([1,1,2,2,2,3,4,5,5,9], 2))


18. Find Duplicates in Array


Find duplicates value in an array


// 18. Find Duplicates in Array
const findDuplicates = arr => {
return [...new Set(arr.filter((item, index) => arr.indexOf(item) !== index))];
};
scrib.show(findDuplicates([1,1,2,2,2,3,4,5,5,9]))


19. Check if Value is Numeric


Useful when we want to add a conditional to check for the type of value and proceed doing numeric calculations if the value is numeric.


// 19. Check if Value is Numeric
const isNumeric = val => !isNaN(parseFloat(val)) && isFinite(val);
scrib.show(isNumeric(NaN)) // false
scrib.show(isNumeric("24s")) // false
scrib.show(isNumeric("24")) // true
scrib.show(isNumeric(24)) // true
scrib.show(isNumeric(24.45)) // true


20. Pick specific keys from an object


Useful when you don't want the entire object and want only specific parts of it


// 20. Pick specific keys from an object
const pick = (obj, keys) =>
keys.reduce((acc, key) => {
if (key in obj) acc[key] = obj[key];
return acc;
}, {});
const person = { "name": "mysterio", "age": "24", "country": "India" }
scrib.show(pick(person, ["name", "age"]))

That's it for this post, Let me know if i could do any improvements in this article. Also, do check

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

website.

You can contact me on -


Instagram -

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.


LinkedIn -

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.


Email - shubhmtiwri00@gmail.com

You can help me with some donation at the link below Thank you??

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Also check these posts as well


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.




Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу