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)
Hope this is helpful ✨
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 ✅
Top comments (91)
Careful, JS is effing weird:
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...That's just the tip of the iceberg:
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).
I am literally using
instanceof
, which means not a constant, I guess?Why are you explaining it like it is magic?
Of course. But, I mean does it make more sense
Infinity == Infinity
is true andNaN == NaN
is not?Great, then why the comparison? Just because a instanceof can be equal to the other doesn't mean all of them are equal, right?
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.
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.
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):
Yeah, i see.
Thank you for sharing your knowledge and experience.
IMO infinity is not a number.
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.Yes
Infinity is a number in math. I think it's set this way for internal reasons, but outside of programming infinity is a number
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.
Well, in JS it is a number.
maybe calling it Infinity was a poor choice 😉
Thanks for sharing 🙌
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:
What is NaN in JavaScript?
Uploadcare ・ Jan 25 ・ 7 min read
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
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...
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.
Second I saw that isNaN example I knew I had to check comments. IsNaN is very annoying to work with.
Everything besides null , undefined , strings, numbers, boolean, and symbols are objects in javascript.
There are also BigInts
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' ]
Or:
🤣🤣🤣
Gold star to the first person to fully explain how this works
Makes you sound like a pirate reading that second line of code! Arrrrrr!
Well this is the best method i found to delete an element inside DOM as a Jr. Developer 😂😂
If it is wrong correct it 🥶
Oh boy, this is gonna be fun. First of all, re-formatting the code a bit will make it a lot more readable:
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: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 ofarr
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 writingfoo = {...bar}
but using destructuring. So what's happening there, on its own, isarr = {...arr}
, meaning we get an array-like object copy ofarr
.({[0]: foo} = [1, 2, 3])
is equivalent tofoo = [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:
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: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 intoarr
. In the original code, this "throw-away" variable just happens to also bearr
to save up on alet
and to make the code a bit more confusing.So, what ultimately happens is:
arr
(other keys)arr
is passed intoObject.values
, returning all values of the array except the one to be deleted in the form of a new array.There you go :)
⭐
It deletes an element lol 😂😂
Or arr = arr.filter(i => i !== "C")
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
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.
And for the Vanilla javascript?
Btw I use Event Propagation to remove Elements from DOM in Vanilla javascript
What do you mean by rerender ?
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
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).
Also if we splice the state of useState and then update the state with the spliced version using setState, will it make a difference?
Don't mutate your state in React !
stackoverflow.com/questions/551785...
Ohk thanks for this
Looks great, Thanks for sharing 🙌
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:
2) Remove duplicates from an array:
3) Generate a random number between 1 and 100:
4) Check if a string is a valid number:
Your method is not correct:
Probably you meant "Check if a string contains a number"?
python equivalent:
5) Get the current date and time:
6) Check if a variable is an array:
7) Check if a variable is an object:
8) Convert an array to a string:
9) Check if a variable is a function:
10) Convert an object to an array:
Depends on the type of the object. For example dict:
11) Count the occurrences of an element in an array:
12) Create a new object with a dynamic key and value:
13) Check if a string is a palindrome:
14) Get the the sum of all the numbers in an array
or
15) Get the current timestamp:
16) Check if a variable is null (None in python):
17) Check if a variable is undefined:
18) Find the minimum value in an array
19) Check if an array is empty:
20) Create a new array with a specified range of numbers:
This is amazing, Thanks a lot for sharing 🔥🙌
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.
Thanks for the heads up. Fixed!
Shorter version for 20
That's helpful, Thanks for sharing 🙌
great. isn't 2, 14 and 18 the same?
Thanks for the update, I just fixed that 🙌
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 inparseFloat
.That's helpful, Thanks for sharing 🙌
8) Convert an array to a string:
13) Check if a string is a palindrome:
Using
split('')
will not work with some strings - try"🤔😈"
.Thanks for sharing 🙌
ChatGPT will be loving all this
Yeah 🙌
Love it :) Isn't 2, 14 and 18 exactly the same?
And ironic...
Thanks for the update, I just fixed that 🙌
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();
That's very helpful, Thanks for sharing 🙌