자바스크립트 코딩 규약 - Javascript Code Conventions

Douglas Crockford 의 영어 원문(https://www.crockford.com/code.html)을 번역 한 글입니다.
다른 언어들의 코딩 규칙 혹은 기존의 자바스크립트 규칙들과 비교 했을때 특별한 내용은 없지만,
각각의 규칙들을 언급하게 된 이유나 기술적인 배경에 대해서 생각 해보는 시간을 가지려고 시작 했습니다.
직접 번역 한내용이라, 의역 및 제 개인적인 생각도 포함 되어있습니다. (직접 번역했지만 번역기같이 표현되는게, 제 능력부족을 명확하게 보여주면서도 좀 억울하네요.^^; 적당한 표현이 떠오를때마다 계속 수정 하겠습니다.)
개인적인 의견은 "역자주"를 표시 했으며, 어색한 표현들은 조금씩 추가적으로 수정을 하도록 하겠습니다.
** 잘못된 내용에 대한 따끔한 지적이나 의견은 항상 감사합니다.
** 원문의 초안 자체는 공개된지 오래됬지만 2019년에 ES6 기반으로 예제코드 등이 조금씩 수정된것으로 보입니다.
2019-05-15
Code Conventions for the JavaScript Programming Language
This is a set of coding conventions and rules for use in JavaScript programming.
이 문서는 자바스크립트 프로그래밍에 사용되는 코딩 규칙 및 방식에 대해서 얘기 합니다.
The long-term value of software to an organization is in direct proportion to the quality of the codebase. Over its lifetime, a program will be handled by many pairs of hands and eyes. If a program is able to clearly communicate its structure and characteristics, it is less likely that it will break when modified in the never-too-distant future. Code conventions can help in reducing the brittleness of programs.
장기적인 관점에서 Software의 가치는 소스코드의 품질에 정비례 합니다. Program 은 항상 많은 사람들에 의해서 유지보수 되는데,
만약 Program 이 그 구조와 특성을 명확하게 전달 할 수 있다면, 향후 수정하기에 훨씬 수월 할 것입니다.
코딩 규칙을 적용 함으로서 program을 더 튼튼하게 만들수 있습니다.
All of our JavaScript code is sent directly to the public. It should always be of publication quality. Neatness counts. Diversity of people, culture, and perspective is a good and valueable thing. Diversity of programming styles is a bad thing. It creates friction, impeding the ability of people to work together. It can make it easier for bugs to form and hide.
모든 JavaScript code 는 대중에게 공개됩니다.(역자주: Client Side Javascript 경우에 해당, nodejs 같은 Server Side의 경우는 그렇지 않은 경우도 많지요.)
그렇기 때문에 항상 최고의 품질을 유지 해야 합니다. 보기에 좋은떡이 먹기에도 좋습니다.
문화와 인종, 관점의 다양성은 훌륭한것이며 가치있는것입니다. 하지만 프로그래밍 스타일의 다양성은 그렇지 못합니다. 공동작업을 어렵게 만들며, 버그가 발생하기 쉽고 발견하기 어렵게 합니다.
JavaScript Files
JavaScript programs should be stored in and delivered as .js files.
JavaScript program은 .js 확장자로 저장되어야 합니다.
JavaScript code should not be embedded in HTML files unless the code is specific to a single session. Code in HTML adds significantly to pageweight with no opportunity for mitigation by caching, minification, and compression.
한번쓰고 폐기하는 경우가 아닌 이상, 코드를 HTML file 에 포함(embed)하면 안됩니다. Code 를 포함 하게 되면 caching 이나 압축이 용이하지 않고, 결국 page 를 읽어오는데 부하가 발생 합니다.
Whitespace
Where possible, these rules are consistent with centuries of good practice with literary style. Deviations from literary style should only be tolerated if there is strong evidence of a significant benefit.Personal preference is not a significant benefit.
특별한 상황이 아니라면, 이 문서에서 언급하는 내용은 기존의 코딩 규약들과 크게 다르지 않을것이며, 개인적인 취향은 언급되지 않습니다.
Blank lines improve readability by setting off sections of code that are logically related.
논리적으로 연관된 부분들 끼리 빈줄로 구분 하는것은 가독성을 높입니다.
Blank spaces should always be used in the following circumstances:
공백은 아래의 상황에서 항상 사용되어야 합니다.
A keyword followed by ( left parenthesis should be separated by a space. Spaces are used to make things that are not invocations look less like invocations, so for example, there should be space after if or while.
키워드와 ( 좌괄호 사이는 반드시 공백으로 구분되어야 합니다. 공백을 사용함으로서 함수 호출이 아닌데 부분이 함수호출로 보이는 것을 방지 합니다. If 나 while 같은 경우를 말합니다.
 while (true) {
A blank space should not be used between a function value and its invoking ( left parenthesis. This helps to distinguish between keywords and function invocations.
함수호출을 위한 ( 좌괄호 앞에는 공백을 사용하지 않음으로서, 키워드와 함수호출을 구분 할수 있습니다.
- The word function is always followed with one space.
function 이라는 단어 뒤에는 항상 공백을 삽입니다.
- No space should separate a unary operator and its operand except when the operator is a word such as typeof.
단항연산자와 그 피연산자 사이에는 공백을 삽입하지 않습니다. 단, typeof는 제외 합니다.
- All binary operators should be separated from their operands by a space on each side except . period and ( left parenthesis and [ left bracket.
모든 이항연산자는 피연산자들과 공백으로 구분 합니다. 단, . ( 좌 괄호 [ 좌 대괄호 는 제외합니다.
- Every , comma should be followed by a space or a line break.
모든 , 콤마 뒤에는 항상 공백 혹은 개행을 입력합니다. (역자주, 엔터키를 입력)
- Each ; semicolon at the end of a statement should be followed with a line break.
문장 마침에 사용하는 ; 세미콜론 뒤에는 개행을 입력합니다.
- Each ; semicolon in the control part of a for statement should be followed with a space.
for 문에 사용하는 ; 세미콜론 뒤에는 공백을 입력합니다.
Every statement should begin aligned with the current indentation. The outermost level is at the left margin. The indentation increases by 4 spaces when the last token on the previous line is { left brace[ left bracket( left paren. The matching closing token will be the first token on a line, restoring the previous indentation.
모든 명령문 은 현재 들여쓰기와 동일하게 정렬되어야 합니다. 가장 바깥쪽 레벨은 왼쪽 여백에서 시작 합니다. 직전 라인이 { 좌 중괄호, [ 좌 대괄호, ( 좌 괄호 인 경우에 공백4칸씩 증가 시키며, 각각의 닫는 괄호가 문장의 처음에 나올 경우에 직전의 들여쓰기를 되돌립니다.
The ternary operator can be visually confusing, so wrap the entire ternary expression in parens. The condition, the ? question mark, and the : colon always begins a line, indented 4 spaces.
삼항 연산자는 각각의 표현식 을 괄호로 묶음으로서 가독성을 높힙니다. 조건부, ? 물음표, : 콜론 은 항상 문장의 처음에 나와야 하며, 4칸의 공백으로 들여쓰기 합니다.
 let integer = function ( value, default_value ) { value = resolve(value); return ( typeof value === "number" ? Math.floor(value) : ( typeof value === "string" ? value.charCodeAt(0) : default_value ) ); }; 
Clauses (casecatchdefaultelsefinally) are not statements and so should not be indented like statements.
Case, catch, default, else, finally 와 같은 Clauses(역자주, 굳이 "절"같은 단어로 번역 하지 않음) 는 명령문 가 아니기 때문에 특별히 들여쓰기 하지 않습니다.
Use of tabs invites confusion, argument,and crying, with little compensating value. Do not use tabs. Use space.
탭을 사용하면 조금 편할지 몰라도 큰이득없이 피곤해집니다. 탭은 사용하지 말고 그냥 공백을 사용합니다.
Comments
Be generous with comments. It is useful to leave information that will be read at a later time by people (possibly your future self) who will need to understand what you have done and why. The comments should be well-written and clear, just like the code they are annotating. An occasional nugget of humor might be appreciated. Frustrations and resentments will not.
주석을 충분히 남기시기 바랍니다. 나중에 그 소스코드를 읽어야 할 사람들에게(당신 자신일지도?) 정보를 남기기 유용합니다. 주석은 코드 만큼 명확하게 작성되어야 합니다. 조금 유머러스하게 작성되어도 좋습니다. 비관적이거나 불만스러운 내용은 말구요.
It is important that comments be kept up-to-date. Erroneous comments can make programs even harder to read and understand.
주석은 항상 최신의 상태를 유지 해야 합니다.(역자주, 프로그램코드만 수정하고 주석은 수정 하지않는 경우를 방지 해야 한다는 뜻인듯합니다.) 잘못된 주석은 오히려 가독성을 떨어트립니다.
Make comments meaningful. Focus on what is not immediately visible. Don't waste the reader's time with stuff like
의미 있는 주석을 남기세요. 직관적이지 않은 부분에 집중하세요. 아래와 같은 주석으로 코드를 읽는 사람들을 귀찮게 하지 마시기 바랍니다.
// Set i to zero. i = 0;
Use line comments, not block comments. The comments should start at the left margin.
블럭주석(역자주, /***/) 보다, 라인 주석(역자주, //) 을 사용하세요.
주석은 왼쪽 여백에서 시작 해야 합니다.
Variable Declarations
All variables should be declared before used. JavaScript does not require this, but doing so makes the program easier to read and makes it easier to detect undeclared variables that may become implied. Implied global variables should never be used. Use of global variables should be minimized.
모든 변수는 사용하기전에 선언부터 해야 합니다. 자바스크립트 문법에서 허용은 되지만, 이렇게 함으로서 가독성을 높이고 해당 변수가 implied 되는것을 방지 할 수 있습니다. Implied 전역 변수는 사용되어서는 안됩니다.(역자주, 선언하지 않을 경우, windows BOM의 변수에 접근하게 됨을 방지하고자 하는것 같음.) 전역변수 사용을 자제 해야 합니다.
let currentEntry; // currently selected table entry let level; // indentation level let size; // size of the table
Function Declarations
All functions should be declared before they are used. Inner functions should come after the outer function's variable declarations. This helps make it clear what variables are included in its scope.
모든 함수는 선언부터 해야합니다. 내부함수는 외부함수 선언부 내부에 포함되어야 합니다. 이렇게 함으로서 각 변수의 스코프를 명확히 판단 할 수 있습니다.
There should be no space between the name of a function and the ( left parenthesis of its parameter list. There should be one space between the ) right parenthesis and the { left curly brace that begins the statement body. The body itself is indented four spaces. The } right curly brace is aligned with the line containing the beginning of the declaration of the function.
함수명과 파라미터 시작부분의 ( 좌 괄호 사이에 공백이 있으면 안되며, 함수 본문이 시작되기전의 ) 우 괄호 와 { 좌 중괄호 사이에 는 공백을 하나 삽입합니다. 함수 본문은 공백 4칸으로 들여쓰기 합니다. } 우 중괄호 는 함수 선언의 시작부분과 동일하게 정렬합니다.
function outer(c, d) { let e = c * d; function inner(a, b) { return (e * a) + b; } return inner(0, 1); } 
This convention works well with JavaScript because in JavaScript, functions and object literals can be placed anywhere that an expression is allowed. It provides the best readability with inline functions and complex structures.
자바스크립트는 문법이 허용하는 한, 함수와 오브젝트 값들의 위치에 상관하지 않음으로, 이 방식은 자바스크립트와 잘 어울립니다. 이렇게 함으로서 복잡한 구조의 함수본문에도 최고의 가독성을 가질 수 있습니다.
function getElementsByClassName(className) { let results = []; walkTheDOM( document.body, function (node) { let array; // array of class names let ncn = node.className; // the node's classname // If the node has a class name, then split it into a list of simple names. // If any of them match the requested name, then append the node to the list of results. if (ncn && ncn.split(" ").indexOf(className) >= 0) { results.push(node); } } ); return results; }
If a function literal is anonymous, there should be one space between the word function and the ( left parenthesis. If the space is omitted, then it can appear that the function's name is function, which is an incorrect reading.
익명함수의 경우, function 키워드와 ( 좌 괄호 사이에는 공백이 포함 되어야 합니다. 공백이 없을 경우, 해당 함수의 이름이 function 인것으로 보일 수 있습니다. (역자주, 대부분의 텍스트 에디터에 syntax highlighting 기능이 있기 때문에 딱히 체감은 어려울듯)
div.onclick = function (e) { return false; }; that = { method: function () { return this.datum; }, datum: 0 };
Use of global functions should be minimized.
전역함수는 자제 하세요.
When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.
선언즉시 실행되어야 하는 함수의 경우, 함수자체가 아닌, 함수 실행결과가 전달됨을 명확히 하기 위해서, 전체 함수 실행 표현식을 괄호로 묶어야 합니다.
let collection = (function () { let keys = []; let values = []; return { get: function (key) { let at = keys.indexOf(key); if (at >= 0) { return values[at]; } }, set: function (key, value) { let at = keys.indexOf(key); if (at < 0) { at = keys.length; } keys[at] = key; values[at] = value; }, remove: function (key) { let at = keys.indexOf(key); if (at >= 0) { keys.splice(at, 1); values.splice(at, 1); } } }; }()); 
Names
Names should be formed from the 26 upper and lower case letters (A .. Za .. z), the 10 digits (0 .. 9), and _ underbar. Avoid use of international characters because they may not read well or be understood everywhere. Do not use $ dollar sign or \ backslash in names.
이름은 영어 대소문자(A .. Z, a .. z), 숫자(0 .. 9) 그리고 _ 언더바 로 작성되어야 합니다. 이외의 국제문자의 사용은 읽기도 이해하기도 어렵기 때문에 자제 해야 합니다.(역자주, 원 저자인 더글라스 크록포드는 미국사람입니다.ㅠㅠ) $ 달라 혹은 \ 백슬래시 는 사용 하지 마세요.(역자주, JQuery...ㅠㅠ)
Do not use _ underbar as the first or last character of a name. It is sometimes intended to indicate privacy, but it does not actually provide privacy. If privacy is important, use closure. Avoid conventions that demonstrate a lack of competence.
_ 언더바 를 이름의 시작이나 끝부분에 사용하지 마세요. 특정상황에서 private 을 표현하기도 합니다만, 실제로 이름만으로 접근성 기능을 사용 할 수는 없습니다. 접근성을 위해서는 clusure 를 사용하시기 바랍니다. 잘 알고 사용해야 합니다.
Most variables and functions should start with a lower case letter.
대부분의 변수명와 함수명은 영어소문자로 시작 해야 합니다. (역자주, 예외가 되는 상황은 아래에 나옵니다.)
Constructor functions that must be used with the new prefix should start with a capital letter. JavaScript issues neither a compile-time warning nor a run-time warning if a required new is omitted. Bad things can happen if new is missing, so the capitalization convention is an important defense.
new 키워드와 함께 사용해야 하는 생성자 함수의 경우에는 대문자로 시작 해야 합니다. 자바스크립트는 new를 생략 하더라도, 어떠한 compile-time warning 이나 run-time warning 을 발생 시키지 않습니다. new 키워드가 생략되면 뭔가 좋지않은 일이 생길 수 있으므로, 생성자 함수를 대문자로 시작 하는것으로 방어가 될 수 있습니다.
Global variables should be avoided, but when used should be in ALL_CAPS.
전역 변수의 사용은 자제되어야 하지만, 정 사용해야 한다면 대문자만 사용합니다.
Statements
Simple Statements
Each line should contain at most one statement. Put a ; semicolon at the end of every statement that does not end with a {block}. Note that an assignment statement that is assigning a function literal or object literal is still an assignment statement and must end with a semicolon.
각 라인당 하나의 문장만 작성 해야 합니다. { 나 } 로 끝나는 문장이 아니라면 나머지 모든 문장은 ; 세미콜론 으로 끝내야 합니다. 함수값이나 객체값을 대입하는 경우라고 해도 여전히 대입문이므로 세미콜론으로 끝내야 합니다.(역자주, 함수값이나 객체값은 } 로 끝나므로..)
JavaScript allows any expression to be used as a statement. This can mask some errors, particularly in the presence of semicolon insertion. The only expressions that should be used as statements are assignments, invocations, and delete.
자바스크립트는 표현식 를 명령문으로 사용 하는것을 문제 삼지 않습니다. 이 부분은 특히 세미콜론을 사용하는 경우에 에러를 찾기 어려울 수 있습니다. 대입, 호출 그리고 delete 만이 명령문으로 사용 되어야 하는 표현식 입니다.
Compound Statements
Compound statements are statements that contain lists of statements enclosed in { } curly braces.
복합문은 {} 중괄호 로 둘러싸인 명령문 들을 말합니다.
- The enclosed statements should be indented four more spaces.
각 명령문들은 공백4칸으로 들여쓰기 되어야 합니다.
- The { left curly brace should be at the end of the line that begins the compound statement.
복합문의 시작은 { 좌 중괄호 로 끝나야 합니다.
- The } right curly brace should begin a line and be indented to align with the beginning of the line containing the matching { left curly brace.
} 우 중괄호 는 문장의 시작점에 있어야 하며, { 좌 중괄호 와 동일하게 정렬 되어야 합니다.
- Braces should be used around all statements, even single statements, when they are part of a control structure, such as an if or for statement. This makes it easier to add statements without accidentally introducing bugs.
복합문이 if 나 for 같은 제어문의 경우, 단 한줄일 지라도 괄호로 둘러쌈으로서 명령문을 쉽게 추가 하거나 버그 발생을 줄일 수 있습니다. (역자주, for(;;)a=a+1;같이 쓰지 말라는 뜻 인듯?)
Labels
Statement labels should be avoided. Only these statements should be labeled: whiledoforswitch.
라벨문 사용은 자제 합니다. While, do, for, switch 에 한해서 사용 할 수는 있습니다.
return Statement
The return value expression must start on the same line as the return keyword in order to avoid semicolon insertion.
세미콜론 삽입에 의한 에러를 방지 하기 위해서, 리턴값은 return 키워드와 동일 문장에서 시작 해야 합니다.
if Statement
if statement should have one of these forms:
If 문은 아래와 같이 작성 합니다.
if (condition) { statements } if (condition) { statements } else { statements } if (condition) { statements } else if (condition) { statements } else { statements }
for Statement
The for should be avoided, preferring the array methods if possible. When the for statement is used, it should one of these forms:
가능하다면 Arrays 에 정의된 함수들을 이용함으로서 for 문의 사용은 자제 합니다. 굳이 사용 한다면 아래와 같이 작성합니다.
for (initialization; condition; update) { statements } for ( initialization; condition; update ) { statements }
while Statement
while statement should have the following form:
While 문은 아래와 같이 작성합니다.
while (condition) { statements }
do Statement
do statement should have this form:
Do 문은 아래와 같이 작성합니다.
do { statements } while (condition);
Unlike the other compound statements, the do statement always ends with a ; semicolon.
다른 복합문과는 달리, do 명령문은 항상 ; 세미콜론 으로 끝내도록 합니다.
switch Statement
switch statement should be avoided, but when used should have this form:
스위치 문은 자제되어야 하지만, 사용한다면 아래와 같이 작성 하도록 합니다.
switch (expression) { case expression: statements default: statements }
Each case is aligned with the switch. This avoids over-indentation. A case label is not a statement, and should not be indented like one.
각 case 문은 switch 문과 정렬해서 과하게 들여쓰기 하는것을 방지 합니다. Case 라벨은 명령문이 아닙니다. 따라서 들여쓰기 하지 않아야 합니다.
Each group of statements (except the default) should end with breakreturn, or throw. Do not fall through.
Default 를 제외한 각 명령문들은 반드시 break 나 return, 혹은 throw 로 끝나야 합니다. 한번 시작 한일은 끝마쳐야죠? (역자주, 왜 본문의 예제에는 case 문이 break 로 끝나지 않는지는 잘 모르겠습니다. 원 저자에게 문의 할 예정입니다. 일단 원문 그래도 옮겨옵니다.)
try Statement
The try statement should have this form:
Try 문은 아래와 같이 작성 합니다.
try { statements } catch (variable) { statements }
The finally clause should be avoided. If it is used, it should have this form:
finally문의 사용은 자제 해야 합니다만, 사용한다면 아래와 같이 작성 합니다. (역자주, 이부분도 개인적으로는 이해 되지 않는 부분입니다. finally 의 사용에 대해서 인터넷상에 여러 의견들이 있긴 한것 같습니다만, 정확하게는 이부분도 원저자에게 문의 해볼 예정입니다.)
try { statements } catch (variable) { statements } finally { statements }
continue Statement
Avoid use of the continue statement. It tends to obscure the control flow of the function.
제어 흐름을 헷갈리게 함으로, Continue 문의 사용은 자제 해야 합니다.
with Statement
The with statement should not be used.
With 문은 절대 사용하지 않습니다.
{} and []
Use {} instead of new Object(). Use [] instead of new Array().
Use arrays when the member names would be sequential integers. Use objects when the member names are arbitrary strings or names.
new Object() 대신 {} 를 사용합니다. New Array() 대신 [] 를 사용 합니다.
연속적인 숫자를 멤버명으로 가질때는 배열을, 문자열을 멤버명으로 가질때에는 객체를 사용합니다.
, comma Operator
Avoid the use of the comma operator. (This does not apply to the comma separator, which is used in object literals, array literals, and parameter lists.) Having a character that is sometimes a separator and sometimes an operator is a source of confusion.
쉼표 연산자의 사용은 자제 합니다. (Object 값이나 배열값 혹은 파라미터 구분에 사용하는 쉼표는 제외입니다.) 구분자인지 operator 인지 헷갈릴수 있는 문자는 사용하지 않는것이 좋습니다.
Assignment Expressions
Avoid doing assignments in the condition part of if and while statements.
If 나 while 의 조건부 내부에 대입문을 작성 하지 않도록 합니다.
Is
아래 코드는
if (a = b) {
a correct statement? Or was
정상일까요? 아니면 아래의 코드를 의도 한 건데 실수 한걸까요?
if (a == b) {
intended? Avoid constructs that cannot easily be determined to be correct.
의도된 동작인지 아닌지 쉽게 유추 할수 없는 일은 만들지 맙시다.
=== and !== Operators.
Use the === and !== operators. The == and != operators produce false positives and false negatives, so they should not be used.
== 와 != 는 정확하지 않을수 있으므로, === 와 !== 를 사용 하도록 합니다.(역자주, 링크 참조(https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators , https://whatis.techtarget.com/definition/false-positive))
Confusing Pluses and Minuses
Be careful to not follow a + with + or ++. This pattern can be confusing. Insert parens between them to make your intention clear.
보다 명확하게 표현 하기 위해서는 + 연산자 바로 뒤에 + 나 ++연산자가 사용 될때는 주의를 기울여야 합니다. 작성자의 의도를 명확하게 표현 하기 위해서 괄호를 사용 하세요.
total = subtotal + +myInput.value;
is better written as
위 구조보다는 아래가 낫습니다.
 total = subtotal + Number(myInput.value);
so that the + + is not misread as ++. Avoid ++.
왜냐하면 + + 가 ++ 로 읽혀지는것을 방지 할 수 있기 때문이죠.
eval is Evil
The eval function is the most misused feature of JavaScript. Avoid it.
eval 함수는 자바스크립트 에서 가장 잘 못 사용되어 지는 함수 입니다. 사용을 자제 하시기 바랍니다.
eval has aliases. Do not use the Function constructor. Do not pass strings to setTimeout or setInterval.
eval 뿐만 아니라, Function 생성자를 사용하거나, setTimeout 이나 setTimeout 에 문자열을 전달 하는것도 하면 안됩니다.

Comments

Popular posts from this blog

Spring Batch : JobExecutionAlreadyRunningException: A job execution for this job is already running

3.1.0 릴리즈 알림

문자미러링 기능 출시 완료