DEV Community

Cover image for 20 Killer JavaScript One-Liners That’ll Save You Hours of Coding 🤯🔥

20 Killer JavaScript One-Liners That’ll Save You Hours of Coding 🤯🔥

Ram Maheshwari ♾️ on January 27, 2023

Take your JavaScript skills to the next level with these essential one-liners that will also save you hours of coding 🚀 1) Find the ma...
Collapse
 
pcjmfranken profile image
Peter Franken • Edited

Careful, JS is effing weird:

!isNaN(parseFloat('Infinity')) // true
typeof NaN === 'number' // true (lol)
typeof null === 'object' // true
typeof Math === 'object' // true
typeof MyClass === 'function' // true
typeof new Date() === 'object' // true
Enter fullscreen mode Exit fullscreen mode

There's more where that came from, but the gist of it is that whenever JS claims something is an object, function, or numerical value it's probably lying or not telling the whole story. Mistakes with JS types can lead to some very nasty bugs, so always make sure you know what is actually going on with your code!

I highly recommend reading up on how prototypes work, or at the very least check out this this MDN page on typeof's various gotcha's: developer.mozilla.org/en-US/docs/W...

Collapse
 
wiseai profile image
Mahmoud Harmouch • Edited

That's just the tip of the iceberg:

NaN == NaN // false (Lol), so it seems like these NaNs are two different instances of a NaN object?
NaN instanceof Number // false, even though it is part of IEEE 754 numeric standard.
NaN == Number.NaN // false (lol), two different NaNs in JS? Probably like the first case (two different instances).
parseInt(NaN) // NaN (lol)
Infinity == Infinity // true (lol), like how?
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bsides profile image
Rafael Pereira

You're treating NaN as a constant, which is not. Makes a lot of sense once you understand what NaN is. When you do an operation that results in NaN, its failure is not exactly the same as the other. Imagine doing an operation manually and you'll understand that it's never equals the other and there are more ways to reach that result, making it always different. This blog post is good to know more: ntgard.medium.com/why-nan-nan-3d41...

Infinity is not reverse NaN, they are pretty different. Infinity behaves as a property (or constant), which is the highest number (or lowest in case of negative infinity).

Infinity > Infinity // false
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
wiseai profile image
Mahmoud Harmouch • Edited

You're treating NaN as a constant, which is not.

I am literally using instanceof, which means not a constant, I guess?

Makes a lot of sense once you understand what NaN is.

doubt

When you do an operation that results in NaN, its failure is not exactly the same as the other. Imagine doing an operation manually and you'll understand that it's never equals the other and there are more ways to reach that result, making it always different.

Why are you explaining it like it is magic?

Infinity is not reverse NaN, they are pretty different.

Of course. But, I mean does it make more sense Infinity == Infinity is true and NaN == NaN is not?

Thread Thread
 
bsides profile image
Rafael Pereira • Edited

I am literally using instanceof, which means not a constant, I guess?

Great, then why the comparison? Just because a instanceof can be equal to the other doesn't mean all of them are equal, right?

Why are explaining it like it is magic?

I tried to explain because I thought it would help. A lot of times when I was learning JavaScript and came into something like this, an explanation which was not complex as say IEEE754 really helped me. So if it sounded condescending I'm sorry, it was not my intention.

Of course. But, I mean does it make more sense Infinity == Infinity is true and NaN == NaN is not?

At first yes, for sure. That's why it's important to see how they got to this point when they were developing the language. It's not a bug if it's intentional and I was very surprised with most of them to be intentional when I was learning. I mean, it's part of the process to start liking it, otherwise people tend to be stuck in "this language is trash because of this", you know? At least happened to me.

Thread Thread
 
wiseai profile image
Mahmoud Harmouch

A lot of times when I was learning JavaScript and came into something like this, an explanation which was not complex as say IEEE754 really helped me.

But, my concern is that there is a NaN object under the Number type (Number.NaN) even though NaN is NOT a number - I think the reason for this is that NaN is part of the IEEE 754 values which means all Number values including NaN. So, the thing that is confusing is the naming of these variables. Same thing for Infinity which is not actually the usual mathematical infinity, but rather a const (max value):

parseFloat("Infinity") === Infinity // true
parseFloat("NaN") === NaN // false
Enter fullscreen mode Exit fullscreen mode

At first yes, for sure. That's why it's important to see how they got to this point when they were developing the language. It's not a bug if it's intentional and I was very surprised with most of them to be intentional when I was learning. I mean, it's part of the process to start liking it, otherwise people tend to be stuck in "this language is trash because of this", you know? At least happened to me.

Yeah, i see.

Thank you for sharing your knowledge and experience.

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

21) Delete a specific item from an array -
arr.splice(arr.indexOf(item_to_delete),1)

Example -
let arr = ["A","B","C","D","E"];

arr.splice(arr.indexOf("C"),1)

console.log(arr)//[ 'A', 'B', 'D', 'E' ]

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Or:

let arr = ["A","B","C","D","E"]
arr = Object.values(({[arr.indexOf('C')]:arr,...arr}=arr,arr))
console.log(arr)  //[ 'A', 'B', 'D', 'E' ]
Enter fullscreen mode Exit fullscreen mode

🤣🤣🤣

Gold star to the first person to fully explain how this works

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Makes you sound like a pirate reading that second line of code! Arrrrrr!

Arr

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Well this is the best method i found to delete an element inside DOM as a Jr. Developer 😂😂
If it is wrong correct it 🥶

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Oh boy, this is gonna be fun. First of all, re-formatting the code a bit will make it a lot more readable:

Object.values(
  (
    {
      [arr.indexOf('C')]:arr,
      ...arr
    } = arr,
    arr
  )
)
Enter fullscreen mode Exit fullscreen mode

Starting from the outside, Object.values does what it says on the tin and returns the values of the object, so it's safe to assume whatever happens on the inside will return an object mapping some values to the array items except for the one to be deleted.

The inner pair of braces is a bit weird. I haven't checked this with the documentation, but from the looks of it, the form (exp_1, expr_2) will evaluate two expressions and return only the latter, so this block could be somewhat reshaped into something along these lines:

    {
      [arr.indexOf('C')]:arr,
      ...arr
    } = arr
    return arr
Enter fullscreen mode Exit fullscreen mode

if it was a function. So the code applies some de-structuring magic to the array, then hands it back to Object.values as mentioned above.

Now, for the de-structuring part, here's where the real magic happens.

The first access of arr inside square braces is just accessing the array for reading; it gets the index of the element to be deleted. The second two occurrences of arr can be thought of as "writing" access, as in these are making changes to the variable.

Looking at the components here:

({...foo} = bar) is a weirder way of writing foo = {...bar} but using destructuring. So what's happening there, on its own, is arr = {...arr}, meaning we get an array-like object copy of arr.

({[0]: foo} = [1, 2, 3]) is equivalent to foo = [1, 2, 3][0]

At this point, I'm still struggling to wrap my head around what actually happens here, but with a bit of testing, it looks like the rhs of the de-structuring assignment doesn't have to be the same variable, which makes for a much simpler example:

({[0]: arr, ...arr} = [1, 2, 3], arr)
Enter fullscreen mode Exit fullscreen mode

This somehow results in the object {1: 2, 2: 3}.

After some more testing, it looks like the first arr in this expression can be any other variable:

({0: _, ...arr} = [1, 2, 3], arr)
Enter fullscreen mode Exit fullscreen mode

Which now makes it a lot more obvious what's going on. The key 0 (in my example) is being de-structured into some throw-away variable, then the remaining key-value pairs are de-structured into arr. In the original code, this "throw-away" variable just happens to also be arr to save up on a let and to make the code a bit more confusing.


So, what ultimately happens is:

  1. The index of the value to delete is calculated
  2. The array is de-structured into a throw-away variable (key from 1.) and into arr (other keys)
  3. arr is passed into Object.values, returning all values of the array except the one to be deleted in the form of a new array.

There you go :)

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

Collapse
 
wiseai profile image
Mahmoud Harmouch • Edited

Thanks for sharing. I have added the python equivalent (assuming an array is a list in python for simplicity):

1) Find the max value in an array:

max(array)
Enter fullscreen mode Exit fullscreen mode

2) Remove duplicates from an array:

[*set(array)]
Enter fullscreen mode Exit fullscreen mode

3) Generate a random number between 1 and 100:

import random; random.randint(1, 100) # one-liner, LOL.
Enter fullscreen mode Exit fullscreen mode

4) Check if a string is a valid number:

Your method is not correct:

!isNaN(parseFloat("123.asd")) // true
Enter fullscreen mode Exit fullscreen mode

Probably you meant "Check if a string contains a number"?

python equivalent:

string.lstrip('-').replace('.','',1).isdigit()
Enter fullscreen mode Exit fullscreen mode

5) Get the current date and time:

from datetime import datetime; datetime.utcnow() # datetime.datetime(2023, 1, 28, 8, 24, 41, 221834)
Enter fullscreen mode Exit fullscreen mode

6) Check if a variable is an array:

type(array) is list
Enter fullscreen mode Exit fullscreen mode

7) Check if a variable is an object:

issubclass(variable , object)
Enter fullscreen mode Exit fullscreen mode

8) Convert an array to a string:

",".join(array)
Enter fullscreen mode Exit fullscreen mode

9) Check if a variable is a function:

import inspect; inspect.isfunction(variable)
Enter fullscreen mode Exit fullscreen mode

10) Convert an object to an array:

Depends on the type of the object. For example dict:

[*dict_object.items())]
Enter fullscreen mode Exit fullscreen mode

11) Count the occurrences of an element in an array:

array.count(element)
Enter fullscreen mode Exit fullscreen mode

12) Create a new object with a dynamic key and value:

{ key: value}
Enter fullscreen mode Exit fullscreen mode

13) Check if a string is a palindrome:

string == string[::-1]
Enter fullscreen mode Exit fullscreen mode

14) Get the the sum of all the numbers in an array

sum(array)
Enter fullscreen mode Exit fullscreen mode

or

from functools import reduce, operator; reduce(operator.add, array) 
Enter fullscreen mode Exit fullscreen mode

15) Get the current timestamp:

from datetime import datetime; datetime.timestamp(datetime.now())   
Enter fullscreen mode Exit fullscreen mode

16) Check if a variable is null (None in python):

not variable
Enter fullscreen mode Exit fullscreen mode

17) Check if a variable is undefined:

'variable' in vars() or 'variable' in globals()
Enter fullscreen mode Exit fullscreen mode

18) Find the minimum value in an array

min(array)
Enter fullscreen mode Exit fullscreen mode

19) Check if an array is empty:

not array
Enter fullscreen mode Exit fullscreen mode

20) Create a new array with a specified range of numbers:

[* range(n)]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

This is amazing, Thanks a lot for sharing 🔥🙌

Collapse
 
rjbudzynski profile image
rjbudzynski

19 can be simplified tonot array.

6 to type(array) is list

BTW in a python context array usually refers to numpy array rather than list.

Collapse
 
wiseai profile image
Mahmoud Harmouch

Thanks for the heads up. Fixed!

Collapse
 
posandu profile image
Posandu

Shorter version for 20

[...Array(n).keys()]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

That's helpful, Thanks for sharing 🙌

Collapse
 
pulkitsingh profile image
Pulkit Singh

great. isn't 2, 14 and 18 the same?

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Thanks for the update, I just fixed that 🙌

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

8) Convert an array to a string:

'' + array
Enter fullscreen mode Exit fullscreen mode

13) Check if a string is a palindrome:

string === [...string].reverse().join``
Enter fullscreen mode Exit fullscreen mode

Using split('') will not work with some strings - try "🤔😈".

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Thanks for sharing 🙌

Collapse
 
codingjlu profile image
codingjlu

I love how you've included [...new Set(array)] 3 times. By the way, isNaN automatically tries to parse the string into a number, and returns false when failing, so no need to wrap the string in parseFloat.

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

That's helpful, Thanks for sharing 🙌

Collapse
 
jaywilkinson profile image
James Wilkinson

ChatGPT will be loving all this

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Yeah 🙌

Collapse
 
oricis profile image
Moisés Alcocer

Alternatively to the tip number 8, when you want to have something as 1,2,3,4 (array elements separated by commas in a string) you can simply use:
arr.toString();

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

That's very helpful, Thanks for sharing 🙌

Collapse
 
michahumbel profile image
Humbel Micha

Love it :) Isn't 2, 14 and 18 exactly the same?

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)

And ironic...

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Thanks for the update, I just fixed that 🙌

Collapse
 
kitanga_nday profile image
Kitanga Nday

array.length === 0 can be shortened to !array.length

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

That's very helpful, Thanks for sharing 🙌

Collapse
 
squarou profile image
Benjamin

[...new Set(array)] is duplicated in your post 😉

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Thanks for the update, I just fixed that 🙌

Collapse
 
kumarkalyan profile image
Kumar Kalyan

nice article @rammcodes

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Thank You 🙌

Collapse
 
lotfijb profile image
Lotfi Jebali

These are good practices
Thank you for sharing

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Sounds great, Thank you 🙌

Collapse
 
karlkras profile image
Karl Krasnowsky

13) Check if a string is a palindrome:

Well there's something I've been looking for. 😆

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Sounds good 😅

Collapse
 
jared201 profile image
Jared Odulio

Thanks for sharing!

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

No problem 🙌

Collapse
 
bri219 profile image
Brian Aponte

Great article. Thanks Ram!

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Sounds great, Thanks a lot ❤️🙌

Collapse
 
iikitty profile image
iikitty

4) Check if a string is a valid number:

!isNaN(parseFloat(string))
Enter fullscreen mode Exit fullscreen mode

This one is not working properly

const string = '1234.5678';
!isNaN(parseFloat(string)); // true
!isNaN(string);             // true
Enter fullscreen mode Exit fullscreen mode
const string = '1234あ5678';
!isNaN(parseFloat(string)); // true
!isNaN(string);             // false
Enter fullscreen mode Exit fullscreen mode
const string = '1234.5678.9';
!isNaN(parseFloat(string)); // true
!isNaN(string);             // false
Enter fullscreen mode Exit fullscreen mode
Collapse
 
iikitty profile image
iikitty

This one works better & properly.

!isNaN(+string)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jimmonte profile image
jimmonte

Starting at the left end of the string after skipping any whitespace characters, parseFloat() only returns NaN if the first characters do not form a float number. The function stops parsing at the character that ends the number and returns the number found to that point.

Collapse
 
jcubic profile image
Jakub T. Jankiewicz • Edited

You don't need parseFloat with isNaN, to check if value is a number. it will be converted to number before the check:

!isNaN('100') == true
!isNaN('hello') == false
Enter fullscreen mode Exit fullscreen mode

There is Number.isNaN that don't do the conversion.

Collapse
 
bokomoko profile image
João Eurico "Bokomoko" Lima • Edited

20 also could be done with

Array(n).fill(0).map((_,i)=>i)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nameandnums profile image
FiftyP

Why does #3 seem 'smelly' to me?

"Generate a random number between 1 and 100:
Math.floor(Math.random() * 100) + 1"

Math.random() => 0 to 1 (NOT including 1) => [0, 1)
Math.random()*100. => 0 to 100 (NOT including 100) => [0, 100)
Math.floor(Math.random()*100) => int(0 to 100) (NOT including 100) => [0, 100)
Math.floor(Math.random()*100)+1 => int(1 to 101) (NOT including 101) => [1, 101)

so, the Math.floor(Math.random()*100)+1 CAN include 100, so is NOT '1 to 100 (not including 100)', which would be expected from all the other descriptions of 'A to B' which DON'T include the upper bound.
IMO, the description "between" is (1, 100), but the functions used seem to be [a,b), so the user might also expect [1,100), but they actually get [1,100] - or [1,101) since they're only integers.

Collapse
 
nameandnums profile image
FiftyP

found = false;
count = 0;
while (!found) {
const value = Math.floor(Math.random() * 100) + 1;
found = value === 100;
count++;
}
197

Collapse
 
wadecodez profile image
Wade Zimmerman • Edited

Number 7 is wrong because arrays and null have a type of object. This is why typescript was invented.

typeof null // object
typeof {} // object
typeof [] // object
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gaoryrt profile image
gaoryrt

20) Create a new array with a specified range of numbers:

[...Array(n).keys()]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
myrlandnu profile image
Jørn André Myrland

Hey, you forgot this one:

!!~text.indexOf(query)
Enter fullscreen mode Exit fullscreen mode

I use this one all the time.

Collapse
 
chinmayj93 profile image
Chinmay Joshi • Edited

How can you forget the most valuable code while debugging - console.log("asdasdasd");

Collapse
 
volkanalkilic profile image
Volkan Alkılıç • Edited

Thank you ChatGPT for 20 useless tips that i already know.

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

🙌

Collapse
 
m4heshd profile image
Mahesh Bandara Wijerathna

This whole article screams "I AM A JS BEGINNER". Most of these snippets will destroy your logic in specific scenarios. You should edit this.

Collapse
 
jakeroid profile image
Ivan Karabadzhak

I like your efforts. I think each JS developer should know those. But, be careful with isNaN function.

Collapse
 
zeeh1975 profile image
zeeh1975

I like 20, very clever!

Collapse
 
ra1nbow1 profile image
Matvey Romanov

Thanks a lot :)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Somewhat weirdly, this post appears to have changed authors? 🤔 @thepracticaldev

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️ • Edited

Yeah, I don't know how it got removed from my account and got transferred into this account @thepracticaldev , maybe some bug?

Collapse
 
flyingcrp profile image
flyingCrp

Image description