There are more than 10 million Javascript developers in the world, and this number is increasing every day. Although JavaScript is better known for its dynamic nature, it also has many other great features. In this blog, we will see 20 JavaScript one-liner programs you should know.
1. Random ID generation
This can be your preferred feature when you are prototyping and need a unique id.
const a = Math.random().toString(36).substring(2);
console.log(a)
----------------------------
72pklaoe38u
2. Generate random numbers within the range
In many cases, we need to generate a random number in a range. Math.random
function can help us generate random numbers and then convert them to the required range.
max = 20
min = 10
var a = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(a)
-------------------------
17
3. Randomly arrange the array (shuffle)
In JavaScript, we don't have a module, because python has random.shuffle()
, but there is still a way to shuffle an array in one line of code.
var arr = ["A", "B", "C","D","E"];
console.log(arr.slice().sort(() => Math.random() - 0.5))
------------------------------
[ 'C', 'B', 'A', 'D', 'E' ]
4. Get random boolean values
The Math.random
function in Javascript can be used to generate random numbers between ranges. To generate a random Boolean value, we need to randomly get a number between 0 and 1, and then check if it is greater than or less than 0.5.
const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
---------------------------------------
false
5. Generate a random hexadecimal code
You can use this one-line program to challenge your abilities as a web developer. This one-line program will generate a random hexadecimal code. You can use a one-line program to generate 3-6 color codes, which will create a color pallet for you.
console.log('#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0'));
------------------1st Run------------
#48facd
------------------2nd Run-------------
#93d806
------------------3rd Run-------------
#9072f9
6. Reverse the string
There are many ways to reverse a string, but this is one of the easiest ways I found on the Internet.
const reverse = str => str.split('').reverse().join('');
console.log(reverse('javascript'));
----------------------------------------
tpircsavaj
7. Swap two variables
The following code shows some simple ways to exchange two variables without using the third variable, only one line of code.
a = 5
b = 7
---------方法 1---------
b = [a, a = b][0]; // One Liner
----------方法 2-----------
[a,b] = [b,a];
console.log("A=",a)
console.log("B=",b)
8. Multivariate allocation
Like Python, JavaScript can also use this clever deconstruction technique to assign multiple variables in the same line of code at the same time.
var [a,b,c,d] = [20,14,30,"COD"]
console.log(a,b,c,d)
------------------------------------
20 14 30 COD
9. Check even and odd numbers
There are many ways to do this, one of the easiest is to use arrow functions and write the entire code in just one line.
const isEven = num => num % 2 === 0;
console.log(isEven(2));
---------------------------------
true
console.log(isEven(3));
----------------------------------
false
10.FizzBuzz
This question is one of the famous interview questions used to check the core of programmers. In this test, we need to write a program to print numbers from 1 to 100. But if it is a multiple of 3, it prints "Fizz" instead of a number, and if it is a multiple of 5, it prints "Buzz".
for(i=0;++i<10;console.log(i%5?f||i:f+'Buzz'))f=i%3?'':'Fizz'
----------------------------------
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
11. Palindrome
A palindrome is a string or number that looks exactly the same when it is reversed. For example: abba, 121, etc.
const isPalindrome = str => str === str.split('').reverse().join('');
result = isPalindrome('abcba');
console.log(result)
-----------------------------------
true
result = isPalindrome('abcbc');
console.log(result)
---------------------------------
false
12. Check whether all elements in the array meet certain conditions
const hasEnoughSalary = (salary) => salary >= 30000
const salarys = [70000, 19000, 12000, 30000, 15000, 50000]
result = salarys.every(hasEnoughSalary)
console.log(result)
-------------------------------
false
const salarys = [70000, 190000 ,120000, 30000, 150000,50000]
result = salarys.every(hasEnoughSalary) // Results in false
console.log(result)
---------------------------------
true
13. Calculate the number of days between two given dates
const days = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (86400000));
result = days(new Date('2020-04-15'), new Date('2021-01-15'));
console.log(result)
--------------------------------------------------------
275
To calculate the number of days between two dates, we first find the absolute value between the two dates, then divide it by 86400000, which is equal to the number of milliseconds in a day, and finally, we round up and return the result.
14. Convert a string to a number
A very simple way to convert a string to a number is to use type conversion.
toNumber = str => +str;
toNumber = str => Number(str);
result = toNumber("2");
console.log(result)
console.log(typeof(result))
----------------------------------
2
number
15. Combine multiple arrays
const cars = ['🚓', '🚗'];
const trucks = ['🚚', '🚛'];
----- 方法 1 -------
const combined = cars.concat(trucks);
console.log(combined)
--------------------------------------------------
[ '🚓', '🚗', '🚚', '🚛' ]
----- 方法 2 --------
const combined = [].concat(cars,trucks);
console.log(combined)
--------------------------------------------------
[ '🚓', '🚗', '🚚', '🚛' ]
16. Truncate the number to a fixed decimal point
With the help of Math.pow()
you can truncate numbers to a certain decimal point.
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
-----------------------------------------------------------------
toFixed(25.198726354, 1); // 25.1
toFixed(25.198726354, 2); // 25.19
toFixed(25.198726354, 3); // 25.198
toFixed(25.198726354, 4); // 25.1987
toFixed(25.198726354, 5); // 25.19872
toFixed(25.198726354, 6); // 25.198726
17. Scroll to the top of the page
window.scrollTo()
method can help you complete the task. It needs to scroll to the x and y coordinates of that position on the page. If you set them to (0,0), it will scroll to the top of the page.
const goToTop = () => window.scrollTo(0, 0);
goToTop();
18.Convert Fahrenheit to Celsius (and vice versa)
Regardless of whether you choose Fahrenheit or Celsius, it is always a better idea to convert all temperature parameters into one unit.
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
--------Examples-------
celsiusToFahrenheit(15); // 59
celsiusToFahrenheit(-20); // -4
fahrenheitToCelsius(59); // 15
fahrenheitToCelsius(32); // 0
19. The value of a specific cookie
cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_ga');
// Result: "GA1.3.974792242.1509957189"
20. Copy text to clipboard
Copying text to the clipboard is very useful and a difficult problem to solve. You can find various solutions on the Internet, but the solution below may be one of the smallest and smartest.
const copyTextToClipboard = async (text) => {
await navigator.clipboard.writeText(text)
}
21. Remove HTML tags
This one-line code uses regular expressions to delete any string that <xxx>
x
can be any character, including /
"<b>A</b>".replace(/<[^>]+>/gi, "");
22. Clone the array
It will return a copy of the original array.
oldArray = [1,4,2,3]
var newArray = oldArray.slice(0);
console.log(newArray)
------------------------------------
[1,4,2,3]
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。