Hi Dev,
Today I'm gonna share my 7 favorite Javascript shorthand tips that will look cool and clean on your code.
Alright, Let's begin.
...
For further actions, you may consider blocking this person and/or reporting abuse
Wouldn't the equivalent longhand expression be
if (myValue == true)
? Your example will return false unlessmyValue
is a boolean.Other than that, all those are great features of JavaScript.
Came to the comments to say this 😃
Yea I agree, that part is very misleading... its equiv to
if (Boolean(myValue)) {...}
Yeah, you are right. I'll change it right away. Thanks, patrik, Blake
I assumed that it's a boolean. I was just trying to explain the truthy expressions.
I'll put appropriate comments. Thanks for the feedback.
Oh, gotcha! I assumed you were checking that it was a truthy value.
I would never use "2) Decimal Values with trailing zeroes" and would strongly advise against using this in anything other than personal projects. The only benefit you get is confusing other developers, especially juniors.
I think that up to one's perspective. We can easily see those expressions in mathematics.
Cool trick for #5. You could even include parameters for require like so:
Nice list.
In the last example I prefer to use
[1,2,3].includes(1)
instead of~[1,2,3].indexOf(1)
Wow, guess I became a ninja and didn't even realize it... 6 out of 7 tricks. Not bad
Mandatory parameter seems very useful
const num1 = +"100"
Does this shorthand work in all browsers?It's just usage of a unary operator '+'. So, I believe it will work the same on all browsers. But you cannot use const, instead of const use var since const is introduced in ES6.
I think #6 is code smell (bad advice). Instead be concise and use parseInt, parseFloat, or Number for typecasting
For #7 we could just use
Array.prototype.includes()
(developer.mozilla.org/en-US/docs/W...)I like the Mandatory Parameter way of throwing error for required fields.Its cool and enhances readability.
Thanks for sharing
Uhm nice to know , but points 5,6 and 7 seem less readable to me. Personally I prefer longhand in those cases.