DEV Community

🔟 Short and Sweet JavaScript One-Liners for Mastery ⚡️🚀

Arjun Vijay Prakash on February 06, 2024

🌟 Introduction When it comes to programming finding solutions often involves approaches, each with its own advantages and disadvantages ...
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

A few issues and points here:

0,1 - Get the Smallest/Largest Element of an Array:

As Tamimul pointed out, this can be much shorter - although shorter again from his version (there's little point wrapping an inbuilt function in another function - this will just add overhead):

Math.min(...arr)
Math.max(...arr)
Enter fullscreen mode Exit fullscreen mode

2 - Shuffle an array

Whilst this works, it's inefficient and will show bias in the shuffling. The Fisher-Yates shuffle is a far better way to do this.

3 - Group an array by an object property

This is built in to JS - Object.groupBy - and enjoys broad support on most modern browsers.

4 - Reverse a string

The version shown will break with strings such as "Hello world 😊". The following version has issues of it's own, but is much better:

const reverseString = str => [...str].reverse().join``
Enter fullscreen mode Exit fullscreen mode

6 - Check if Two Arrays Contain the Same Values

The provided function doesn't work in some situations:

console.log(areEqual(['a', 'b'], ['a,b'])  // true!?!
Enter fullscreen mode Exit fullscreen mode

8 - Conditional Flow Control with Nested Ternaries

Nested ternaries are never a good idea - very poor readability. Also, your code is a really bizarre way of achieving it's goal. Why not just:

const getNumWord = i => ['one', 'two', 'three', 'four'][i-1] || 'unknown'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lionelrowe profile image
lionel-rowe

Whoah somehow I never clocked that Math.random() - 0.5 would give biased results when passed as a sorting function, though I guess it's obvious with the benefit of hindsight.

Collapse
 
shadow_m2 profile image
Mohammad Bagheri

Although you very much seem like a nerd, but your approach is much nicer and smarter

Collapse
 
lionelrowe profile image
lionel-rowe

Depends how big your arrays are. This will work fine for a 100,000 element array but throw RangeError: Maximum call stack size exceeded for a million elements... whereas the reduce version will work for either.

Collapse
 
greenteaisgreat profile image
Nathan G Bornstein

@lionelrowe this is super interesting! I ended up using console.time() to check and see the execution time for both of these methods and while the Math.max(...arr) version ended up performing faster than the .reduce() method, you're 100% right. For me, it capped out if I put 130,000 elements into my array.

So while the Math.max() way is more efficient, I'm guessing JavaScript's callstack can handle only so many execution contexts.
Image description

Here's the code if anyone wants to copy/paste to fiddle with it:

const testArr = Array(120000).fill(5); 
testArr.push(6); 

const mathMax = (arr) => Math.max(...arr);

const reduceMax = (arr) => arr.reduce((smallest, num) => Math.max(smallest, num));

console.time(mathMax(testArr));
console.timeEnd(mathMax(testArr)); 


console.time(reduceMax(testArr));
console.timeEnd(reduceMax(testArr));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hari03 profile image
Hariharan • Edited

An excerpt from this great blog

In this case, we create an array for 2.000.000 elements. Array elements are stored in the heap, and therefore the function receives only the reference to the array.

When we use apply or spread operator javascript converts each element from your Iterable object to a separate argument. And therefore you may pass not a reference, but a lot of primitive values.

Collapse
 
valeria-d-23 profile image
Valeria-D-23

Thnx! Very, very helpful!

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

Thanks! I appreciate that comment.

Collapse
 
_ndeyefatoudiop profile image
Ndeye Fatou Diop

This is super cool ! I didn’t realise you could do this !

Collapse
 
officialphaqwasi profile image
Isaac Klutse

Thanks, this will help me all I need is to practice using them more.

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

Exactly! Happy Coding!

Collapse
 
mrretro profile image
retro • Edited

I prefer this way

1. const getSmallest = arr => Math.min(...arr)
2. const getLargest = arr => Math.max(...arr)
Enter fullscreen mode Exit fullscreen mode