JavaScript is undoubtedly the crucial pillar of web development. If you build all the functionalities in your web applications using JavaScript from scratch, then you need to know some syntax and built-in methods. These JavaScript one-liners are highly functional and can quickly reduce the number of lines in your code.
In this post, we are exploring the simple JavaScript one-line code statements that can simplify your code to a great extent. Let’s look at the most commonly used JavaScript one-liners.
1. Shuffle array
One of the developers’ most important JavaScript skills is working with arrays. You will often have to shuffle the array for several applications like eCommerce product sorting, database management, and random number generation. You don’t need to use iterations and for loops to shuffle an array every time. It can be done with this JavaScript one-liner:
const shuffleArray = (arr) => arr.sort(() => Math.random() – 0.5);
The code has a complexity of O(n log n), which makes code execution faster.
Example code:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(shuffleArray(arr));
2. Detecting dark mode
Nobody can question the rising popularity of dark mode. It is a recommended feature for apps on devices that support dark mode. If you have wondered how developers can achieve this functionality, the following single-line JavaScript code makes it a walk in the park. You can easily detect dark mode with this code:
const isDarkMode = () =>
window.matchMedia && window.matchMedia(“(prefers-color-scheme: dark)”).matches;
In practical application, this method is used as follows:
console.log(isDarkMode());
Unlike other methods of detecting dark mode in JavaScript, the matchMedia method is most widely supported. It has 97.19% support on all modern browsers.
3. Generate random color
If your JavaScript application uses random color generation, you no longer have to rely on long and tedious functions to generate colors. You can achieve the same functionality with an inbuilt JavaScript function called generateRandomHexColor.
Here’s how you can use the code:
const generateRandomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
It is also one of the most commonly used JavaScript one-liners, making it much easier to generate colors randomly without needing to separate function calls. It is also a much more efficient way to achieve the goal.
4. FizzBuzz
Often asked as a tricky JavaScript interview question, the challenge here is to print numbers from 1 to 100, but for all the multiples of 3, the program must print “Fizz,” and for all the multiples of 5, it should print “Buzz.”
Believe it or not, achieving the goal with a JavaScript one-liner is possible.
for(i=0;++i<10;console.log(i%5?f||i:f+’Buzz’))f=i%3?”:’Fizz’
It is often asked in the interview to evaluate a JavaScript developer’s understanding of the concepts to the core.
Example output of the above code:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
5. Removing duplicates in an array
One of the unique features of JavaScript is that it only stores special items in the sets. This feature can be advantageous for developers who can use it to remove duplicate entries in an array. However, it is essential to note that this method only works for sorting primitive data in an array.
While for more complex applications, you might have to write multiple lines of code to remove array sorting objects with duplicate values, for more straightforward applications, you can use this single line of JavaScript code to remove duplicates.
const removeDuplicates = (arr) => […new Set(arr)]
Here’s the code in action:
removeDuplicates([31, 56, 12, 31, 45, 12, 31])
//Output
[ 31, 56, 12, 45 ]
6. Copy to clipboard
For web applications, copy to clipboard is an expected feature, especially if they are data-driven. It allows users to share text from one application to another conveniently. You don’t need to write fancy functions. JavaScript has inbuilt functionality to achieve the same. Just use this JavaScript one-liner:
const copyToClipboard = (text) => navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
// Using it in your code:
copyToClipboard(“Hello World!”);
An important point to note here is that this method currently works for 93.08% of global users, which is why you must check the browser compatibility of your end users before using this API.
7. Detecting a palindrome
In JavaScript, palindromes have useful applications such as DNA marking, biological sequencing, and compression algorithms. While all these uses may require you to write hundreds of lines of code to be effective, for easy use, you can detect a palindrome by using this line of code:
const isPalindrome = str => str === str.split(”).reverse().join(”);
Here’s an example code:
result = isPalindrome(‘abcba’);
console.log(result)
//Output
true
result = isPalindrome(‘abcbc’);
console.log(result)
//Output
false
Conclusion
Hope we have helped you become a better programmer by sharing these clever JavaScript online liners. There are many more such tricks that you will learn as you get experience, but the above ones will get you started.
Talent500 is the platform for JavaScript developers to find the best career opportunities. Sign up here to know more.
Add comment