11 JavaScript One-Liners You Should Know

0


JavaScript is one of the most popular programming languages. It is used to develop websites, web applications, web servers, games, mobile applications, etc.


JavaScript syntax, especially its anonymous and arrow functions, allows concise code. You can do a lot of things with just one line of code.

In this article, you will learn about 11 JavaScript one-liners that will help you 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 there are variations. A camelCase string begins with a lowercase letter, with each subsequent word starting with an uppercase letter. There is no space or punctuation in a camelCase string.

Programming languages ​​and programmers use different case schemes for the names of variables and methods.

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 a 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));

Go out:

VIDEO OF THE DAY MAKEUSE
helloWorld
makeUseOf
thisIsAVariable

2. How to mix a JavaScript array

Mixing an array means randomly rearranging its elements. You can mix 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));

Go out:

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

You will get variable output through separate executions of this code.

Related: JavaScript Arrow Functions Can Make You A Better Developer

3. How to find the mean of an array

The average mean is the sum of the array elements 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));

Go out:

3
33.5
6

Related: How to Find the Average 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 line:


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

The statement will come back true if dark mode is running, if not, it will come back 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 come back true if your browser is running on an Apple device, if not, it will come back false.

Related: JavaScript Array Methods You Need To Master Today

6. How to check if an array is empty

An array is empty if it contains no elements. 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));

Go out:

false
true
false

7. How to find unique values ​​in an array

The next line removes repeating values ​​from an array, leaving only values ​​that occur once.

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));

Go out:

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

8. How to generate a random hexadecimal color

Hexadecimal colors are a way to represent colors using hexadecimal values. They follow the format #RRGGBB, or RR is red, GG is green, and BB is blue. The hexadecimal color values ​​range from 00 to FF, which specify the intensity of the component. You can generate random hexadecimal colors using the following JavaScript code:


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

Go out:

#ff7ea1

Every time you run the code you 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 from 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 from 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));

Go out:

6.283185307179586
3.141592653589793
2.0943951023931953

Convert radians to degrees

You can convert an angle from 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));

Go out:

360
180
119.99999999999999

10. How to check if the 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, executed in a browser, will print true. Executed via a command line interpreter, it will print false.


11. How to generate a random UUID

UUID stands for Universally Unique Identifier. It is 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());

Go out:

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

Every time you run the code, it generates a random UUID.

If you’d like to check out the full source code used in this article, here’s the GitHub repository.

Get practical knowledge about JavaScript by creating projects

The best way to master any programming language is to create projects. You can use the tips described in this article when developing JavaScript projects. If you’re a beginner and looking for project ideas, start by creating a simple project like a To-Do app, web calculator, or browser extension.



Code editor containing JavaScript code blocks

10 JavaScript Project Ideas For Beginners

JavaScript is a crucial programming language to learn. If you are a novice, here are some projects to help you deepen your knowledge.

Read more


About the Author


Share.

About Author

Comments are closed.