I was going through this Javascript tutorial when I came across a call for “one line – one action”.
alert( 2 * counter++ );Though technically okay, such notation usually makes code less readable. One line does multiple things – not good.
While reading code, a fast “vertical” eye-scan can easily miss something like counter++ and it won’t be obvious that the variable increased.
We advise a style of “one line – one action”:
alert( 2 * counter ); counter++;
Later, I came across a very highly upvoted answer on Stack Overflow:
const randomElement = array[Math.floor(Math.random() * array.length)];
Which looks like a lot of actions to me.
I understand style is a matter of personal preference, but I wonder if more experienced programmers might see the above as constituting one larger action (and so still one line - one action).
I searched through the internet but could not find an authoritative source in describing what I was looking for regarding "one line - one action".
If you are unsure, add another variable.
As you correctly said, there are a lot of operations in this line:
If you want to make your code more readable, I would write something like this:
In addition, if you get an exception / error on these lines, you can differentiate if the index calculation or something with the array is wrong.