Skip to main content

Command Palette

Search for a command to run...

20 Killer JavaScript One Liners โ˜๏ธ

Super handy one line snippets to make your life easier

Published
โ€ข4 min read
20 Killer JavaScript One Liners โ˜๏ธ
S

Savio Martin is a 14 year old who spends time building useful products. He is a designer, front-end web developer, and content creator.

Hello Folks ๐Ÿ‘‹

This is Savio here. I'm young dev with an intention to enhance as a successful web developer. I love building web apps with React. I have proved my superiority in frontend technologies.

Today, I'd like to share 20 Killer JavaScript one liners to make your life easier. Let's goooo ๐Ÿš€


Retrieve the value of a cookie by accessing with document.cookie

cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();

cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"

Convert RGB to Hex

const rgbToHex = (r, g, b) =>
  "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(0, 51, 255); 
// Result: #0033ff

Copy to Clipboard

Easily copy any text to clipboard using navigator.clipboard.writeText.

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

copyToClipboard("Hello World");

Check if Date is Valid

Use the following snippet to check if a given date is valid or not.

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid("December 17, 1995 03:24:00");
// Result: true

Find the day of year

Find which is the day by a given date.

const dayOfYear = (date) =>
  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date());
// Result: 272

Capitalise a String

Javascript doesn't have an inbuilt capitalise function, so we can use the following code for the purpose.

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

capitalize("follow for more")
// Result: Follow for more

Find the number of days between two days

Find the days between 2 given days using the following snippet.

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)

dayDif(new Date("2020-10-21"), new Date("2021-10-22"))
// Result: 366

Clear All Cookies

You can easily clear all cookies stored in a web page by accessing the cookie using document.cookie and clearing it.

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));

Generate Random Hex

You can generate random hex colors with Math.random and padEnd properties.

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;

console.log(randomHex());
// Result: #92b008

Remove Duplicated from Array

You can easily remove duplicates with Set in JavaScript. Its a life saver.

const removeDuplicates = (arr) => [...new Set(arr)];

console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// Result: [ 1, 2, 3, 4, 5, 6 ]

Get Query Params from URL

You can easily retrieve query params from a url either by passing window.location or the raw URL goole.com?search=easy&page=3

const getParameters = (URL) => {
  URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
  return JSON.stringify(URL);
};

getParameters(window.location)
// 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 => date.toTimeString().slice(0, 8);

console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// Result: "17:30:00"

Check if a number is even or odd

const isEven = num => num % 2 === 0;

console.log(isEven(2)); 
// Result: True

Find Average of Numbers

Find the average between multiple numbers using reduce method.

const average = (...args) => args.reduce((a, b) => a + b) / args.length;

average(1, 2, 3, 4);
// Result: 2.5

Scroll to Top

You can use window.scrollTo(0, 0) method to automatic scroll to top. Set both x and y as 0.

const goToTop = () => window.scrollTo(0, 0);

goToTop();

Reverse a string

You can easily reverse a string using split, reverse and join methods.

const reverse = str => str.split('').reverse().join('');

reverse('hello world');     
// Result: 'dlrow olleh'

Check if array is empty

Simple one liner to check if an array is empty, will return true or false.

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;

isNotEmpty([1, 2, 3]);
// Result: true

Get Selected Text

Get the text the user has select using inbuilt getSelection property.

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

getSelectedText();

Shuffle an Array

Shuffling an array is super easy with sort and random methods.

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

console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]

Detect Dark Mode

Check if a user's device is in dark mode with the following code.

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

console.log(isDarkMode) // Result: True or False

๐Ÿ‘€ Wrapping Up

Yeah, that's a wrap. Hope you enjoyed the article. Do not hesitate to share your feedback. I am on Twitter @saviomartin7. Give a follow!

Follow me on Github @saviomartin, Don't miss my amazing projects! ๐Ÿ’ฏ

Feedbacks are greatly appreciated! ๐Ÿ™Œ Have an amazing day!

๐ŸŒŽ Lets connect

D
Dave Bray3y ago

Hey Savio - loved your one liners and used the isDateValid one ... until

On iOS new Date('2009-10-11 11:01:01') is Invalid

on Chrome new Date('2009-10-11 11:01:01') Sun Oct 11 2009 11:01:01 GMT+1000 (Australian Eastern Standard Time)

clearly I'm in Oz ...

It's hard to debug iOS as I use Win11

cheers

S

I saw many young guys wasting their time by bing watch which is not useful and you are awesome. Great Job!! all the best for fantastic future.Savio Martin

I think minor typo at very first heading "Get Value of a brower Cookie" should be browser

M

Excellent write-up, Savio. You can find a few more JavaScript tips here.

Thanks for the efforts!

A

Excellent Work Savio Martin

2
S

Thank you buddy, makes me motivated to write more in this series. Surely more killer one liners coming soon here! ๐ŸŽ‰๐Ÿ”ฅ

A

Good job, I really like the list!

I have recently played with window.getSelection(); and if you are using it in an .addEventListener('click'=>{}); function and you click on a non-text area, you will always get the first element that is in the horizontal line of the window. That happens because the caret is always at the start of the window and will give you the next element that is in the line since it counts it as selected.

I found that a bit unexpected but it works like that. Keep up the good work!

1
S

Thanks mate, you're a genius. Keep it up!

1
A

Great! covered diverse areas.

1
S

Thank you so much buddy, means a lot ๐ŸŽ‰

A

Nice blog bro.

Plus I love this page's light theme more than the dark one.

1
S

Thank you mate. Same for me, I love this site's light theme more. I should work more on the dark theme.

1
A

Savio Martin You could try using the darker shades of the colours you have used for the light theme.