## DEV Community 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)
``````

### 2) Remove duplicates from an array:

``````[...new Set(array)]
``````

### 3) Generate a random number between 1 and 100:

``````Math.floor(Math.random() * 100) + 1
``````

### 4) Check if a string is a valid number:

``````!isNaN(parseFloat(string))
``````

### 5) Get the current date and time:

``````new Date().toString()
``````

### 6) Check if a variable is an array:

``````Array.isArray(variable)
``````

### 7) Check if a variable is an object:

``````typeof variable === "object"
``````

### 8) Convert an array to a string:

``````array.join(",")
``````

### 9) Check if a variable is a function:

``````typeof variable === "function"
``````

### 10) Convert an object to an array:

``````Object.values(object)
``````

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

``````array.filter(x => x === element).length
``````

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

``````{ [key]: value }
``````

### 13) Check if a string is a palindrome:

``````string === string.split("").reverse().join("")
``````

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

``````array.reduce((a, b) => a + b, 0));
``````

### 15) Get the current timestamp:

``````Date.now()
``````

### 16) Check if a variable is null:

``````variable === null
``````

### 17) Check if a variable is undefined:

``````typeof variable === "undefined"
``````

### 18) Find the minimum value in an array

``````Math.min(...array)
``````

### 19) Check if an array is empty:

``````array.length === 0
``````

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

``````Array.from({ length: n }, (_, i) => i)
``````

Do Like ❤️ & Save 🔖

Do 𝗙𝗼𝗹𝗹𝗼𝘄 me on Linkedin for more:
Tips💡+ Guides📜 + Resources ⚡ related to Programming and Web Development 👨‍💻 Do Follow me here on dev.to ✅ 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
``````

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... 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?
`````` 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
`````` 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. 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? 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. 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
``````

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. 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. 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 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. 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. 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 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. 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. Kitanga Nday

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

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' ] 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' ]
``````

🤣🤣🤣

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

Well this is the best method i found to delete an element inside DOM as a Jr. Developer 😂😂
If it is wrong correct it 🥶 𒎏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
)
)
``````

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

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`.

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

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:

``````({: arr, ...arr} = [1, 2, 3], arr)
``````

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)
``````

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 :) Jon Randy 🎖️ Mysterio

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 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. Mysterio

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

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 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). 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)
``````

## 2) Remove duplicates from an array:

``````[*set(array)]
``````

## 3) Generate a random number between 1 and 100:

``````import random; random.randint(1, 100) # one-liner, LOL.
``````

## 4) Check if a string is a valid number:

``````!isNaN(parseFloat("123.asd")) // true
``````

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

python equivalent:

``````string.lstrip('-').replace('.','',1).isdigit()
``````

## 5) Get the current date and time:

``````from datetime import datetime; datetime.utcnow() # datetime.datetime(2023, 1, 28, 8, 24, 41, 221834)
``````

## 6) Check if a variable is an array:

``````type(array) is list
``````

## 7) Check if a variable is an object:

``````issubclass(variable , object)
``````

## 8) Convert an array to a string:

``````",".join(array)
``````

## 9) Check if a variable is a function:

``````import inspect; inspect.isfunction(variable)
``````

## 10) Convert an object to an array:

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

``````[*dict_object.items())]
``````

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

``````array.count(element)
``````

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

``````{ key: value}
``````

## 13) Check if a string is a palindrome:

``````string == string[::-1]
``````

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

``````sum(array)
``````

or

``````from functools import reduce, operator; reduce(operator.add, array)
``````

## 15) Get the current timestamp:

``````from datetime import datetime; datetime.timestamp(datetime.now())
``````

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

``````not variable
``````

## 17) Check if a variable is undefined:

``````'variable' in vars() or 'variable' in globals()
``````

## 18) Find the minimum value in an array

``````min(array)
``````

## 19) Check if an array is empty:

``````not array
``````

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

``````[* range(n)]
`````` rjbudzynski

19 can be simplified to`not array`.

6 to `type(array) is list`

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

Thanks for the heads up. Fixed! Posandu

Shorter version for 20

``````[...Array(n).keys()]
`````` 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`. Jon Randy 🎖️ • Edited

8) Convert an array to a string:

``````'' + array
``````

13) Check if a string is a palindrome:

``````string === [...string].reverse().join``
``````

Using `split('')` will not work with some strings - try `"🤔😈"`. 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();` Lotfi Jebali

These are good practices
Thank you for sharing

DEV Community