DEV Community

Cover image for 7 killer JavaScript One-Liners You Must Know 😎😎
Ashish donga
Ashish donga

Posted on

7 killer JavaScript One-Liners You Must Know 😎😎

top 7 best killer javascript one liners that you must know in your code journey

Generate random string

if you will ever need a temporary uniques id for something, this is one liner will generate a random string for you

const randomString = Math.random().toString(36).slice(2);
console.log(randomString)
Enter fullscreen mode Exit fullscreen mode

extract domain name from an email

you can use the substring() method to extract the domain name of the email

let email = 'admin@ashishdonga.me';
let getDomain = email.substring(email.indexOf('@') + 1);

console.log(getDomain)
Enter fullscreen mode Exit fullscreen mode

detect dark mode

with this one linera 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

*check if an element is focused *

to detect if the element has the focus in javascript, you can use the read only javascript property activeElement of the document object

const elem = document.querySelector('.text-input')
const isFocus = elem = document.activeElement;
Enter fullscreen mode Exit fullscreen mode

Redirecting User

you can redirect the user to any specific URL using Javascript

const redirect = url => location.href = url
Enter fullscreen mode Exit fullscreen mode

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); // false
console.log(isArray.fruits); //true
Enter fullscreen mode Exit fullscreen mode

check if an array is empty

this is 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(arra1);
console.log(arr2)
Enter fullscreen mode Exit fullscreen mode

read more

12 javascript pro snippet codes for everyday problems

What is difference between undefined & null in javascript ?

share this JavaScript One-Liners article with your friends

Top comments (1)

Collapse
 
monawwar profile image
Monawwar Abdullah

can you check check if a variable is an array code snippet again?