Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a correct way of spacing in Javascript?

Tags:

javascript

In a preliminary technical interview, I was asked to write a simple calculator function in Javascript. My code was passable but he commented on my bad spacing. I wrote something like this:

 var calc = function(num1, num2, operand){       //function(...  VS function (...
      if(operand === 'add'){                     
           return num1 + num2;
      } else if(operand === 'multiply'){         // if(...
           return num1 * num2;                            
      } else if (operand === 'subtract'){        // if (... 
           return num1 - num2;
      } else {
           console.log("Not a valid operand");
      };
 };

I am a beginner in Javascript looking to learn and maintain good coding habits. I understand the function above would run regardless of my inconsistent spacing, but is there a correct way of spacing Javascript control loops?

Any advice or coding examples will help! Thanks!

like image 949
andy4thehuynh Avatar asked Dec 20 '22 08:12

andy4thehuynh


1 Answers

He probably thought it was bad because you write in a different style than he does.

A good resource on code style is the Google JavaScript Style Guide.

The key point at the end of the page says:

BE CONSISTENT.

If you're editing code, take a few minutes to look at the code around you and determine its style. If they use spaces around all their arithmetic operators, you should too. If their comments have little boxes of hash marks around them, make your comments have little boxes of hash marks around them too.

The point of having style guidelines is to have a common vocabulary of coding so people can concentrate on what you're saying rather than on how you're saying it. We present global style rules here so people know the vocabulary, but local style is also important. If code you add to a file looks drastically different from the existing code around it, it throws readers out of their rhythm when they go to read it. Avoid this.

like image 179
Amy Avatar answered Jan 10 '23 07:01

Amy