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...
For further actions, you may consider blocking this person and/or reporting abuse
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 == Infinityis true andNaN == NaNis 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.
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.valuesdoes 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.valuesas mentioned above.Now, for the de-structuring part, here's where the real magic happens.
The first access of
arrinside square braces is just accessing the array for reading; it gets the index of the element to be deleted. The second two occurrences ofarrcan 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
arrin 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 bearrto save up on aletand to make the code a bit more confusing.So, what ultimately happens is:
arr(other keys)arris 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 :)
⭐
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 listBTW 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 🙌
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 🙌
I love how you've included
[...new Set(array)]3 times. By the way,isNaNautomatically 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 🙌
ChatGPT will be loving all this
Yeah 🙌
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 🙌
Love it :) Isn't 2, 14 and 18 exactly the same?
And ironic...
Thanks for the update, I just fixed that 🙌
array.length === 0can be shortened to!array.lengthThat's very helpful, Thanks for sharing 🙌
[...new Set(array)] is duplicated in your post 😉
Thanks for the update, I just fixed that 🙌
nice article @rammcodes
Thank You 🙌
These are good practices
Thank you for sharing
Sounds great, Thank you 🙌
13) Check if a string is a palindrome:
Well there's something I've been looking for. 😆
Sounds good 😅
Thanks for sharing!
No problem 🙌
Great article. Thanks Ram!
Sounds great, Thanks a lot ❤️🙌
This one is not working properly
This one works better & properly.
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.
You don't need parseFloat with isNaN, to check if value is a number. it will be converted to number before the check:
There is Number.isNaN that don't do the conversion.
20 also could be done with
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)+1CAN 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.
found = false;count = 0;
while (!found) {
const value = Math.floor(Math.random() * 100) + 1;
found = value === 100;
count++;
}
197
Number 7 is wrong because arrays and null have a type of object. This is why typescript was invented.
20) Create a new array with a specified range of numbers:
Hey, you forgot this one:
I use this one all the time.
How can you forget the most valuable code while debugging -
console.log("asdasdasd");Thank you ChatGPT for 20 useless tips that i already know.
🙌
This whole article screams "I AM A JS BEGINNER". Most of these snippets will destroy your logic in specific scenarios. You should edit this.
I like your efforts. I think each JS developer should know those. But, be careful with isNaN function.
I like 20, very clever!
Thanks a lot :)
Somewhat weirdly, this post appears to have changed authors? 🤔 @thepracticaldev
Yeah, I don't know how it got removed from my account and got transferred into this account @thepracticaldev , maybe some bug?