0

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".

hallofren
  • 21
  • 3

1 Answers1

1

If you are unsure, add another variable.

As you correctly said, there are a lot of operations in this line:

const randomElement = array[Math.floor(Math.random() * array.length)];

If you want to make your code more readable, I would write something like this:

const index = Math.floor(Math.random() * array.length);
const randomElement = array[index];

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.

PixelPeter
  • 11
  • 1
  • 2