Article posted using bloggu.io. Try it for free.
Imagine the scenario where you have a variable supposed to be an array and you want to get its le...
For further actions, you may consider blocking this person and/or reporting abuse
Your short example will also give the length of a string, or any other object that has a length property... so strictly speaking, the code is not equivalent at all.
Also, a shorter way to do the same thing (as the second example) would be:
Indeed it will give the length of a string. Even if a string behave like an array of characthers, it is not really an array as
Array.isArray()
will return false.So yes the two code are not striclty equivalent. But it will do the job in a short and more elegant way.
And the way you showed is really nice, thanks.
your first sample must be changed to:
the following code:
is nice to look at, but not to be used in a team. The detailed version is much clearer and even years later it is immediately clear to every reader what is meant.
indeed, the first version might be more readable as simple code (even if take more lines) is most of the times better code to read.
In my case I use it because it allows me to do the job (getting the length wihout exception) without needing each time to import and call a custom helper function that will do the job instead for reusability purposes.
Maybe the first is sort enough and give back result 0 for string too.
is the way to go. why create an empty array when you just want to get 0?
Indeed, this is better, thanks.
Indeed ternary expression are another way to write short and beautiful code.
I'll cover it in another article.
Another interesting short hand expression I would like to add is the following,
Instead of doing this,
We can do something like this,
Indeed, nice one.
Great article! We can discuss the readability surely but JavaScript is vast and these shortcuts make coding easier and modern.
Definitely worth checking the docs time from time!🚀
just know those 3 logical ops can be used for "short 'if'" statement.
thanks for sharing!
You're welcome.