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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With