javascript-one-liner-snippets

Amazing JavaScript One-liner Snippets to Code like a Pro developer

These JavaScript One-liner Snippets will make you a pro programmer. Try these snippets if you are a JavaScript developer.

One line code to swap two variables

By using the ES6 destructuring method in JavaScript, we can swap two values in one line without needing a transient variable.

let a = "AAA";
let b = "BBB";

[a, b] = [b, a];

// now  a = "BBB" and b = "AAA"

Copy text to clipboard

If you only need to support modern browsers, then the asynchronous Clipboard API is highly recommended. It’s compatible with all modern browsers and provides a simple and secure way to update the contents of the clipboard.

let copyText = async (text) => {
    await navigator.clipboard.writeText(text);
}

Use the above code like this:

let copyTxt = () => {

    var copyText = document.getElementById("input-field-id");

    copyText.select();

    navigator.clipboard
      .writeText(copyText.value)
      .then(() => {
        alert("text copied");
      })
      .catch(() => {
        alert("sorry text not copied");
      });
}

Check if the current tab is in focus or active

How to detect if the user has switched browser windows? Here is a simple solution in JavaScript.


const isFocused = () => !document.hidden; 
isFocused() // returns true or false

// or use if statement
if (!document.hidden) {
    // not hidden
}

Detect the Apple devices in JavaScript

Check the device if it is an Apple product or not. The following methods will return the result in boolean.

const appleProduct = () => /Mac|iphone|ipad/.test(navigator.platform);
appleProduct(); // returns true or false

Alternatively, you can detect the device like this.


const appleProduct = ['iPad', 'iPhone', 'iPod', 'MacIntel'].indexOf(navigator.platform) >= 0;

console.log(appleProduct)

Scroll to the top of the page

The window Interface’s scrollTo() method can be used to scroll to a specific position on the page. It takes two parameters: the x and y coordinates of the scrollable page.

When both parameters are set to 0, the page will be scrolled to the top and leftmost points.

Learn more on how to create the smooth scroll effect in CSS, JavaScript, and JQuery

const backToTop = window.scrollTo(0, 0);
backToTop(); // page scrolls to top

Generate a random string or unique ID

Generate a unique id in JavaScript. Specify the values (2 – 36) to get the generated unique value in the toString() method.


const uniqueString = () => Math.random().toString(30).slice(2);
uniqueString();

// something like 'gj9lmjcobik'

Merge arrays

Merge multiple arrays into one with the following two methods. You can use the contact() method or separate operator to achieve this.


const mergeArrays = (a, b) => a.concat(b);
const mergeArrays = (a, b) => [...a, ...b];
mergeArrays(a, b)

Merge and remove the duplicate items. The JavaScript Set does not contain duplicate values so convert newly merged values to sets and then back to arrays.


const mergeArrays = (a, b) => new Set(a.concat(b));
const mergeArrays = (a, b) => new Set([...a, ...b]);
const newArray = [...mergeArrays(a, b)];

Reverse a string

To reverse a string, you no longer need to use libraries. This snippet will help you reverse any string with just one line of code. Take a look at the code example below.


const reverseString = str => str.split("").reverse().join("");
console.log(reverseString('google')) // 'elgoog'

One-liner if Else Statment

In JavaScript, you’ve definitely used the if-else statement, which is basically multi-liner code. But did you know that an if-else statement can be written in only one line?


// normal code
if (a > b){
  console.log('A is greater');
}
else{
  console.log('B is greater')
}

// simple code
a > b ? console.log('A is greater') : console.log('B is greater')

Extract the domain name or username from the email address

There are many ways to extract the domain name or user name from the email address in Javascript. These are the simplest ways to get the domain name or user name from the email address. Use the substring or split method to extract the username or domain name.

Get Domain Name


let Email = "[email protected]";

// 1: Get Domain Name
let Domain = Email.substring(Email.indexOf("@")+1);
console.log(Domain); // example.com

// 2: Get The domain Name
let Domain = Email.split("@")[1];
console.log(Domain); // example.com

Get username


let Email = "[email protected]";

// 2: Get The Username
let Username = Email.split("@")[0];
console.log(Username); // username123

Detect the dark mode

With this code snippet, you can easily determine whether the current user is using the dark mode on the system or not.


let isDarkMode = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;

console.log(isDarkMode); // true or false

Check if an element is focused

The activeElement read-only property of the Document interface returns the Element within the DOM that currently has focus.


let el = document.querySelector('#element_id');
let isFocus = el == document.activeElement;
console.log(isFocus); // true or false


// test it
let el = document.querySelector('#emailAddress');

el.addEventListener('focus', () => {
let isFocus = el == document.activeElement;
console.log(isFocus); // true or false
});

If you want to find out the tag name which is currently active then the following code will help you.


let activeElement = document.activeElement.tagName;
console.log(activeElement); // something like BODY, INPUT etc.

Redirect a user to a specific URL

To acquire the current page address (URL) and to redirect the browser to a new page, use the window.location object. You can write the window objects without window.


window.location = "https://google.com";
OR
location = "https://google.com";

Check if a variable is an array

You can check if a variable is an array or not using Array.isArray() method.


const users = ["john", "mark", "bush", "mikel"];
let checkUsers = Array.isArray(users);
console.log(checkUsers); // true

// other examples
Array.isArray([1, 2, 3]); // true
Array.isArray({val: 55}); // false
Array.isArray('username'); // false
Array.isArray(undefined); // false

Check if an array is Empty

This is very simple to check whether the array is empty or not. Simply check the length of an array.


const users = ["john", "mark", "bush", "mikel"];
console.log(users.length > 0); // true (erray is not empty)

const users = [];
console.log(users.length > 0); // false (erray is empty)

AdBlocker Message

Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.