Open in app Get started
Mertcan Arguç · Follow
Dec 23, 2021 · 3 min read
15 Javascript codes you will always need
Shuffle an Array
Shuffling an array is super easy with sort and random methods.
const shuffleArray = (arr) => [Link](() => 0.5 - [Link]());
[Link](shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]
Check if Date is Valid
Open in app Get started
Use the following snippet to check if a given date is valid or not.
const isDateValid = (...val) => .valueOf());
isDateValid("December 17, 1995 [Link]");
// Result: true
Copy to Clipboard
Easily copy any text to clipboard using [Link] .
const copyToClipboard = (text) => [Link](text);
copyToClipboard("Hello World");
Find the day of the year
Find which is the day by a given date.
const dayOfYear = (date) =>
[Link]((date - new Date([Link](), 0, 0)) / 1000 / 60 /
60 / 24);
dayOfYear(new Date());
// Result: 272
Capitalize a String
Javascript doesn’t have an inbuilt capitalize function, so we can use the following code for
this purpose.
const capitalize = str => [Link](0).toUpperCase() + [Link](1)
capitalize("follow for more")
// Result: Follow for more
Open in app Get started
Find the number of days between two days
Find the days between 2 given days using the following snippet.
const dayDif = (date1, date2) => [Link]([Link]([Link]() -
[Link]()) / 86400000)
dayDif(new Date("2020-10-21"), new Date("2021-10-22"))
// Result: 366
Clear All Cookies
You can easily clear all cookies stored on a web page by accessing the cookie using
[Link] and clearing it.
const clearCookies = [Link](';').forEach(cookie =>
[Link] = [Link](/^ +/, '').replace(/=.*/,
`=;expires=${new Date(0).toUTCString()};path=/`));
Generate Random Hex
You can generate random hex colors with [Link] and padEnd properties.
const randomHex = () => `#${[Link]([Link]() *
0xffffff).toString(16).padEnd(6, "0")}`;
[Link](randomHex());
// Result: #92b008
Remove Duplicated from Array
You can easily remove duplicates with Set in JavaScript. It's a lifesaver.
const removeDuplicates = (arr) => [...new Set(arr)];
[Link](removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// Result: [ 1, 2, 3, 4, 5, 6 ]
Open in app Get started
Get Query Params from URL
You can easily retrieve query params from a URL either bypassing [Link] or the
raw URL [Link]?search=easy&page=3
const getParameters = (URL) => {
URL = [Link]('{"' + decodeURI([Link]("?")[1]).replace(/"/g,
'\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
return [Link](URL);
};
getParameters([Link])
// Result: { search : "easy", page : 3 }
Log Time from Date
We can log time, in the format hour::minutes::seconds from a given date.
const timeFromDate = date => [Link]().slice(0, 8);
[Link](timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
// Result: "[Link]"
Check if a number is even or odd
const isEven = num => num % 2 === 0;
[Link](isEven(2));
// Result: True
Find Average of Numbers
Find the average between multiple numbers using reduce method.
const average = (...args) => [Link]((a, b) => a + b) /
[Link];
Open in app Get started
average(1, 2, 3, 4);
// Result: 2.5
Check if the array is empty
A simple one-liner to check if an array is empty, will return true or false .
const isNotEmpty = arr => [Link](arr) && [Link] > 0;
isNotEmpty([1, 2, 3]);
// Result: true
Get Selected Text
Get the text the user has selected using inbuilt getSelection property.
const getSelectedText = () => [Link]().toString();
getSelectedText();
Detect Dark Mode
Check if a user’s device is in dark mode with the following code.
const isDarkMode = [Link] && [Link]('(prefers-
color-scheme: dark)').matches
[Link](isDarkMode) // Result: True or False
Buy me a coffee [Link] 🧋