DEV Community

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

Posted on • Updated on

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

Take your JavaScript skills to the next level with these essential one-liners that will also save you hours of coding 🚀


1) Find the max value in an array:

Math.max(...array)
Enter fullscreen mode Exit fullscreen mode

2) Remove duplicates from an array:

[...new Set(array)]
Enter fullscreen mode Exit fullscreen mode

3) Generate a random number between 1 and 100:

Math.floor(Math.random() * 100) + 1
Enter fullscreen mode Exit fullscreen mode

4) Check if a string is a valid number:

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

5) Get the current date and time:

new Date().toString()
Enter fullscreen mode Exit fullscreen mode

6) Check if a variable is an array:

Array.isArray(variable)
Enter fullscreen mode Exit fullscreen mode

7) Check if a variable is an object:

typeof variable === "object"
Enter fullscreen mode Exit fullscreen mode

8) Convert an array to a string:

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

9) Check if a variable is a function:

typeof variable === "function"
Enter fullscreen mode Exit fullscreen mode

10) Convert an object to an array:

Object.values(object)
Enter fullscreen mode Exit fullscreen mode

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

array.filter(x => x === element).length
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.split("").reverse().join("")
Enter fullscreen mode Exit fullscreen mode

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

array.reduce((a, b) => a + b, 0));
Enter fullscreen mode Exit fullscreen mode

15) Get the current timestamp:

Date.now()
Enter fullscreen mode Exit fullscreen mode

16) Check if a variable is null:

variable === null
Enter fullscreen mode Exit fullscreen mode

17) Check if a variable is undefined:

typeof variable === "undefined"
Enter fullscreen mode Exit fullscreen mode

18) Find the minimum value in an array

Math.min(...array)
Enter fullscreen mode Exit fullscreen mode

19) Check if an array is empty:

array.length === 0
Enter fullscreen mode Exit fullscreen mode

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

Array.from({ length: n }, (_, i) => i)
Enter fullscreen mode Exit fullscreen mode

Hope this is helpful ✨

Do Like ❤️ & Save 🔖


Do 𝗙𝗼𝗹𝗹𝗼𝘄 me on Linkedin for more:
Tips💡+ Guides📜 + Resources ⚡ related to Programming and Web Development 👨‍💻

Ram Maheshwari (@rammcodes) Linkedin


Do Follow me here on dev.to ✅

Oldest comments (91)

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
 
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
 
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
 
devdufutur profile image
Rudy Nappée

Or arr = arr.filter(i => i !== "C")

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

But i think using filter method to delete an element is heavy process as filter method returns a new array , suppose you are performing this action on 1000 Dom elements, it means if you remove 1 element using filter, other 999 element will rerender
On the other hand using splice method will remove the element from the original array directly

Thread Thread
 
marcelomartinez profile image
Marcelo Martínez

Talking about React, the other 999 elements won´t rerender because it keep track of them with a key and knows they haven´t changed.

Also, Reacts uses the Object.is(x, y) method to know when the state changed, and if you remove an array element using splice, React won´t rerender because it still is the reference to the same array even tho you modified it.

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

And for the Vanilla javascript?
Btw I use Event Propagation to remove Elements from DOM in Vanilla javascript

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Also if we splice the state of useState and then update the state with the spliced version using setState, will it make a difference?

Thread Thread
 
devdufutur profile image
Rudy Nappée

Don't mutate your state in React !
stackoverflow.com/questions/551785...

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Ohk thanks for this

 
devdufutur profile image
Rudy Nappée

What do you mean by rerender ?

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Like once in a project i mapped the Array item with HTML UI using method,
Then delete element with button click using filter method, What it was doing is refreshing the entire list of HTML element, like there is a update Dom method which sets the innerHTML of the list with the updated array
So it was doing a heavy operation with that filter array approach
Then i used the Event Propagation and find the element using closest() method of DOM, when we click on delete button of an element, it will find the closest parent element which holds that delete button and other Things, and then deleting that parent element using remove() method

Thread Thread
 
devdufutur profile image
Rudy Nappée

Actually with React you shouldn't mutate your state. If your keys are consistent it will not rerender your other elements. With filter, the objects identities doesn't change, only the array identity (it returns a new array containing the same objects).

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Looks great, Thanks for sharing 🙌

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
 
shubhamtiwari909 profile image
Shubham Tiwari

It deletes an element lol 😂😂

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
 
jaywilkinson profile image
James Wilkinson

ChatGPT will be loving all this

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Yeah 🙌

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
 
codingjlu profile image
codingjlu

IMO infinity is not a number.

Collapse
 
pcjmfranken profile image
Peter Franken

Agreed, which makes it all the more useful to know that it's classified as one in JS anyway (and in fact by most other software and runtimes too, due to the IEEE 754 standard for floating-point arithmetic).

The isFinite global function (spec, MDN) might come in handy next time you need to validate a numerical type.

Collapse
 
scriptneutron profile image
script-neutron

Yes

Collapse
 
kigazon profile image
Josef Held

Well, in JS it is a number.
maybe calling it Infinity was a poor choice 😉

Collapse
 
kitanga_nday profile image
Kitanga Nday

Infinity is a number in math. I think it's set this way for internal reasons, but outside of programming infinity is a number

Thread Thread
 
pcjmfranken profile image
Peter Franken

At the risk of sounding super pedantic, it would be more accurate to say infinity represents a number (a quantity) rather than actually being one itself. Unlike maths' infinity which can actually represent different measures, JS' version is essentially just an "out of bounds" indicator (x+n) within our "fake" digital/binary arithmetic and therefore only infinite on a philosophical level.

Funny when you realise that JS' infinity is actually, at its most basic level, a very much finite amount of ones and zeroes.

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Thanks for sharing 🙌

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
 
kitanga_nday profile image
Kitanga Nday

Second I saw that isNaN example I knew I had to check comments. IsNaN is very annoying to work with.

Collapse
 
uploadcare profile image
Uploadcare

The fact that NaN is a number is totally fine and is not related to the JS. It's due to IEEE-754.

However, isNaN is broken, that's true.

Read more:

Collapse
 
pcjmfranken profile image
Peter Franken

That is a very solid and comprehensive article! Whilst not new knowledge to me, I believe people who might not be as familiar with this subject should have no problems following along!

Thanks for sharing it here

Collapse
 
bitcreep profile image
Bitcreep

Everything besides null , undefined , strings, numbers, boolean, and symbols are objects in javascript.

Collapse
 
jimmonte profile image
jimmonte

There are also BigInts

Collapse
 
matborowiak profile image
Mat Borowiak
  1. Math is a global object
  2. Class is a function, there are no classes in JavaScript, it is a syntatic sugar over native functions, which are virtualised through objects.
  3. See what Date constructor returns.

What you are implying is ridiculous to anyone who knows JavaScript. You clearly don't, so I am not sure what makes you confident to throw falsy claims about JS "lying". You didn't even check the language spec, and have no clue how this works.

developer.mozilla.org/en-US/docs/W...
developer.mozilla.org/en-US/docs/W...
developer.mozilla.org/en-US/docs/W...

Collapse
 
pcjmfranken profile image
Peter Franken • Edited

You misunderstand. I merely listed some common pitfalls that newcomers often seem to run into, and provided a link to further details.

What a hateful and abusive response. Completely uncalled for and gained you nothing.
I wish you a more joyful and happy day tomorrow.

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
 
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
 
lotfijb profile image
Lotfi Jebali

These are good practices
Thank you for sharing

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Sounds great, Thank you 🙌

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
 
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
 
bri219 profile image
Brian Aponte

Great article. Thanks Ram!

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Sounds great, Thanks a lot ❤️🙌

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
 
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
 
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
 
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 🙌