DEV Community

Cover image for 7 Killer JavaScript One-Liners that you must know
Kamran Ahmad
Kamran Ahmad

Posted on

7 Killer JavaScript One-Liners that you must know

1. Generate Random String
if you will ever need a temporary unique id for something. this
one-liner will generate a random string for you

const randomString = Math.random().toString(36).slice(2);
console.log(randomString); //output- r0zf1xfqcr (the string will be random )
Enter fullscreen mode Exit fullscreen mode

2. Extract Domain Name From An Email
you can use the substring() method to extract the domain name
of the email.

let email = 'xyz@gmail.com';
le getDomain = email.substring(email.indexOf('@') + 1);

console.log(getDomain); // output - gmail.com
Enter fullscreen mode Exit fullscreen mode

3. Detect Dark Mode
with this one-liner, you can check if the user is using dark mode ( and then you can update some functionality according to dark mode)

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').match;
Enter fullscreen mode Exit fullscreen mode

4. Check if An Element is Focused
to detect if the element has the focus in JavaScript, you can use the read-only property activeElement of the Document object.

const elem = document.querySelector(' .text-input');

const isFocus = elem == document.activeElemnt;

/* isFocus will be true if elem will have focus, and isFocus will be false if elem will not have focus */
Enter fullscreen mode Exit fullscreen mode

5. Check If An Array Is Empty
this one-liner will let you know if an array is empty or not.

let arr1 = [];
let arr2 = [2, 4, 6, 8, 10];

const arr1IsEmpty = !(Array.isArray(arr1) && arr1.length >0);
const arr2IsEmpty = !(Array.isArray(arr2) && arr2.length >0);

console.log(arr1); //output - true
console.log(arr2); // output - false
Enter fullscreen mode Exit fullscreen mode

6. Redirecting User
you can redirect the user to any specific URL using JavaScript.

const redirect = url => location.href = url

/* call redirect (url) whenever you want to redirect the user to a specific url */
Enter fullscreen mode Exit fullscreen mode

7. Check If A Variable Is An Array
You can check if any Variable is an Array or not using the Array.isArray() method.

let fruit = 'apple';
let fruits = ["apple", "banana", "mango", "orange", "grapes"];

const isArray = (arr) => Array.isArray(arr);

console.log(isArray.(fruit)); //output - false
console.log(isArray.(fruits)), //output- true
Enter fullscreen mode Exit fullscreen mode

Top comments (28)

Collapse
 
m0nm profile image
m0nm

Nice tips, but i think you made a mistake on the fifth tip. It should be like this:

console.log(arr1IsEmpty); //output - true
console.log(arr2IsEmpty); // output - false
Enter fullscreen mode Exit fullscreen mode
Collapse
 
remoharsono profile image
Remo Harsono

Thanks for sharing Kamran, here's my little one

Reverse date format and change the delimiter

let str = "2022-01-25";
console.log(str.split("-").reverse().join("/")); // output: 25/01/2022
Enter fullscreen mode Exit fullscreen mode
Collapse
 
othmanekahtal profile image
Othmane kahtal

Nice hacks bro
My favourite tip : select elements directly by id without getElementById
<h1 id='h1'></h1>
you can do to select element :
h1.style.Color instead document.getElementById('h1').style.Color

Collapse
 
ibrahimwehbi profile image
Ibrahim Wehbi

that's why it is a bad practice to use id(attribute) in HTML elements and that you should always use class(attribute), in larger scale applications you will face unpredictable behavior because Javascript will be filled with global variables

Collapse
 
ikamran01 profile image
Kamran Ahmad

nice bro that's great

Collapse
 
prakhart111 profile image
Prakhar Tandon

Want to add a "Killer" trick.

A function to check if a given positive integer is a power of 2

function isPowerofTwo(num){
     if( num & (num-1) == 0 ) return true;
return false;
}
Enter fullscreen mode Exit fullscreen mode

& used here is the Bitwise AND.

Collapse
 
jchlu profile image
Johnny C-L

This is what the modulus operator % is for. By negating the check, you return 1 (true) or 0 (false) with:
console.log(!num % 2)

Collapse
 
prakhart111 profile image
Prakhar Tandon

Modulus checks if the number is divisible by a number or not, It doesn't checks for exponent.

Collapse
 
lordshenk profile image
lordshenk

Nice tricks. The first one is cool.

Collapse
 
skotlindjames profile image
skotlindjames

KILLER INDEED

Collapse
 
arnavkr profile image
Arnav Kumar • Edited

Nice but there are some errors

like in tip 7
there should not be . after the isArray and there shouldn't be a , at the end it should be ;

fixed code

let fruit = 'apple';
let fruits = ["apple", "banana", "mango", "orange", "grapes"];

const isArray = (arr) => Array.isArray(arr);

console.log(isArray(fruit)); //output - false
console.log(isArray(fruits)); //output- true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
thumbone profile image
Bernd Wechner • Edited

Poe's Law (look it up if you need to it's an essential part of modern internet vocabulary)

As in surely, when I read this, I read it as a parody, a joke ...

Replacing this:

console.log(Array.isArray(fruit)); //output - false
Enter fullscreen mode Exit fullscreen mode

with this:

console.log(isArray(fruit)); //output - false
Enter fullscreen mode Exit fullscreen mode

is a killer one-liner indeed. Well the killer one-liner is in fact:

const isArray = (arr) => Array.isArray(arr);
Enter fullscreen mode Exit fullscreen mode

As in, it's one line, no-one needs (a killer).

And on a close inspection the errors aside (a hasty post it seems) they all seem to be in jest.

Collapse
 
prakhart111 profile image
Prakhar Tandon

Quite Helpful,
I would like to add something to the first one.
Math.random is not actually a very good way if you want to use it for generating an id, it's okay if you are using it for some personal project.

Thing is that these functions generate a pseudo random number.
I have explained about this Here in detail.

If you want to generate more "random" random values, you can check out the Crypto global Here on MDN

Cheers and following you now !

Collapse
 
andi1984 profile image
Andreas Sander

Side note: matchMedia is also very interesting for checking whether a certain media-query is matched or not. And also listening for changes.

Cf. developer.mozilla.org/en-US/docs/W...

Collapse
 
lexlohr profile image
Alex Lohr

Using location.href is bad for the testability, better use location.assign(url).

Collapse
 
alokikpathak profile image
Alokik Pathak

Cool...

Get unique items of array

const arrayWithDuplicate = [1,1,2,3,3,4,4,1];
const arrayWithoutDuplicate = [...new Set(arrayWithDuplicate)]; // [1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

Get common items between two array

const arr1 = [3,2,4,5,2];
const arr2 = [3,6,8,23,4];
const arrayWithCommonItem = [...new Set(arr1)].filter(x => arr2.includes(x)); // [3,4]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ironcladdev profile image
Conner Ow

Very nice tips! I really enjoy javascript one-liners and how useful and effective they are!

I believe to get the url of an email, an easier way is const emailUrl = email => email.split("@")[1]

Collapse
 
basharath profile image
Basharath

Hey, while inserting the code blocks, indicate the language so that it would be nicely highlighted.

```js -> this line


Enter fullscreen mode Exit fullscreen mode
Collapse
 
pierre profile image
Pierre-Henry Soria ✨

Thanks for sharing this Jamran 😊

Collapse
 
athifbinu profile image
Athif binu

Thanks for share at that valuable information.