6 One Liners Hacks in Javascript Part-2

Introduction

Last year, I shared a series of "One Liner Hacks In JavaScript" that proved invaluable for many developers. Now, I'm excited to present a fresh collection of concise JavaScript tricks that promise to streamline your coding process and enhance efficiency in your projects. These one-liners are designed to save you time and effort, offering elegant solutions to common programming challenges. Let's dive into these powerful hacks and discover how they can elevate your JavaScript development experience.

  • Shorten the Console.log()
  • Palindrome Check
  • Sort Alphabetically
  • Unique Elements
  • Generate Random Color
  • Swap the variables

1. Shorten the Console.log()

Tired of writing console.log() again and again? This tip will show you how to shorten your console.log() and speed up your writing.

var con=console.log.bind(document);

Output

Console

2. Palindrome Check

This short-line code trick will help you to find if a string is palindrome or not.

function palindrome(str){
    return str === str.split('').reverse().join('')
}

console.log(palindrome('mom')) // true
console.log(palindrome('12321')) // true
console.log(palindrome('1234')) // false

3. Sort Alphabetically

Sort is a common problem in programming and this tip will save you a lot of time while sorting alphabetically.

function alphabetSort(arr){
    return arr.sort((a,b) => a.localeCompare(b));
}

let array=["d","c","a","e","b"]

Output

Array

4. Unique Elements

Every language has its own implementation of a hash list. in javascript we have Set, you can easily get unique elements from an array using the set data structure.

const getUnique = (arr) => [...new Set(arr)];
const arr=[1,1,2,3,1,2,4,6,1,2,5,4,4,3,3];

Output

Log

5. Generate Random Color

The simplest way to generate a random color.

function generatecolor(){
return '#' + Math.floor(Math.random() * (256 * 256 * 256)).toString(16).padStart(6,'0');
}

Output

>

Generator

6. Swap the variables

You probably swap the two variables using the third variable temp, this trick will show you to swap the two variables using destructuring in javascript.

var a=6,b=7;
[a,b]=[b,a]

Output

Output

Conclusion

In the world of JavaScript development, every line of code counts. The one-liner hacks presented here are not just shortcuts. They're tools that can significantly enhance your productivity and streamline your workflow. By incorporating these concise solutions into your projects, you'll not only save time and effort but also elevate the quality and efficiency of your code. So, embrace these one-liners and unleash their transformative potential in your JavaScript project.