JavaScript is one of the most popular programming languages. It's used to develop websites, web applications, web servers, games, mobile apps, and more.JavaScript's syntax, particularly its anonymous and arrow functions, allows for concise code. You can achieve a lot with just a single line of code.In this article, you'll learn about 11 JavaScript one-liners that will help you to code like a pro.

1. How to Convert a String From snake_case to camelCase

A string in snake_case uses the underscore character to separate each word. Each word in a snake_case string usually begins with a lowercase letter, although variants exist. A camelCase string begins with a lowercase letter, each following word beginning with an uppercase letter. There are no intervening spaces or punctuation in a camelCase string.

Programming languages—and programmers—use different casing schemes for variable and method names.

Examples of snake_case strings: hello_world, this_is_a_variable, SCREAMING_SNAKE_CASE

Examples of camelCase strings: helloWorld, thisIsVariable, makeUseOf

You can convert a snake_case string to camelCase using the following code:

        const convertSnakeToCamel = (s) => s.toLowerCase().replace(/(_\w)/g, (w) => w.toUpperCase().substr(1));
 
let s1 = "hello_world";
console.log(convertSnakeToCamel(s1));
 
let s2 = "make_use_of";
console.log(convertSnakeToCamel(s2));
 
let s3 = "this_is_a_variable";
console.log(convertSnakeToCamel(s3));

Output:

        helloWorld
makeUseOf
thisIsAVariable

2. How to Shuffle a JavaScript Array

Shuffling an array means randomly rearranging its elements. You can shuffle a JavaScript array using the following code:

        const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
 
let arr1 = [1, 2, 3, 4, 5];
console.log(shuffleArray(arr1));
 
let arr2 = [12, 34, 45, 43];
console.log(shuffleArray(arr2));
 
let arr3 = [2, 4, 6, 8, 10];
console.log(shuffleArray(arr3));

Output:

        [ 3, 5, 1, 4, 2 ]
[ 45, 34, 12, 43 ]
[ 4, 10, 2, 6, 8 ]

You'll get varying output across separate runs of this code.

Related: JavaScript Arrow Functions Can Make You a Better Developer

3. How to Find the Average of an Array

The mean average is the sum of the elements of the array divided by the number of elements. You can find the average of an array in JavaScript using the following code:

        const calculateAverage = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;
 
let arr1 = [1, 2, 3, 4, 5];
console.log(calculateAverage(arr1));
 
let arr2 = [12, 34, 45, 43];
console.log(calculateAverage(arr2));
 
let arr3 = [2, 4, 6, 8, 10];
console.log(calculateAverage(arr3));

Output:

        3
33.5
6

Related: How to Find the Mean of an Array in Python, C++, JavaScript, and C

4. How to Detect Dark Mode Using JavaScript

With code running in a web browser, you can detect dark mode using the following one-liner:

        const darkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
console.log(darkMode);

The statement will return true if dark mode is running, otherwise, it'll return false.

5. How to Detect an Apple Browser Using JavaScript

You can check if the browser is running on an Apple computer using this simple regular expression match:

        const appleBrowser = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(appleBrowser);

The statement will return true if your browser is running on an Apple device, otherwise, it'll return false.

Related: JavaScript Array Methods You Should Master Today

6. How to Check if an Array Is Empty

An array is empty if there are no elements in it. You can check if an array is empty using the following code:

        const checkEmptyArray = (arr) => !Array.isArray(arr) || arr.length === 0;
 
let arr1 = [1, 2, 3, 4, 5];
console.log(checkEmptyArray(arr1));
 
let arr2 = [];
console.log(checkEmptyArray(arr2));
 
let arr3 = [""];
console.log(checkEmptyArray(arr3));

Output:

        false
true
false

7. How to Find Unique Values in an Array

The following one-liner removes repeating values from an array, leaving only values that occur just a single time.

        const findUniquesInArray = (arr) => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));
 
let arr1 = [1, 2, 3, 4, 5, 1, 2, 3];
console.log(findUniquesInArray(arr1));
 
let arr2 = ['W', 'E', 'L', 'C', 'O', 'M', 'E', 'T', 'O', 'M', 'U', 'O'];
console.log(findUniquesInArray(arr2));
 
let arr3 = [5, 5, 5, 3, 3, 4, 5, 8, 2, 8];
console.log(findUniquesInArray(arr3));

Output:

        [ 4, 5 ]
[ 'W', 'L', 'C', 'T', 'U' ]
[ 4, 2 ]

8. How to Generate a Random Hex Color

Hex colors are a way of representing colors through hexadecimal values. They follow the format #RRGGBB, where RR is red, GG is green, and BB is blue. The values of hexadecimal colors are in the range from 00 to FF, which specify the intensity of the component. You can generate random hex colors using the following JavaScript code:

        const randomHexColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;
console.log(randomHexColor());

Output:

        #ff7ea1
    

Each time when you run the code, you'll get a random hex color.

9. How to Convert Degrees to Radians and Vice-Versa

Degrees and Radians represent the measure of an angle in geometry. You can easily convert an angle in radians to degrees, and vice-versa, using the following mathematical formulas:

        Radians = Degrees × π/180
Degrees = Radians × 180/π

Convert Degrees to Radians

You can convert an angle in degrees to radians using the following code:

        const degreesToRadians = (deg) => (deg * Math.PI) / 180.0;
 
let temp1 = 360;
console.log(degreesToRadians(temp1));
 
let temp2 = 180;
console.log(degreesToRadians(temp2));
 
let temp3 = 120;
console.log(degreesToRadians(temp3));

Output:

        6.283185307179586
3.141592653589793
2.0943951023931953

Convert Radians to Degrees

You can convert an angle in radians to degrees using the following code:

        const radiansToDegrees = (rad) => (rad * 180) / Math.PI;
 
let temp1 = 6.283185307179586;
console.log(radiansToDegrees(temp1));
 
let temp2 = 3.141592653589793;
console.log(radiansToDegrees(temp2));
 
let temp3 = 2.0943951023931953;
console.log(radiansToDegrees(temp3));

Output:

        360
180
119.99999999999999

10. How to Check if Code Is Running in a Browser

You can check if your code is running in a browser using the following:

        const isRunningInBrowser = typeof window === 'object' && typeof document === 'object';

console.log(isRunningInBrowser);

The above code, running in a browser, will print true. Running via a command-line interpreter, it will print false.

11. How to Generate a Random UUID

UUID stands for Universally Unique Identifier. It's a 128-bit value used to uniquely identify an object or entity on the internet. Use the following code to generate a random UUID:

        const generateRandomUUID = (a) => (a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, generateRandomUUID));
console.log(generateRandomUUID());

Output:

        209b53dd-91cf-45a6-99a7-554e786f87d3
    

Each time when you run the code, it generate a random UUID.

If you want to have a look at the complete source code used in this article, here's the GitHub repository.

Get Hands-On JavaScript Knowledge by Building Projects

The best way to master any programming language is by building projects. You can use the short-hand tricks described in this article while developing JavaScript projects. If you're a beginner and looking for some project ideas, start by building a simple project like a To-Do app, web calculator, or browser extension.