함수 호출과 this

JAVA같은 언어에서 this는 클래스로부터 생성되는 인스턴스 객체를 의미한다.다른 의미를 가질 염려가 없어서 혼란이 생기지 않는다.

자바스크립트에서는 this는 함수의 현재 실행 문맥(context)이다.

arguments 객체

C와 같은 엄격한 언어와 달리, 자바스크립트에서는 함수를 호출할 때 함수 형식에 맞춰 인자를 넘기지 않더라도 에러가 발생하지 않는다. 정의된 함수의 인자보다 적게 함수를 호출했을 경우, 넘겨지지 않은 인자에는undefined값이 할당된다. 이와 반대로 정의된 인자 개수보다 많게 호출했을 경우 초과된 인수는 무시된다.

이러한 특성 때문에, 런타임 시에 호출된 인자의 개수를 확인하고 이에 따라 동작을 다르게 해줘야 할 경우가 있다. 이를 가능케 하는게 함수를 호출할 때 암묵적으로 전달되는 arguments 객체다. 이 객체는 실제 배열이 아닌 유사 배열 객체이다.

function add(a, b) { 
  console.dir(arguments); 
  return a + b; 
} 

console.log(add(1)); // NaN 
console.log(add(1, 2)); // 3 
console.log(add(1, 2, 3)); // 3

호출 패턴과 this 바인딩

자바스크립트에서 함수를 호출할 때 기존 매개변수로 전달되는 인자값에 더해, 앞서 설명한 arguments 객체 및this 인자가 함수 내부로 암묵적으로 전달된다.this가 이해하기가 어려운 이유는 자바스크립트의 여러 가지 함수가 호출되는 방식(호출 패턴)에 따라 this가 다른 객체를 참조하기(this 바인딩) 때문이다.

1. 객체의 메서드 호출할 때 this 바인딩

객체의 프로퍼티가 함수일 경우, 이 함수를 메서드라고 부른다. 메서드 내부 코드에서 사용된 this는해당 메서드를 호출한 객체로 바인딩 된다.

var myObject = { 
  name: 'foo', 
  sayName: function () {
    console.log(this == myObject) // true
    console.log(this.name); 
  } 
} 

var otherObject = { name: 'bar' } 
otherObject.sayName = myObject.sayName; 
myObject.sayName(); // foo otherObject.sayName(); // bar

2. 함수를 호출할 때 this 바인딩

함수를 호출할 경우는, 해당 함수 내부 코드에서 사용된this는 전역 객체에 바인딩된다.브라우저에서 자바스크립트를 실행하는 경우 전역 객체는 window 객체다.

var test = 'This is test'; 
console.log(window.test); // 'This is test' 

var sayFoo = function() { 
  console.log(this.test); // 'This is test' 
} 

sayFoo();

 

  • 메소드 내의 내부함수
    이러한 함수 호출에서의 this 바인딩 특성은내부 함수(inner function)를 호출했을 경우에도 동일하게 적용되므로유의해서 사용해야 한다.
var numbers = {  
   numberA: 5,
   numberB: 10,
   sum: function() {
     console.log(this === numbers); // => true
     function calculate() {
       // this는 window, 엄격 모드였으면 undefined
       console.log(this === numbers); // => false
       return this.numberA + this.numberB;
     }
     return calculate();
   }
};
numbers.sum(); // NaN, 엄격 모드(use strict)였으면 TypeError

 
자바스크립트에서내부 함수 호출 패턴을 정의해 놓지 않았기 때문에,함수로 취급되어 함수 호출 패턴 규칙에 따라 내부 함수의 this는 전역 객체에 바인딩된다. 그래서 흔히들 that 변수를 이용하여 this 값을 저장한다.

var numbers = {  
   numberA: 5,
   numberB: 10,
   sum: function() {
     console.log(this === numbers); // => true
     const that = this
     function calculate() {
       // this는 window, 엄격 모드였으면 undefined
       console.log(this === numbers); // => false
       console.log(that === numbers); // => true
       return that.numberA + that.numberB; // 15
     }
     return calculate();
   }
};
numbers.sum(); // NaN, 엄격 모드(use strict)였으면 TypeError

이와 같은 this 바인딩의 한계를 극복하려고, this 바인딩을 명시적으로 할 수 있도록 call과 apply 메서드를 제공한다.  

  • 클래스 내의 메소드가 가지는 this
    ES6의 문법으로 클래스(class)를 정의할 때도 메소드의 실행 문맥은 인스턴스 객체 자신이다.
class Planet {  
  constructor(name) {
    this.name = name;    
  }
  getName() {
    console.log(this === earth); // => true
    return this.name;
  }
}
var earth = new Planet('Earth');  
// 메소드 실행. 여기서의 this는 earth.
earth.getName(); // => 'Earth'

 

  • 객체 내의 메소드가 외부에서 분리되었을 때의 this
    객체 내에 있는 메소드는 별도의 변수로 분리가 가능하다. 이 변수를 통해 메소드를 호출할 때! this는 함수 호출에서의 문맥으로 바뀐다.
var obj = {   
    sayHello: function() {
        if(this == obj) {
            console.log('this == obj');
        } else if(this == window) {
            console.log('this == window');
        }
    }   
};

obj .sayHello(); // this == obj
var reference = obj.sayHello;
reference(); // this == window

3. 생성자 함수를 호출할 때 this 바인딩

자바스크립트에서기존 함수에 new 연산자를 붙여서 호출하면 해당 함수는 생성자 함수로 동작한다.일반 함수에 new를 붙여 호출하면 원치 않는 생성자 함수로 동작할 수 있기 때문에, 대부분의 자바스크립트 스타일 가이드에서는 특정 함수가 생성자 함수로 정의되어 있음을 알리려고 함수 이름의 첫 문자를 대문자로 쓰기를 권하고 있다.
 
생성자 함수에서의 this는생성자 함수를 통해 새로 생성되어 반환되는 객체에 바인딩된다.(이는 생성자 함수에서 명시적으로 다른 객체를 반환하지 않는 일반적인 경우에 적용됨)

// Person 생성자 함수 
var Person = function(name) { 
  this.name = name; 
} 
// foo 객체 생성 
var foo = new Person('foo'); 
console.log(foo.name); // foo

 

  • 객체 리터럴 방식과 생성자 함수를 통한 객체 생성 방식의 차이

객체 리터럴 방식으로 생성된 객체는 생성자 함수처럼 다른 인자를 넣어 형식은 같지만 다른 값을 가지는 객체를 생성할 수 없다.

var foo = { name : 'foo' } 

function Person(name) { 
  this.name = name; 
} 

var bar = new Person('bar'); 
var baz = new Person('baz');

또 다른 차이점은 객체 리터럴 방식으로 생성한 foo 객체의 __proto__ 프로퍼티는 Object.prototype를 가르키며, 생성자 함수를 통해 생성한 bar, baz 객체의 __proto__ 프로퍼티는 Person.prototype를 가르킨다는 점이다.  

  • 생성자 함수를 new를 붙이지 않고 호출할 경우

생성자 함수를 new를 붙이지 않고 호출할 경우 위에서 살펴본2. 함수를 호출할 때 this 바인딩규칙이 적용되어 this가 전역객체에 바인딩된다. 이런 위험성을 피하려고 널리 사용되는 패턴이 있다.

function A(arg) { 
  if (!(this instanceof A)) { 
    return new A(arg); 
  } 

  this.value = arg ? arg : 0; 
}

ES6에서의 class에서 생성자도 this는 새로 생긴 객체다.

class Bar {  
  constructor() {
    console.log(this instanceof Bar); // => true
    this.property = 'Default Value';
  }
}
// Constructor invocation
var barInstance = new Bar();  
barInstance.property; // => 'Default Value'


출처: https://jeong-pro.tistory.com/109?category=799620 [기본기를 쌓는 정아마추어 코딩블로그]

4. call과 apply 메서드를 이용한 명시적인 this 바인딩

Function.prototype 객체의 메서드인 call()과 apply()를 통해 명시적으로 this를 바인딩 가능하다.
간접 실행은 함수가 .call() 이나 .apply 메소드와 함께 호출될 때를 가리킨다.
 
.call(arg1,arg2,...) 메소드는 첫 번째 인자는 실행 문맥(this), 나머지 인자는 호출함수에 전달할 매개변수를 하나씩 받는다.
.apply(arg1,[args]) 메소드는 첫 번째 인자는 실행 문맥(this), 나머지 인자는 호출 함수에 전달할 매개변수를 배열로 받는다.

var rabbit = { name: 'White Rabbit' };  
function concatName(string) {  
  console.log(this === rabbit); // => true
  return string + this.name;
}
// Indirect invocations
concatName.call(rabbit, 'Hello ');  // => 'Hello White Rabbit'  
concatName.apply(rabbit, ['Bye ']); // => 'Bye White Rabbit'
// Person 생성자 함수 
function Person(name) { 
  this.name = name; 
} 

// foo 빈 객체 생성 
var foo = {}; 
Person.apply(foo, ['foo']); 
console.log(foo.name); // foo 
console.log(foo.__proto__ === Object.prototype) // true

예제에서 알 수 있듯이 apply()를 통해 호출한 경우, 생성자 함수 방식이 아닌 this 가 foo 객체에 바인딩되어 proto 프로퍼티가 Person.prototype이 아닌 Object.prototype이다.
 
이처럼 apply()나 call() 메서드는 this를 원하는 값으로 명시적으로 매핑해서 특정 함수나 메서드를 호출할 수 있다는 장점이 있다. 그리고 이들의 대표적인 용도가 arguments 객체와 같은 유사 배열 객체에서 배열 메서드를 사용하는 경우이다. arguments 객체는 실제 배열이 아니므로 pop(), shift() 같은 표준 메서드를 사용할 수 없지만 apply() 메서드를 이용하면 가능하다.

function myFunction() { 

  // arguments.shift(); 에러 발생 
  var args \= Array.prototype.slice.apply(arguments); 
} 

myFunction(); 

출처:

  1. https://itstory.tk/entry/JavaScript-4-함수와-프로토타입-체이닝-2-this란[덕's IT Story]
  2. ES6 화살표 함수(arrow function)를 배우기 전 자바스크립트 this 이해하기

https://google.github.io/styleguide/jsguide.html#features-functions



Google JavaScript Style Guide

1 Introduction

This document serves as the complete definition of Google’s coding standards for source code in the JavaScript programming language. A JavaScript source file is described as being in Google Style if and only if it adheres to the rules herein.

Like other programming style guides, the issues covered span not only aesthetic issues of formatting, but other types of conventions or coding standards as well. However, this document focuses primarily on the hard-and-fast rules that we follow universally, and avoids giving advice that isn't clearly enforceable (whether by human or tool).

1.1 Terminology notes

In this document, unless otherwise clarified:

  1. The term comment always refers to implementation comments. We do not use the phrase documentation comments, instead using the common term “JSDoc” for both human-readable text and machine-readable annotations within /** … */.

  2. This Style Guide uses RFC 2119 terminology when using the phrases mustmust notshouldshould not, and may. The terms prefer and avoid correspond to should and should not, respectively. Imperative and declarative statements are prescriptive and correspond to must.

Other terminology notes will appear occasionally throughout the document.

1.2 Guide notes

Example code in this document is non-normative. That is, while the examples are in Google Style, they may not illustrate the only stylish way to represent the code. Optional formatting choices made in examples must not be enforced as rules.

2 Source file basics

2.1 File name

File names must be all lowercase and may include underscores (_) or dashes (-), but no additional punctuation. Follow the convention that your project uses. Filenames’ extension must be .js.

2.2 File encoding: UTF-8

Source files are encoded in UTF-8.

2.3 Special characters

2.3.1 Whitespace characters

Aside from the line terminator sequence, the ASCII horizontal space character (0x20) is the only whitespace character that appears anywhere in a source file. This implies that

  1. All other whitespace characters in string literals are escaped, and

  2. Tab characters are not used for indentation.

2.3.2 Special escape sequences

For any character that has a special escape sequence (\'\"\\\b\f\n\r\t\v), that sequence is used rather than the corresponding numeric escape (e.g \x0a\u000a, or \u{a}). Legacy octal escapes are never used.

2.3.3 Non-ASCII characters

For the remaining non-ASCII characters, either the actual Unicode character (e.g. ) or the equivalent hex or Unicode escape (e.g. \u221e) is used, depending only on which makes the code easier to read and understand.

Tip: In the Unicode escape case, and occasionally even when actual Unicode characters are used, an explanatory comment can be very helpful.

ExampleDiscussion
const units = 'μs';Best: perfectly clear even without a comment.
const units = '\u03bcs'; // 'μs'Allowed, but there’s no reason to do this.
const units = '\u03bcs'; // Greek letter mu, 's'Allowed, but awkward and prone to mistakes.
const units = '\u03bcs';Poor: the reader has no idea what this is.
return '\ufeff' + content; // byte order markGood: use escapes for non-printable characters, and comment if necessary.

Tip: Never make your code less readable simply out of fear that some programs might not handle non-ASCII characters properly. If that happens, those programs are broken and they must be fixed.

3 Source file structure

A source file consists of, in order:

  1. License or copyright information, if present
  2. @fileoverview JSDoc, if present
  3. goog.module statement
  4. goog.require statements
  5. The file’s implementation

Exactly one blank line separates each section that is present, except the file's implementation, which may be preceded by 1 or 2 blank lines.

If license or copyright information belongs in a file, it belongs here.

3.2 @fileoverview JSDoc, if present

See 7.5 Top/file-level comments for formatting rules.

3.3 goog.module statement

All files must declare exactly one goog.module name on a single line: lines containing a goog.module declaration must not be wrapped, and are therefore an exception to the 80-column limit.

The entire argument to goog.module is what defines a namespace. It is the package name (an identifier that reflects the fragment of the directory structure where the code lives) plus, optionally, the main class/enum/interface that it defines concatenated to the end.

Example

goog.module('search.urlHistory.UrlHistoryService');

3.3.1 Hierarchy

Module namespaces may never be named as a direct child of another module's namespace.

Illegal:

goog.module('foo.bar');   // 'foo.bar.qux' would be fine, though
goog.module('foo.bar.baz');

The directory hierarchy reflects the namespace hierarchy, so that deeper-nested children are subdirectories of higher-level parent directories. Note that this implies that owners of “parent” namespace groups are necessarily aware of all child namespaces, since they exist in the same directory.

3.3.2 goog.setTestOnly

The single goog.module statement may optionally be followed by a call to goog.setTestOnly().

3.3.3 goog.module.declareLegacyNamespace

The single goog.module statement may optionally be followed by a call to goog.module.declareLegacyNamespace();. Avoid goog.module.declareLegacyNamespace() when possible.

Example:

goog.module('my.test.helpers');
goog.module.declareLegacyNamespace();
goog.setTestOnly();

goog.module.declareLegacyNamespace exists to ease the transition from traditional object hierarchy-based namespaces but comes with some naming restrictions. As the child module name must be created after the parent namespace, this name must not be a child or parent of any other goog.module (for example, goog.module('parent'); andgoog.module('parent.child'); cannot both exist safely, nor can goog.module('parent'); and goog.module('parent.child.grandchild');).

3.3.4 ES6 Modules

Do not use ES6 modules yet (i.e. the export and import keywords), as their semantics are not yet finalized. Note that this policy will be revisited once the semantics are fully-standard.

3.4 goog.require statements

Imports are done with goog.require statements, grouped together immediately following the module declaration. Each goog.require is assigned to a single constant alias, or else destructured into several constant aliases. These aliases are the only acceptable way to refer to the required dependency, whether in code or in type annotations: the fully qualified name is never used except as the argument to goog.require. Alias names should match the final dot-separated component of the imported module name when possible, though additional components may be included (with appropriate casing such that the alias' casing still correctly identifies its type) if necessary to disambiguate, or if it significantly improves readability. goog.require statements may not appear anywhere else in the file.

If a module is imported only for its side effects, the assignment may be omitted, but the fully qualified name may not appear anywhere else in the file. A comment is required to explain why this is needed and suppress a compiler warning.

The lines are sorted according to the following rules: All requires with a name on the left hand side come first, sorted alphabetically by those names. Then destructuring requires, again sorted by the names on the left hand side. Finally, any goog.require calls that are standalone (generally these are for modules imported just for their side effects).

Tip: There’s no need to memorize this order and enforce it manually. You can rely on your IDE to report requires that are not sorted correctly.

If a long alias or module name would cause a line to exceed the 80-column limit, it must not be wrapped: goog.require lines are an exception to the 80-column limit.

Example:

const MyClass = goog.require('some.package.MyClass');
const NsMyClass = goog.require('other.ns.MyClass');
const googAsserts = goog.require('goog.asserts');
const testingAsserts = goog.require('goog.testing.asserts');
const than80columns = goog.require('pretend.this.is.longer.than80columns');
const {clear, forEach, map} = goog.require('goog.array');
/** @suppress {extraRequire} Initializes MyFramework. */
goog.require('my.framework.initialization');

Illegal:

const randomName = goog.require('something.else'); // name must match

const {clear, forEach, map} = // don't break lines
    goog.require('goog.array');

function someFunction() {
  const alias = goog.require('my.long.name.alias'); // must be at top level
  // …
}

3.4.1 goog.forwardDeclare

goog.forwardDeclare is not needed very often, but is a valuable tool to break circular dependencies or to reference late loaded code. These statements are grouped together and immediately follow any goog.require statements. A goog.forwardDeclare statement must follow the same style rules as a goog.require statement.

3.5 The file’s implementation

The actual implementation follows after all dependency information is declared (separated by at least one blank line).

This may consist of any module-local declarations (constants, variables, classes, functions, etc), as well as any exported symbols.

4 Formatting

Terminology Noteblock-like construct refers to the body of a class, function, method, or brace-delimited block of code. Note that, by 5.2 Array literals and 5.3 Object literals, any array or object literal may optionally be treated as if it were a block-like construct.

Tip: Use clang-format. The JavaScript community has invested effort to make sure clang-format does the right thing on JavaScript files. clang-format has integration with several popular editors.

4.1 Braces

4.1.1 Braces are used for all control structures

Braces are required for all control structures (i.e. ifelsefordowhile, as well as any others), even if the body contains only a single statement. The first statement of a non-empty block must begin on its own line.

Illegal:

if (someVeryLongCondition())
  doSomething();

for (let i = 0; i < foo.length; i++) bar(foo[i]);

Exception: A simple if statement that can fit entirely on a single line with no wrapping (and that doesn’t have an else) may be kept on a single line with no braces when it improves readability. This is the only case in which a control structure may omit braces and newlines.

if (shortCondition()) return;

4.1.2 Nonempty blocks: K&R style

Braces follow the Kernighan and Ritchie style (Egyptian brackets) for nonempty blocks and block-like constructs:

  • No line break before the opening brace.
  • Line break after the opening brace.
  • Line break before the closing brace.
  • Line break after the closing brace if that brace terminates a statement or the body of a function or class statement, or a class method. Specifically, there is no line break after the brace if it is followed by elsecatchwhile, or a comma, semicolon, or right-parenthesis.

Example:

class InnerClass {
  constructor() {}

  /** @param {number} foo */
  method(foo) {
    if (condition(foo)) {
      try {
        // Note: this might fail.
        something();
      } catch (err) {
        recover();
      }
    }
  }
}

4.1.3 Empty blocks: may be concise

An empty block or block-like construct may be closed immediately after it is opened, with no characters, space, or line break in between (i.e. {}), unless it is a part of a multi-block statement (one that directly contains multiple blocks: if/else or try/catch/finally).

Example:

function doNothing() {}

Illegal:

if (condition) {
  // …
} else if (otherCondition) {} else {
  // …
}

try {
  // …
} catch (e) {}

4.2 Block indentation: +2 spaces

Each time a new block or block-like construct is opened, the indent increases by two spaces. When the block ends, the indent returns to the previous indent level. The indent level applies to both code and comments throughout the block. (See the example in 4.1.2 Nonempty blocks: K&R style).

4.2.1 Array literals: optionally block-like

Any array literal may optionally be formatted as if it were a “block-like construct.” For example, the following are all valid (not an exhaustive list):

const a = [
  0,
  1,
  2,
];

const b =
    [0, 1, 2];
const c = [0, 1, 2];

someMethod(foo, [
  0, 1, 2,
], bar);

Other combinations are allowed, particularly when emphasizing semantic groupings between elements, but should not be used only to reduce the vertical size of larger arrays.

4.2.2 Object literals: optionally block-like

Any object literal may optionally be formatted as if it were a “block-like construct.” The same examples apply as 4.2.1 Array literals: optionally block-like. For example, the following are all valid (not an exhaustive list):

const a = {
  a: 0,
  b: 1,
};

const b =
    {a: 0, b: 1};
const c = {a: 0, b: 1};

someMethod(foo, {
  a: 0, b: 1,
}, bar);

4.2.3 Class literals

Class literals (whether declarations or expressions) are indented as blocks. Do not add semicolons after methods, or after the closing brace of a class declaration (statements—such as assignments—that contain class expressions are still terminated with a semicolon). Use the extends keyword, but not the @extends JSDoc annotation unless the class extends a templatized type.

Example:

class Foo {
  constructor() {
    /** @type {number} */
    this.x = 42;
  }

  /** @return {number} */
  method() {
    return this.x;
  }
}
Foo.Empty = class {};
/** @extends {Foo<string>} */
foo.Bar = class extends Foo {
  /** @override */
  method() {
    return super.method() / 2;
  }
};

/** @interface */
class Frobnicator {
  /** @param {string} message */
  frobnicate(message) {}
}

4.2.4 Function expressions

When declaring an anonymous function in the list of arguments for a function call, the body of the function is indented two spaces more than the preceding indentation depth.

Example:

prefix.something.reallyLongFunctionName('whatever', (a1, a2) => {
  // Indent the function body +2 relative to indentation depth
  // of the 'prefix' statement one line above.
  if (a1.equals(a2)) {
    someOtherLongFunctionName(a1);
  } else {
    andNowForSomethingCompletelyDifferent(a2.parrot);
  }
});

some.reallyLongFunctionCall(arg1, arg2, arg3)
    .thatsWrapped()
    .then((result) => {
      // Indent the function body +2 relative to the indentation depth
      // of the '.then()' call.
      if (result) {
        result.use();
      }
    });

4.2.5 Switch statements

As with any other block, the contents of a switch block are indented +2.

After a switch label, a newline appears, and the indentation level is increased +2, exactly as if a block were being opened. An explicit block may be used if required by lexical scoping. The following switch label returns to the previous indentation level, as if a block had been closed.

A blank line is optional between a break and the following case.

Example:

switch (animal) {
  case Animal.BANDERSNATCH:
    handleBandersnatch();
    break;

  case Animal.JABBERWOCK:
    handleJabberwock();
    break;

  default:
    throw new Error('Unknown animal');
}

4.3 Statements

4.3.1 One statement per line

Each statement is followed by a line-break.

4.3.2 Semicolons are required

Every statement must be terminated with a semicolon. Relying on automatic semicolon insertion is forbidden.

4.4 Column limit: 80

JavaScript code has a column limit of 80 characters. Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in 4.5 Line-wrapping.

Exceptions:

  1. Lines where obeying the column limit is not possible (for example, a long URL in JSDoc or a shell command intended to be copied-and-pasted).
  2. goog.module and goog.require statements (see 3.3 goog.module statement and 3.4 goog.require statements).

4.5 Line-wrapping

Terminology NoteLine-wrapping is defined as breaking a single expression into multiple lines.

There is no comprehensive, deterministic formula showing exactly how to line-wrap in every situation. Very often there are several valid ways to line-wrap the same piece of code.

Note: While the typical reason for line-wrapping is to avoid overflowing the column limit, even code that would in fact fit within the column limit may be line-wrapped at the author's discretion.

Tip: Extracting a method or local variable may solve the problem without the need to line-wrap.

4.5.1 Where to break

The prime directive of line-wrapping is: prefer to break at a higher syntactic level.

Preferred:

currentEstimate =
    calc(currentEstimate + x * currentEstimate) /
        2.0f;

Discouraged:

currentEstimate = calc(currentEstimate + x *
    currentEstimate) / 2.0f;

In the preceding example, the syntactic levels from highest to lowest are as follows: assignment, division, function call, parameters, number constant.

Operators are wrapped as follows:

  1. When a line is broken at an operator the break comes after the symbol. (Note that this is not the same practice used in Google style for Java.)
    1. This does not apply to the dot (.), which is not actually an operator.
  2. A method or constructor name stays attached to the open parenthesis (() that follows it.
  3. A comma (,) stays attached to the token that precedes it.

Note: The primary goal for line wrapping is to have clear code, not necessarily code that fits in the smallest number of lines.

4.5.2 Indent continuation lines at least +4 spaces

When line-wrapping, each line after the first (each continuation line) is indented at least +4 from the original line, unless it falls under the rules of block indentation.

When there are multiple continuation lines, indentation may be varied beyond +4 as appropriate. In general, continuation lines at a deeper syntactic level are indented by larger multiples of 4, and two lines use the same indentation level if and only if they begin with syntactically parallel elements.

4.6.3 Horizontal alignment: discouraged addresses the discouraged practice of using a variable number of spaces to align certain tokens with previous lines.

4.6 Whitespace

4.6.1 Vertical whitespace

A single blank line appears:

  1. Between consecutive methods in a class or object literal
    1. Exception: A blank line between two consecutive properties definitions in an object literal (with no other code between them) is optional. Such blank lines are used as needed to create logical groupings of fields.
  2. Within method bodies, sparingly to create logical groupings of statements. Blank lines at the start or end of a function body are not allowed.
  3. Optionally before the first or after the last method in a class or object literal (neither encouraged nor discouraged).
  4. As required by other sections of this document (e.g. 3.4 goog.require statements).

Multiple consecutive blank lines are permitted, but never required (nor encouraged).

4.6.2 Horizontal whitespace

Use of horizontal whitespace depends on location, and falls into three broad categories: leading (at the start of a line), trailing (at the end of a line), and internal. Leading whitespace (i.e., indentation) is addressed elsewhere. Trailing whitespace is forbidden.

Beyond where required by the language or other style rules, and apart from literals, comments, and JSDoc, a single internal ASCII space also appears in the following places only.

  1. Separating any reserved word (such as iffor, or catch) from an open parenthesis (() that follows it on that line.
  2. Separating any reserved word (such as else or catch) from a closing curly brace (}) that precedes it on that line.
  3. Before any open curly brace ({), with two exceptions:
    1. Before an object literal that is the first argument of a function or the first element in an array literal (e.g. foo({a: [{c: d}]})).
    2. In a template expansion, as it is forbidden by the language (e.g. abc${1 + 2}def).
  4. On both sides of any binary or ternary operator.
  5. After a comma (,) or semicolon (;). Note that spaces are never allowed before these characters.
  6. After the colon (:) in an object literal.
  7. On both sides of the double slash (//) that begins an end-of-line comment. Here, multiple spaces are allowed, but not required.
  8. After an open-JSDoc comment character and on both sides of close characters (e.g. for short-form type declarations or casts: this.foo = /** @type {number} */ (bar); or function(/** string */ foo) {).

4.6.3 Horizontal alignment: discouraged

Terminology NoteHorizontal alignment is the practice of adding a variable number of additional spaces in your code with the goal of making certain tokens appear directly below certain other tokens on previous lines.

This practice is permitted, but it is generally discouraged by Google Style. It is not even required to maintain horizontal alignment in places where it was already used.

Here is an example without alignment, followed by one with alignment. Both are allowed, but the latter is discouraged:

{
  tiny: 42, // this is great
  longer: 435, // this too
};

{
  tiny:   42,  // permitted, but future edits
  longer: 435, // may leave it unaligned
};

Tip: Alignment can aid readability, but it creates problems for future maintenance. Consider a future change that needs to touch just one line. This change may leave the formerly-pleasing formatting mangled, and that is allowed. More often it prompts the coder (perhaps you) to adjust whitespace on nearby lines as well, possibly triggering a cascading series of reformattings. That one-line change now has a blast radius. This can at worst result in pointless busywork, but at best it still corrupts version history information, slows down reviewers and exacerbates merge conflicts.

4.6.4 Function arguments

Prefer to put all function arguments on the same line as the function name. If doing so would exceed the 80-column limit, the arguments must be line-wrapped in a readable way. To save space, you may wrap as close to 80 as possible, or put each argument on its own line to enhance readability. Indentation should be four spaces. Aligning to the parenthesis is allowed, but discouraged. Below are the most common patterns for argument wrapping:

// Arguments start on a new line, indented four spaces. Preferred when the
// arguments don't fit on the same line with the function name (or the keyword
// "function") but fit entirely on the second line. Works with very long
// function names, survives renaming without reindenting, low on space.
doSomething(
    descriptiveArgumentOne, descriptiveArgumentTwo, descriptiveArgumentThree) {
  // …
}

// If the argument list is longer, wrap at 80. Uses less vertical space,
// but violates the rectangle rule and is thus not recommended.
doSomething(veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,
    tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {
  // …
}

// Four-space, one argument per line.  Works with long function names,
// survives renaming, and emphasizes each argument.
doSomething(
    veryDescriptiveArgumentNumberOne,
    veryDescriptiveArgumentTwo,
    tableModelEventHandlerProxy,
    artichokeDescriptorAdapterIterator) {
  // …
}

4.7 Grouping parentheses: recommended

Optional grouping parentheses are omitted only when the author and reviewer agree that there is no reasonable chance that the code will be misinterpreted without them, nor would they have made the code easier to read. It is not reasonable to assume that every reader has the entire operator precedence table memorized.

Do not use unnecessary parentheses around the entire expression following deletetypeofvoidreturnthrowcaseinof, or yield.

Parentheses are required for type casts: /** @type {!Foo} */ (foo).

4.8 Comments

This section addresses implementation comments. JSDoc is addressed separately in 7 JSDoc.

4.8.1 Block comment style

Block comments are indented at the same level as the surrounding code. They may be in /* … */ or //-style. For multi-line /* … */ comments, subsequent lines must start with * aligned with the * on the previous line, to make comments obvious with no extra context. “Parameter name” comments should appear after values whenever the value and method name do not sufficiently convey the meaning.

/*
 * This is
 * okay.
 */

// And so
// is this.

/* This is fine, too. */

someFunction(obviousParam, true /* shouldRender */, 'hello' /* name */);

Comments are not enclosed in boxes drawn with asterisks or other characters.

Do not use JSDoc (/** … */) for any of the above implementation comments.

5 Language features

JavaScript includes many dubious (and even dangerous) features. This section delineates which features may or may not be used, and any additional constraints on their use.

5.1 Local variable declarations

5.1.1 Use const and let

Declare all local variables with either const or let. Use const by default, unless a variable needs to be reassigned. The var keyword must not be used.

5.1.2 One variable per declaration

Every local variable declaration declares only one variable: declarations such as let a = 1, b = 2; are not used.

5.1.3 Declared when needed, initialized as soon as possible

Local variables are not habitually declared at the start of their containing block or block-like construct. Instead, local variables are declared close to the point they are first used (within reason), to minimize their scope.

5.1.4 Declare types as needed

JSDoc type annotations may be added either on the line above the declaration, or else inline before the variable name.

Example:

const /** !Array<number> */ data = [];

/** @type {!Array<number>} */
const data = [];

Tip: There are many cases where the compiler can infer a templatized type but not its parameters. This is particularly the case when the initializing literal or constructor call does not include any values of the template parameter type (e.g., empty arrays, objects, Maps, or Sets), or if the variable is modified in a closure. Local variable type annotations are particularly helpful in these cases since otherwise the compiler will infer the template parameter as unknown.

5.2 Array literals

5.2.1 Use trailing commas

Include a trailing comma whenever there is a line break between the final element and the closing bracket.

Example:

const values = [
  'first value',
  'second value',
];

5.2.2 Do not use the variadic Array constructor

The constructor is error-prone if arguments are added or removed. Use a literal instead.

Illegal:

const a1 = new Array(x1, x2, x3);
const a2 = new Array(x1, x2);
const a3 = new Array(x1);
const a4 = new Array();

This works as expected except for the third case: if x1 is a whole number then a3 is an array of size x1 where all elements are undefined. If x1 is any other number, then an exception will be thrown, and if it is anything else then it will be a single-element array.

Instead, write

const a1 = [x1, x2, x3];
const a2 = [x1, x2];
const a3 = [x1];
const a4 = [];

Explicitly allocating an array of a given length using new Array(length) is allowed when appropriate.

5.2.3 Non-numeric properties

Do not define or use non-numeric properties on an array (other than length). Use a Map (or Object) instead.

5.2.4 Destructuring

Array literals may be used on the left-hand side of an assignment to perform destructuring (such as when unpacking multiple values from a single array or iterable). A final rest element may be included (with no space between the ... and the variable name). Elements should be omitted if they are unused.

const [a, b, c, ...rest] = generateResults();
let [, b,, d] = someArray;

Destructuring may also be used for function parameters (note that a parameter name is required but ignored). Always specify [] as the default value if a destructured array parameter is optional, and provide default values on the left hand side:

/** @param {!Array<number>=} param1 */
function optionalDestructuring([a = 4, b = 2] = []) {  };

Illegal:

function badDestructuring([a, b] = [4, 2]) {  };

Tip: For (un)packing multiple values into a function’s parameter or return, prefer object destructuring to array destructuring when possible, as it allows naming the individual elements and specifying a different type for each.*

5.2.5 Spread operator

Array literals may include the spread operator (...) to flatten elements out of one or more other iterables. The spread operator should be used instead of more awkward constructs with Array.prototype. There is no space after the ....

Example:

[...foo]   // preferred over Array.prototype.slice.call(foo)
[...foo, ...bar]   // preferred over foo.concat(bar)

5.3 Object literals

5.3.1 Use trailing commas

Include a trailing comma whenever there is a line break between the final property and the closing brace.

5.3.2 Do not use the Object constructor

While Object does not have the same problems as Array, it is still disallowed for consistency. Use an object literal ({} or {a: 0, b: 1, c: 2}) instead.

5.3.3 Do not mix quoted and unquoted keys

Object literals may represent either structs (with unquoted keys and/or symbols) or dicts (with quoted and/or computed keys). Do not mix these key types in a single object literal.

Illegal:

{
  a: 42, // struct-style unquoted key
  'b': 43, // dict-style quoted key
}

5.3.4 Computed property names

Computed property names (e.g., {['key' + foo()]: 42}) are allowed, and are considered dict-style (quoted) keys (i.e., must not be mixed with non-quoted keys) unless the computed property is a symbol (e.g., [Symbol.iterator]). Enum values may also be used for computed keys, but should not be mixed with non-enum keys in the same literal.

5.3.5 Method shorthand

Methods can be defined on object literals using the method shorthand ({method() {… }}) in place of a colon immediately followed by a function or arrow function literal.

Example:

return {
  stuff: 'candy',
  method() {
    return this.stuff;  // Returns 'candy'
  },
};

Note that this in a method shorthand or function refers to the object literal itself whereas this in an arrow function refers to the scope outside the object literal.

Example:

class {
  getObjectLiteral() {
    this.stuff = 'fruit';
    return {
      stuff: 'candy',
      method: () => this.stuff,  // Returns 'fruit'
    };
  }
}

5.3.6 Shorthand properties

Shorthand properties are allowed on object literals.

Example:

const foo = 1;
const bar = 2;
const obj = {
  foo,
  bar,
  method() { return this.foo + this.bar; },
};
assertEquals(3, obj.method());

5.3.7 Destructuring

Object destructuring patterns may be used on the left-hand side of an assignment to perform destructuring and unpack multiple values from a single object.

Destructured objects may also be used as function parameters, but should be kept as simple as possible: a single level of unquoted shorthand properties. Deeper levels of nesting and computed properties may not be used in parameter destructuring. Specify any default values in the left-hand-side of the destructured parameter ({str = 'some default'} = {}, rather than {str} = {str: 'some default'}), and if a destructured object is itself optional, it must default to {}. The JSDoc for the destructured parameter may be given any name (the name is unused but is required by the compiler).

Example:

/**
 * @param {string} ordinary
 * @param {{num: (number|undefined), str: (string|undefined)}=} param1
 *     num: The number of times to do something.
 *     str: A string to do stuff to.
 */
function destructured(ordinary, {num, str = 'some default'} = {})

Illegal:

/** @param {{x: {num: (number|undefined), str: (string|undefined)}}} param1 */
function nestedTooDeeply({x: {num, str}}) {};
/** @param {{num: (number|undefined), str: (string|undefined)}=} param1 */
function nonShorthandProperty({num: a, str: b} = {}) {};
/** @param {{a: number, b: number}} param1 */
function computedKey({a, b, [a + b]: c}) {};
/** @param {{a: number, b: string}=} param1 */
function nontrivialDefault({a, b} = {a: 2, b: 4}) {};

Destructuring may also be used for goog.require statements, and in this case must not be wrapped: the entire statement occupies one line, regardless of how long it is (see 3.4 goog.require statements).

5.3.8 Enums

Enumerations are defined by adding the @enum annotation to an object literal. Additional properties may not be added to an enum after it is defined. Enums must be constant, and all enum values must be deeply immutable.

/**
 * Supported temperature scales.
 * @enum {string}
 */
const TemperatureScale = {
  CELSIUS: 'celsius',
  FAHRENHEIT: 'fahrenheit',
};

/**
 * An enum with two options.
 * @enum {number}
 */
const Option = {
  /** The option used shall have been the first. */
  FIRST_OPTION: 1,
  /** The second among two options. */
  SECOND_OPTION: 2,
};

5.4 Classes

5.4.1 Constructors

Constructors are optional for concrete classes. Subclass constructors must call super() before setting any fields or otherwise accessing this. Interfaces must not define a constructor.

5.4.2 Fields

Set all of a concrete object’s fields (i.e. all properties other than methods) in the constructor. Annotate fields that are never reassigned with @const (these need not be deeply immutable). Private fields must be annotated with @private and their names must end with a trailing underscore. Fields are never set on a concrete class' prototype.

Example:

class Foo {
  constructor() {
    /** @private @const {!Bar} */
    this.bar_ = computeBar();
  }
}

Tip: Properties should never be added to or removed from an instance after the constructor is finished, since it significantly hinders VMs’ ability to optimize. If necessary, fields that are initialized later should be explicitly set to undefined in the constructor to prevent later shape changes. Adding @struct to an object will check that undeclared properties are not added/accessed. Classes have this added by default.

5.4.3 Computed properties

Computed properties may only be used in classes when the property is a symbol. Dict-style properties (that is, quoted or computed non-symbol keys, as defined in 5.3.3 Do not mix quoted and unquoted keys) are not allowed. A [Symbol.iterator] method should be defined for any classes that are logically iterable. Beyond this, Symbol should be used sparingly.

Tip: be careful of using any other built-in symbols (e.g., Symbol.isConcatSpreadable) as they are not polyfilled by the compiler and will therefore not work in older browsers.

5.4.4 Static methods

Where it does not interfere with readability, prefer module-local functions over private static methods.

Static methods should only be called on the base class itself. Static methods should not be called on variables containing a dynamic instance that may be either the constructor or a subclass constructor (and must be defined with @nocollapse if this is done), and must not be called directly on a subclass that doesn’t define the method itself.

Illegal:

class Base { /** @nocollapse */ static foo() {} }
class Sub extends Base {}
function callFoo(cls) { cls.foo(); }  // discouraged: don't call static methods dynamically
Sub.foo();  // illegal: don't call static methods on subclasses that don't define it themselves

5.4.5 Old-style class declarations

While ES6 classes are preferred, there are cases where ES6 classes may not be feasible. For example:

  1. If there exist or will exist subclasses, including frameworks that create subclasses, that cannot be immediately changed to use ES6 class syntax. If such a class were to use ES6 syntax, all downstream subclasses not using ES6 class syntax would need to be modified.

  2. Frameworks that require a known this value before calling the superclass constructor, since constructors with ES6 super classes do not have access to the instance thisvalue until the call to super returns.

In all other ways the style guide still applies to this code: letconst, default parameters, rest, and arrow functions should all be used when appropriate.

goog.defineClass allows for a class-like definition similar to ES6 class syntax:

let C = goog.defineClass(S, {
  /**
   * @param {string} value
   */
  constructor(value) {
    S.call(this, 2);
    /** @const */
    this.prop = value;
  },

  /**
   * @param {string} param
   * @return {number}
   */
  method(param) {
    return 0;
  },
});

Alternatively, while goog.defineClass should be preferred for all new code, more traditional syntax is also allowed.

/**
  * @constructor @extends {S}
  * @param {string} value
  */
function C(value) {
  S.call(this, 2);
  /** @const */
  this.prop = value;
}
goog.inherits(C, S);

/**
 * @param {string} param
 * @return {number}
 */
C.prototype.method = function(param) {
  return 0;
};

Per-instance properties should be defined in the constructor after the call to the super class constructor, if there is a super class. Methods should be defined on the prototype of the constructor.

Defining constructor prototype hierarchies correctly is harder than it first appears! For that reason, it is best to use goog.inherits from the Closure Library .

5.4.6 Do not manipulate prototypes directly

The class keyword allows clearer and more readable class definitions than defining prototype properties. Ordinary implementation code has no business manipulating these objects, though they are still useful for defining @record interfaces and classes as defined in 5.4.5 Old-style class declarations. Mixins and modifying the prototypes of builtin objects are explicitly forbidden.

Exception: Framework code (such as Polymer, or Angular) may need to use prototypes, and should not resort to even-worse workarounds to avoid doing so.

Exception: Defining fields in interfaces (see 5.4.9 Interfaces).

5.4.7 Getters and Setters

Do not use JavaScript getter and setter properties. They are potentially surprising and difficult to reason about, and have limited support in the compiler. Provide ordinary methods instead.

Exception: when working with data binding frameworks (such as Angular and Polymer), getters and setters may be used sparingly. Note, however, that compiler support is limited. When they are used, they must be defined either with get foo() and set foo(value) in the class or object literal, or if that is not possible, with Object.defineProperties. Do not useObject.defineProperty, which interferes with property renaming. Getters must not change observable state.

Illegal:

class Foo {
  get next() { return this.nextId++; }
}

5.4.8 Overriding toString

The toString method may be overridden, but must always succeed and never have visible side effects.

Tip: Beware, in particular, of calling other methods from toString, since exceptional conditions could lead to infinite loops.

5.4.9 Interfaces

Interfaces may be declared with @interface or @record. Interfaces declared with @record can be explicitly (i.e. via @implements) or implicitly implemented by a class or object literal.

All non-static method bodies on an interface must be empty blocks. Fields must be defined after the interface body as stubs on the prototype.

Example:

/**
 * Something that can frobnicate.
 * @record
 */
class Frobnicator {
  /**
   * Performs the frobnication according to the given strategy.
   * @param {!FrobnicationStrategy} strategy
   */
  frobnicate(strategy) {}
}

/** @type {number} The number of attempts before giving up. */
Frobnicator.prototype.attempts;

5.5 Functions

5.5.1 Top-level functions

Exported functions may be defined directly on the exports object, or else declared locally and exported separately. Non-exported functions are encouraged and should not be declared @private.

Examples:

/** @return {number} */
function helperFunction() {
  return 42;
}
/** @return {number} */
function exportedFunction() {
  return helperFunction() * 2;
}
/**
 * @param {string} arg
 * @return {number}
 */
function anotherExportedFunction(arg) {
  return helperFunction() / arg.length;
}
/** @const */
exports = {exportedFunction, anotherExportedFunction};
/** @param {string} arg */
exports.foo = (arg) => {
  // do some stuff ...
};

5.5.2 Nested functions and closures

Functions may contain nested function definitions. If it is useful to give the function a name, it should be assigned to a local const.

5.5.3 Arrow functions

Arrow functions provide a concise syntax and fix a number of difficulties with this. Prefer arrow functions over the function keyword, particularly for nested functions (but see 5.3.5 Method shorthand).

Prefer using arrow functions over f.bind(this), and especially over goog.bind(f, this). Avoid writing const self = this. Arrow functions are particularly useful for callbacks, which sometimes pass unexpected additional arguments.

The right-hand side of the arrow may be a single expression or a block. Parentheses around the arguments are optional if there is only a single non-destructured argument.

Tip: It is a good practice to use parentheses even for single-argument arrows, since the code may still parse reasonably (but incorrectly) if the parentheses are forgotten when an additional argument is added.

5.5.4 Generators

Generators enable a number of useful abstractions and may be used as needed.

When defining generator functions, attach the * to the function keyword when present, and separate it with a space from the name of the function. When using delegating yields, attach the * to the yield keyword.

Example:

/** @return {!Iterator<number>} */
function* gen1() {
  yield 42;
}

/** @return {!Iterator<number>} */
const gen2 = function*() {
  yield* gen1();
}

class SomeClass {
  /** @return {!Iterator<number>} */
  * gen() {
    yield 42;
  }
}

5.5.5 Parameters

Function parameters must be typed with JSDoc annotations in the JSDoc preceding the function’s definition, except in the case of same-signature @overrides, where all types are omitted.

Parameter types may be specified inline, immediately before the parameter name (as in (/** number */ foo, /** string */ bar) => foo + bar). Inline and @param type annotations must not be mixed in the same function definition.

5.5.5.1 Default parameters

Optional parameters are permitted using the equals operator in the parameter list. Optional parameters must include spaces on both sides of the equals operator, be named exactly like required parameters (i.e., not prefixed with opt_), use the = suffix in their JSDoc type, come after required parameters, and not use initializers that produce observable side effects. All optional parameters must have a default value in the function declaration, even if that value is undefined.

Example:

/**
 * @param {string} required This parameter is always needed.
 * @param {string=} optional This parameter can be omitted.
 * @param {!Node=} node Another optional parameter.
 */
function maybeDoSomething(required, optional = '', node = undefined) {}

Use default parameters sparingly. Prefer destructuring (as in 5.3.7 Destructuring) to create readable APIs when there are more than a small handful of optional parameters that do not have a natural order.

Note: Unlike Python's default parameters, it is okay to use initializers that return new mutable objects (such as {} or []) because the initializer is evaluated each time the default value is used, so a single object won't be shared across invocations.

Tip: While arbitrary expressions including function calls may be used as initializers, these should be kept as simple as possible. Avoid initializers that expose shared mutable state, as that can easily introduce unintended coupling between function calls.

5.5.5.2 Rest parameters

Use a rest parameter instead of accessing arguments. Rest parameters are typed with a ... prefix in their JSDoc. The rest parameter must be the last parameter in the list. There is no space between the ... and the parameter name. Do not name the rest parameter var_args. Never name a local variable or parameter arguments, which confusingly shadows the built-in name.

Example:

/**
 * @param {!Array<string>} array This is an ordinary parameter.
 * @param {...number} numbers The remainder of arguments are all numbers.
 */
function variadic(array, ...numbers) {}

5.5.6 Returns

Function return types must be specified in the JSDoc directly above the function definition, except in the case of same-signature @overrides where all types are omitted.

5.5.7 Generics

Declare generic functions and methods when necessary with @template TYPE in the JSDoc above the class definition.

5.5.8 Spread operator

Function calls may use the spread operator (...). Prefer the spread operator to Function.prototype.apply when an array or iterable is unpacked into multiple parameters of a variadic function. There is no space after the ....

Example:

function myFunction(...elements) {}
myFunction(...array, ...iterable, ...generator());

5.6 String literals

5.6.1 Use single quotes

Ordinary string literals are delimited with single quotes ('), rather than double quotes (").

Tip: if a string contains a single quote character, consider using a template string to avoid having to escape the quote.

Ordinary string literals may not span multiple lines.

5.6.2 Template strings

Use template strings (delimited with `) over complex string concatenation, particularly if multiple string literals are involved. Template strings may span multiple lines.

If a template string spans multiple lines, it does not need to follow the indentation of the enclosing block, though it may if the added whitespace does not matter.

Example:

function arithmetic(a, b) {
  return `Here is a table of arithmetic operations:
${a} + ${b} = ${a + b}
${a} - ${b} = ${a - b}
${a} * ${b} = ${a * b}
${a} / ${b} = ${a / b}`;
}

5.6.3 No line continuations

Do not use line continuations (that is, ending a line inside a string literal with a backslash) in either ordinary or template string literals. Even though ES5 allows this, it can lead to tricky errors if any trailing whitespace comes after the slash, and is less obvious to readers.

Illegal:

const longString = 'This is a very long string that far exceeds the 80 \
    column limit. It unfortunately contains long stretches of spaces due \
    to how the continued lines are indented.';

Instead, write

const longString = 'This is a very long string that far exceeds the 80 ' +
    'column limit. It does not contain long stretches of spaces since ' +
    'the concatenated strings are cleaner.';

5.7 Number literals

Numbers may be specified in decimal, hex, octal, or binary. Use exactly 0x0o, and 0b prefixes, with lowercase letters, for hex, octal, and binary, respectively. Never include a leading zero unless it is immediately followed by xo, or b.

5.8 Control structures

5.8.1 For loops

With ES6, the language now has three different kinds of for loops. All may be used, though for-of loops should be preferred when possible.

for-in loops may only be used on dict-style objects (see 5.3.3 Do not mix quoted and unquoted keys), and should not be used to iterate over an array.Object.prototype.hasOwnProperty should be used in for-in loops to exclude unwanted prototype properties. Prefer for-of and Object.keys over for-in when possible.

5.8.2 Exceptions

Exceptions are an important part of the language and should be used whenever exceptional cases occur. Always throw Errors or subclasses of Error: never throw string literals or other objects. Always use new when constructing an Error.

Custom exceptions provide a great way to convey additional error information from functions. They should be defined and used wherever the native Error type is insufficient.

Prefer throwing exceptions over ad-hoc error-handling approaches (such as passing an error container reference type, or returning an object with an error property).

5.8.2.1 Empty catch blocks

It is very rarely correct to do nothing in response to a caught exception. When it truly is appropriate to take no action whatsoever in a catch block, the reason this is justified is explained in a comment.

try {
  return handleNumericResponse(response);
} catch (ok) {
  // it's not numeric; that's fine, just continue
}
return handleTextResponse(response);

Illegal:

   try {
    shouldFail();
    fail('expected an error');
  }
  catch (expected) {}

Tip: Unlike in some other languages, patterns like the above simply don’t work since this will catch the error thrown by fail. Use assertThrows() instead.

5.8.3 Switch statements

Terminology Note: Inside the braces of a switch block are one or more statement groups. Each statement group consists of one or more switch labels (either case FOO: or default:), followed by one or more statements.

5.8.3.1 Fall-through: commented

Within a switch block, each statement group either terminates abruptly (with a breakreturn or thrown exception), or is marked with a comment to indicate that execution will or might continue into the next statement group. Any comment that communicates the idea of fall-through is sufficient (typically // fall through). This special comment is not required in the last statement group of the switch block.

Example:

switch (input) {
  case 1:
  case 2:
    prepareOneOrTwo();
  // fall through
  case 3:
    handleOneTwoOrThree();
    break;
  default:
    handleLargeNumber(input);
}
5.8.3.2 The default case is present

Each switch statement includes a default statement group, even if it contains no code.

5.9 this

Only use this in class constructors and methods, or in arrow functions defined within class constructors and methods. Any other uses of this must have an explicit @this declared in the immediately-enclosing function’s JSDoc.

Never use this to refer to the global object, the context of an eval, the target of an event, or unnecessarily call()ed or apply()ed functions.

5.10 Disallowed features

5.10.1 with

Do not use the with keyword. It makes your code harder to understand and has been banned in strict mode since ES5.

5.10.2 Dynamic code evaluation

Do not use eval or the Function(...string) constructor (except for code loaders). These features are potentially dangerous and simply do not work in CSP environments.

5.10.3 Automatic semicolon insertion

Always terminate statements with semicolons (except function and class declarations, as noted above).

5.10.4 Non-standard features

Do not use non-standard features. This includes old features that have been removed (e.g., WeakMap.clear), new features that are not yet standardized (e.g., the current TC39 working draft, proposals at any stage, or proposed but not-yet-complete web standards), or proprietary features that are only implemented in some browsers. Use only features defined in the current ECMA-262 or WHATWG standards. (Note that projects writing against specific APIs, such as Chrome extensions or Node.js, can obviously use those APIs). Non-standard language “extensions” (such as those provided by some external transpilers) are forbidden.

5.10.5 Wrapper objects for primitive types

Never use new on the primitive object wrappers (BooleanNumberStringSymbol), nor include them in type annotations.

Illegal:

const /** Boolean */ x = new Boolean(false);
if (x) alert(typeof x);  // alerts 'object' - WAT?

The wrappers may be called as functions for coercing (which is preferred over using + or concatenating the empty string) or creating symbols.

Example:

const /** boolean */ x = Boolean(0);
if (!x) alert(typeof x);  // alerts 'boolean', as expected

5.10.6 Modifying builtin objects

Never modify builtin types, either by adding methods to their constructors or to their prototypes. Avoid depending on libraries that do this. Note that the JSCompiler’s runtime library will provide standards-compliant polyfills where possible; nothing else may modify builtin objects.

Do not add symbols to the global object unless absolutely necessary (e.g. required by a third-party API).

6 Naming

6.1 Rules common to all identifiers

Identifiers use only ASCII letters and digits, and, in a small number of cases noted below, underscores and very rarely (when required by frameworks like Angular) dollar signs.

Give as descriptive a name as possible, within reason. Do not worry about saving horizontal space as it is far more important to make your code immediately understandable by a new reader. Do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word.

priceCountReader      // No abbreviation.
numErrors             // "num" is a widespread convention.
numDnsConnections     // Most people know what "DNS" stands for.

Illegal:

n                     // Meaningless.
nErr                  // Ambiguous abbreviation.
nCompConns            // Ambiguous abbreviation.
wgcConnections        // Only your group knows what this stands for.
pcReader              // Lots of things can be abbreviated "pc".
cstmrId               // Deletes internal letters.
kSecondsPerDay        // Do not use Hungarian notation.

6.2 Rules by identifier type

6.2.1 Package names

Package names are all lowerCamelCase. For example, my.exampleCode.deepSpace, but not my.examplecode.deepspace or my.example_code.deep_space.

6.2.2 Class names

Class, interface, record, and typedef names are written in UpperCamelCase. Unexported classes are simply locals: they are not marked @private and therefore are not named with a trailing underscore.

Type names are typically nouns or noun phrases. For example, RequestImmutableList, or VisibilityMode. Additionally, interface names may sometimes be adjectives or adjective phrases instead (for example, Readable).

6.2.3 Method names

Method names are written in lowerCamelCase. Private methods’ names must end with a trailing underscore.

Method names are typically verbs or verb phrases. For example, sendMessage or stop_. Getter and setter methods for properties are never required, but if they are used they should be named getFoo (or optionally isFoo or hasFoo for booleans), or setFoo(value) for setters.

Underscores may also appear in JsUnit test method names to separate logical components of the name. One typical pattern is test<MethodUnderTest>_<state>, for example testPop_emptyStack. There is no One Correct Way to name test methods.

6.2.4 Enum names

Enum names are written in UpperCamelCase, similar to classes, and should generally be singular nouns. Individual items within the enum are named in CONSTANT_CASE.

6.2.5 Constant names

Constant names use CONSTANT_CASE: all uppercase letters, with words separated by underscores. There is no reason for a constant to be named with a trailing underscore, since private static properties can be replaced by (implicitly private) module locals.

6.2.5.1 Definition of “constant”

Every constant is a @const static property or a module-local const declaration, but not all @const static properties and module-local consts are constants. Before choosing constant case, consider whether the field really feels like a deeply immutable constant. For example, if any of that instance's observable state can change, it is almost certainly not a constant. Merely intending to never mutate the object is generally not enough.

Examples:

// Constants
const NUMBER = 5;
/** @const */ exports.NAMES = ImmutableList.of('Ed', 'Ann');
/** @enum */ exports.SomeEnum = { ENUM_CONSTANT: 'value' };

// Not constants
let letVariable = 'non-const';
class MyClass { constructor() { /** @const */ this.nonStatic = 'non-static'; } };
/** @type {string} */ MyClass.staticButMutable = 'not @const, can be reassigned';
const /** Set<String> */ mutableCollection = new Set();
const /** ImmutableSet<SomeMutableType> */ mutableElements = ImmutableSet.of(mutable);
const Foo = goog.require('my.Foo');  // mirrors imported name
const logger = log.getLogger('loggers.are.not.immutable');

Constants’ names are typically nouns or noun phrases.

6.2.5.1 Local aliases

Local aliases should be used whenever they improve readability over fully-qualified names. Follow the same rules as goog.requires (3.4 goog.require statements), maintaining the last part of the aliased name. Aliases may also be used within functions. Aliases must be const.

Examples:

const staticHelper = importedNamespace.staticHelper;
const CONSTANT_NAME = ImportedClass.CONSTANT_NAME;
const {assert, assertInstanceof} = asserts;

6.2.6 Non-constant field names

Non-constant field names (static or otherwise) are written in lowerCamelCase, with a trailing underscore for private fields.

These names are typically nouns or noun phrases. For example, computedValues or index_.

6.2.7 Parameter names

Parameter names are written in lowerCamelCase. Note that this applies even if the parameter expects a constructor.

One-character parameter names should not be used in public methods.

Exception: When required by a third-party framework, parameter names may begin with a $. This exception does not apply to any other identifiers (e.g. local variables or properties).

6.2.8 Local variable names

Local variable names are written in lowerCamelCase, except for module-local (top-level) constants, as described above. Constants in function scopes are still named in lowerCamelCase. Note that lowerCamelCase applies even if the variable holds a constructor.

6.2.9 Template parameter names

Template parameter names should be concise, single-word or single-letter identifiers, and must be all-caps, such as TYPE or THIS.

6.3 Camel case: defined

Sometimes there is more than one reasonable way to convert an English phrase into camel case, such as when acronyms or unusual constructs like IPv6 or iOS are present. To improve predictability, Google Style specifies the following (nearly) deterministic scheme.

Beginning with the prose form of the name:

  1. Convert the phrase to plain ASCII and remove any apostrophes. For example, Müller's algorithm might become Muellers algorithm.
  2. Divide this result into words, splitting on spaces and any remaining punctuation (typically hyphens).
    1. Recommended: if any word already has a conventional camel case appearance in common usage, split this into its constituent parts (e.g., AdWords becomes ad words). Note that a word such as iOS is not really in camel case per se; it defies any convention, so this recommendation does not apply.
  3. Now lowercase everything (including acronyms), then uppercase only the first character of:
    1. … each word, to yield upper camel case, or
    2. … each word except the first, to yield lower camel case
  4. Finally, join all the words into a single identifier.

Note that the casing of the original words is almost entirely disregarded.

Examples:

Prose formCorrectIncorrect
XML HTTP requestXmlHttpRequestXMLHTTPRequest
new customer IDnewCustomerIdnewCustomerID
inner stopwatchinnerStopwatchinnerStopWatch
supports IPv6 on iOS?supportsIpv6OnIossupportsIPv6OnIOS
YouTube importerYouTubeImporterYoutubeImporter*

*Acceptable, but not recommended.

Note: Some words are ambiguously hyphenated in the English language: for example nonempty and non-empty are both correct, so the method names checkNonempty and checkNonEmpty are likewise both correct.

7 JSDoc

JSDoc is used on all classes, fields, and methods.

7.1 General form

The basic formatting of JSDoc blocks is as seen in this example:

/**
 * Multiple lines of JSDoc text are written here,
 * wrapped normally.
 * @param {number} arg A number to do something to.
 */
function doSomething(arg) {  }

or in this single-line example:

/** @const @private {!Foo} A short bit of JSDoc. */
this.foo_ = foo;

If a single-line comment overflows into multiple lines, it must use the multi-line style with /** and */ on their own lines.

Many tools extract metadata from JSDoc comments to perform code validation and optimization. As such, these comments must be well-formed.

7.2 Markdown

JSDoc is written in Markdown, though it may include HTML when necessary.

Note that tools that automatically extract JSDoc (e.g. JsDossier) will often ignore plain text formatting, so if you did this:

/**
 * Computes weight based on three factors:
 *   items sent
 *   items received
 *   last timestamp
 */

it would come out like this:

Computes weight based on three factors: items sent items received last timestamp

Instead, write a Markdown list:

/**
 * Computes weight based on three factors:
 *  - items sent
 *  - items received
 *  - last timestamp
 */

7.3 JSDoc tags

Google style allows a subset of JSDoc tags. See 9.1 JSDoc tag reference for the complete list. Most tags must occupy their own line, with the tag at the beginning of the line.

Illegal:

/**
 * The "param" tag must occupy its own line and may not be combined.
 * @param {number} left @param {number} right
 */
function add(left, right) { ... }

Simple tags that do not require any additional data (such as @private@const@final@export) may be combined onto the same line, along with an optional type when appropriate.

/**
 * Place more complex annotations (like "implements" and "template")
 * on their own lines.  Multiple simple tags (like "export" and "final")
 * may be combined in one line.
 * @export @final
 * @implements {Iterable<TYPE>}
 * @template TYPE
 */
class MyClass {
  /**
   * @param {!ObjType} obj Some object.
   * @param {number=} num An optional number.
   */
  constructor(obj, num = 42) {
    /** @private @const {!Array<!ObjType|number>} */
    this.data_ = [obj, num];
  }
}

There is no hard rule for when to combine tags, or in which order, but be consistent.

For general information about annotating types in JavaScript see Annotating JavaScript for the Closure Compiler and Types in the Closure Type System.

7.4 Line wrapping

Line-wrapped block tags are indented four spaces. Wrapped description text may be lined up with the description on previous lines, but this horizontal alignment is discouraged.

/**
 * Illustrates line wrapping for long param/return descriptions.
 * @param {string} foo This is a param with a description too long to fit in
 *     one line.
 * @return {number} This returns something that has a description too long to
 *     fit in one line.
 */
exports.method = function(foo) {
  return 5;
};

Do not indent when wrapping a @fileoverview description.

7.5 Top/file-level comments

A file may have a top-level file overview. A copyright notice , author information, and default visibility level are optional. File overviews are generally recommended whenever a file consists of more than a single class definition. The top level comment is designed to orient readers unfamiliar with the code to what is in this file. If present, it may provide a description of the file's contents and any dependencies or compatibility information. Wrapped lines are not indented.

Example:

/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 * @package
 */

7.6 Class comments

Classes, interfaces and records must be documented with a description and any template parameters, implemented interfaces, visibility, or other appropriate tags. The class description should provide the reader with enough information to know how and when to use the class, as well as any additional considerations necessary to correctly use the class. Textual descriptions may be omitted on the constructor. @constructor and @extends annotations are not used with the class keyword unless the class is being used to declare an @interface or it extends a generic class.

/**
 * A fancier event target that does cool things.
 * @implements {Iterable<string>}
 */
class MyFancyTarget extends EventTarget {
  /**
   * @param {string} arg1 An argument that makes this more interesting.
   * @param {!Array<number>} arg2 List of numbers to be processed.
   */
  constructor(arg1, arg2) {
    // ...
  }
};

/**
 * Records are also helpful.
 * @extends {Iterator<TYPE>}
 * @record
 * @template TYPE
 */
class Listable {
  /** @return {TYPE} The next item in line to be returned. */
  next() {}
}

7.7 Enum and typedef comments

Enums and typedefs must be documented. Public enums and typedefs must have a non-empty description. Individual enum items may be documented with a JSDoc comment on the preceding line.

/**
 * A useful type union, which is reused often.
 * @typedef {!Bandersnatch|!BandersnatchType}
 */
let CoolUnionType;


/**
 * Types of bandersnatches.
 * @enum {string}
 */
const BandersnatchType = {
  /** This kind is really frumious. */
  FRUMIOUS: 'frumious',
  /** The less-frumious kind. */
  MANXOME: 'manxome',
};

Typedefs are useful for defining short record types, or aliases for unions, complex functions, or generic types. Typedefs should be avoided for record types with many fields, since they do not allow documenting individual fields, nor using templates or recursive references. For large record types, prefer @record.

7.8 Method and function comments

Parameter and return types must be documented. The this type should be documented when necessary. Method, parameter, and return descriptions (but not types) may be omitted if they are obvious from the rest of the method’s JSDoc or from its signature. Method descriptions should start with a sentence written in the third person declarative voice. If a method overrides a superclass method, it must include an @override annotation. Overridden methods must include all @param and @return annotations if any types are refined, but should omit them if the types are all the same.

/** This is a class. */
class SomeClass extends SomeBaseClass {
  /**
   * Operates on an instance of MyClass and returns something.
   * @param {!MyClass} obj An object that for some reason needs detailed
   *     explanation that spans multiple lines.
   * @param {!OtherClass} obviousOtherClass
   * @return {boolean} Whether something occurred.
   */
  someMethod(obj, obviousOtherClass) { ... }

  /** @override */
  overriddenMethod(param) { ... }
}

/**
 * Demonstrates how top-level functions follow the same rules.  This one
 * makes an array.
 * @param {TYPE} arg
 * @return {!Array<TYPE>}
 * @template TYPE
 */
function makeArray(arg) { ... }

Anonymous functions do not require JSDoc, though parameter types may be specified inline if the automatic type inference is insufficient.

promise.then(
    (/** !Array<number|string> */ items) => {
      doSomethingWith(items);
      return /** @type {string} */ (items[0]);
    });

7.9 Property comments

Property types must be documented. The description may be omitted for private properties, if name and type provide enough documentation for understanding the code.

Publicly exported constants are commented the same way as properties. Explicit types may be omitted for @const properties initialized from an expression with an obviously known type.

Tip: A @const property’s type can be considered “obviously known” if it is assigned directly from a constructor parameter with a declared type, or directly from a function call with a declared return type. Non-const properties and properties assigned from more complex expressions should have their types declared explicitly.

/** My class. */
class MyClass {
  /** @param {string=} someString */
  constructor(someString = 'default string') {
    /** @private @const */
    this.someString_ = someString;

    /** @private @const {!OtherType} */
    this.someOtherThing_ = functionThatReturnsAThing();

    /**
     * Maximum number of things per pane.
     * @type {number}
     */
    this.someProperty = 4;
  }
}

/**
 * The number of times we'll try before giving up.
 * @const
 */
MyClass.RETRY_COUNT = 33;

7.10 Type annotations

Type annotations are found on @param@return@this, and @type tags, and optionally on @const@export, and any visibility tags. Type annotations attached to JSDoc tags must always be enclosed in braces.

7.10.1 Nullability

The type system defines modifiers ! and ? for non-null and nullable, respectively. Primitive types (undefinedstringnumberbooleansymbol, and function(...): ...) and record literals ({foo: string, bar: number}) are non-null by default. Do not add an explicit ! to these types. Object types (ArrayElementMyClass, etc) are nullable by default, but cannot be immediately distinguished from a name that is @typedef’d to a non-null-by-default type. As such, all types except primitives and record literals must be annotated explicitly with either ? or ! to indicate whether they are nullable or not.

7.10.2 Type Casts

In cases where type checking doesn't accurately infer the type of an expression, it is possible to tighten the type by adding a type annotation comment and enclosing the expression in parentheses. Note that the parentheses are required.

/** @type {number} */ (x)

7.10.3 Template Parameter Types

Always specify template parameters. This way compiler can do a better job and it makes it easier for readers to understand what code does.

Bad:

const /** !Object */ users = {};
const /** !Array */ books = [];
const /** !Promise */ response = ...;

Good:

const /** !Object<string, !User> */ users = {};
const /** !Array<string> */ books = [];
const /** !Promise<!Response> */ response = ...;

const /** !Promise<undefined> */ thisPromiseReturnsNothingButParameterIsStillUseful = ...;
const /** !Object<string, *> */ mapOfEverything = {};

Cases when template parameters should not be used:

  • Object is used for type hierarchy and not as map-like structure.

7.11 Visibility annotations

Visibility annotations (@private@package@protected) may be specified in a @fileoverview block, or on any exported symbol or property. Do not specify visibility for local variables, whether within a function or at the top level of a module. All @private names must end with an underscore.

8 Policies

8.1 Issues unspecified by Google Style: Be Consistent!

For any style question that isn't settled definitively by this specification, prefer to do what the other code in the same file is already doing. If that doesn't resolve the question, consider emulating the other files in the same package.

8.2 Compiler warnings

8.2.1 Use a standard warning set

As far as possible projects should use --warning_level=VERBOSE.

8.2.2 How to handle a warning

Before doing anything, make sure you understand exactly what the warning is telling you. If you're not positive why a warning is appearing, ask for help .

Once you understand the warning, attempt the following solutions in order:

  1. First, fix it or work around it. Make a strong attempt to actually address the warning, or find another way to accomplish the task that avoids the situation entirely.
  2. Otherwise, determine if it's a false alarm. If you are convinced that the warning is invalid and that the code is actually safe and correct, add a comment to convince the reader of this fact and apply the @suppress annotation.
  3. Otherwise, leave a TODO comment. This is a last resort. If you do this, do not suppress the warning. The warning should be visible until it can be taken care of properly.

8.2.3 Suppress a warning at the narrowest reasonable scope

Warnings are suppressed at the narrowest reasonable scope, usually that of a single local variable or very small method. Often a variable or method is extracted for that reason alone.

Example

/** @suppress {uselessCode} Unrecognized 'use asm' declaration */
function fn() {
  'use asm';
  return 0;
}

Even a large number of suppressions in a class is still better than blinding the entire class to this type of warning.

8.3 Deprecation

Mark deprecated methods, classes or interfaces with @deprecated annotations. A deprecation comment must include simple, clear directions for people to fix their call sites.

8.4 Code not in Google Style

You will occasionally encounter files in your codebase that are not in proper Google Style. These may have come from an acquisition, or may have been written before Google Style took a position on some issue, or may be in non-Google Style for any other reason.

8.4.1 Reformatting existing code

When updating the style of existing code, follow these guidelines.

  1. It is not required to change all existing code to meet current style guidelines. Reformatting existing code is a trade-off between code churn and consistency. Style rules evolve over time and these kinds of tweaks to maintain compliance would create unnecessary churn. However, if significant changes are being made to a file it is expected that the file will be in Google Style.
  2. Be careful not to allow opportunistic style fixes to muddle the focus of a CL. If you find yourself making a lot of style changes that aren’t critical to the central focus of a CL, promote those changes to a separate CL.

8.4.2 Newly added code: use Google Style

Brand new files use Google Style, regardless of the style choices of other files in the same package.

When adding new code to a file that is not in Google Style, reformatting the existing code first is recommended, subject to the advice in 8.4.1 Reformatting existing code.

If this reformatting is not done, then new code should be as consistent as possible with existing code in the same file, but must not violate the style guide.

8.5 Local style rules

Teams and projects may adopt additional style rules beyond those in this document, but must accept that cleanup changes may not abide by these additional rules, and must not block such cleanup changes due to violating any additional rules. Beware of excessive rules which serve no purpose. The style guide does not seek to define style in every possible scenario and neither should you.

8.6 Generated code: mostly exempt

Source code generated by the build process is not required to be in Google Style. However, any generated identifiers that will be referenced from hand-written source code must follow the naming requirements. As a special exception, such identifiers are allowed to contain underscores, which may help to avoid conflicts with hand-written identifiers.

9 Appendices

9.1 JSDoc tag reference

JSDoc serves multiple purposes in JavaScript. In addition to being used to generate documentation it is also used to control tooling. The best known are the Closure Compiler type annotations.

9.1.1 Type annotations and other Closure Compiler annotations

Documentation for JSDoc used by the Closure Compiler is described in Annotating JavaScript for the Closure Compiler and Types in the Closure Type System.

9.1.2 Documentation annotations

In addition to the JSDoc described in Annotating JavaScript for the Closure Compiler the following tags are common and well supported by various documentation generations tools (such as JsDossier) for purely documentation purposes.

TagTemplate & ExamplesDescription
@author or @owner@author username@google.com (First Last)

For example:

/**
 * @fileoverview Utilities for handling textareas.
 * @author kuth@google.com (Uthur Pendragon)
 */
 
Document the author of a file or the owner of a test, generally only used in the @fileoverview comment. The @owner tag is used by the unit test dashboard to determine who owns the test results.

Not recommended.

@bug@bug bugnumber

For example:

/** @bug 1234567 */
function testSomething() {
  // …
}

/** * @bug 1234568 * @bug 1234569 */ function testTwoBugs() { // … }

Indicates what bugs the given test function regression tests.

Multiple bugs should each have their own @bug line, to make searching for regression tests as easy as possible.

@code{@code ...}

For example:

/**
 * Moves to the next position in the selection.
 * Throws {@code goog.iter.StopIteration} when it
 * passes the end of the range.
 * @return {!Node} The node at the next position.
 */
goog.dom.RangeIterator.prototype.next = function() {
  // …
};
Indicates that a term in a JSDoc description is code so it may be correctly formatted in generated documentation.
@see@see Link

For example:

/**
 * Adds a single item, recklessly.
 * @see #addSafely
 * @see goog.Collect
 * @see goog.RecklessAdder#add
 */
 
Reference a lookup to another class function or method.
@supported@supported Description

For example:

/**
 * @fileoverview Event Manager
 * Provides an abstracted interface to the
 * browsers' event systems.
 * @supported IE10+, Chrome, Safari
 */
Used in a fileoverview to indicate what browsers are supported by the file.
@desc@desc Message description

For example:

/** @desc Notifying a user that their account has been created. */
exports.MSG_ACCOUNT_CREATED = goog.getMsg(
    'Your account has been successfully created.');
 

You may also see other types of JSDoc annotations in third-party code. These annotations appear in the JSDoc Toolkit Tag Reference but are not considered part of valid Google style.

9.1.3 Framework specific annotations

The following annotations are specific to a particular framework.

FrameworkTagDocumentation
Angular 1@ngInject
Polymer@polymerBehaviorhttps://github.com/google/closure-compiler/wiki/Polymer-Pass

9.1.4 Notes about standard Closure Compiler annotations

The following tags used to be standard but are now deprecated.

TagTemplate & ExamplesDescription
@expose@exposeDeprecated. Do not use. Use @export and/or @nocollapse instead.
@inheritDoc@inheritDocDeprecated. Do not use. Use @override instead.

9.2 Commonly misunderstood style rules

Here is a collection of lesser-known or commonly misunderstood facts about Google Style for JavaScript. (The following are true statements; this is not a list of myths.)

  • Neither a copyright statement nor @author credit is required in a source file. (Neither is explicitly recommended, either.)
  • Aside from the constructor coming first (5.4.1 Constructors), there is no hard and fast rule governing how to order the members of a class (5.4 Classes).
  • Empty blocks can usually be represented concisely as {}, as detailed in (4.1.3 Empty blocks: may be concise).
  • The prime directive of line-wrapping is: prefer to break at a higher syntactic level (4.5.1 Where to break).
  • Non-ASCII characters are allowed in string literals, comments and Javadoc, and in fact are recommended when they make the code easier to read than the equivalent Unicode escape would (2.3.3 Non-ASCII characters).

The following tools exist to support various aspects of Google Style.

9.3.1 Closure Compiler

This program performs type checking and other checks, optimizations and other transformations (such as ECMAScript 6 to ECMAScript 5 code lowering).

9.3.2 clang-format

This program reformats JavaScript source code into Google Style, and also follows a number of non-required but frequently readability-enhancing formatting practices.

clang-format is not required. Authors are allowed to change its output, and reviewers are allowed to ask for such changes; disputes are worked out in the usual way. However, subtrees may choose to opt in to such enforcement locally.

9.3.3 Closure compiler linter

This program checks for a variety of missteps and anti-patterns.

9.3.4 Conformance framework

The JS Conformance Framework is a tool that is part of the Closure Compiler that provides developers a simple means to specify a set of additional checks to be run against their code base above the standard checks. Conformance checks can, for example, forbid access to a certain property, or calls to a certain function, or missing type information (unknowns).

These rules are commonly used to enforce critical restrictions (such as defining globals, which could break the codebase) and security patterns (such as using eval or assigning to innerHTML), or more loosely to improve code quality.

For additional information see the official documentation for the JS Conformance Framework.

9.4 Exceptions for legacy platforms

9.4.1 Overview

This section describes exceptions and additional rules to be followed when modern ECMAScript 6 syntax is not available to the code authors. Exceptions to the recommended style are required when ECMAScript 6 syntax is not possible and are outlined here:

  • Use of var declarations is allowed
  • Use of arguments is allowed
  • Optional parameters without default values are allowed

9.4.2 Use var

9.4.2.1 var declarations are NOT block-scoped

var declarations are scoped to the beginning of the nearest enclosing function, script or module, which can cause unexpected behavior, especially with function closures that reference var declarations inside of loops. The following code gives an example:

for (var i = 0; i < 3; ++i) {
  var iteration = i;
  setTimeout(function() { console.log(iteration); }, i*1000);
}

// logs 2, 2, 2 -- NOT 0, 1, 2
// because `iteration` is function-scoped, not local to the loop.
9.4.2.2 Declare variables as close as possible to first use

Even though var declarations are scoped to the beginning of the enclosing function, var declarations should be as close as possible to their first use, for readability purposes. However, do not put a var declaration inside a block if that variable is referenced outside the block. For example:

function sillyFunction() {
  var count = 0;
  for (var x in y) {
    // "count" could be declared here, but don't do that.
    count++;
  }
  console.log(count + ' items in y');
}
9.4.2.3 Use @const for constants variables

For global declarations where the const keyword would be used, if it were available, annotate the var declaration with @const instead (this is optional for local variables).

9.4.3 Do not use block scoped functions declarations

Do not do this:

if (x) {
  function foo() {}
}

While most JavaScript VMs implemented before ECMAScript 6 support function declarations within blocks it was not standardized. Implementations were inconsistent with each other and with the now-standard ECMAScript 6 behavior for block scoped function declaration. ECMAScript 5 and prior only allow for function declarations in the root statement list of a script or function and explicitly ban them in block scopes in strict mode.

To get consistent behavior, instead use a var initialized with a function expression to define a function within a block:

if (x) {
  var foo = function() {};
}

9.4.4 Dependency management with goog.provide/goog.require

goog.provide is deprecated. All new files should use goog.module, even in projects with existing goog.provide usage. The following rules are for pre-existing goog.provide files, only.

9.4.4.1 Summary
  • Place all goog.provides first, goog.requires second. Separate provides from requires with an empty line.
  • Sort the entries alphabetically (uppercase first).
  • Don't wrap goog.provide and goog.require statements. Exceed 80 columns if necessary.
  • Only provide top-level symbols.

As of Oct 2016, goog.provide/goog.require dependency management is deprecated. All new files, even in projects using goog.provide for older files, should use goog.module.

goog.provide statements should be grouped together and placed first. All goog.require statements should follow. The two lists should be separated with an empty line.

Similar to import statements in other languages, goog.provide and goog.require statements should be written in a single line, even if they exceed the 80 column line length limit.

The lines should be sorted alphabetically, with uppercase letters coming first:

goog.provide('namespace.MyClass');
goog.provide('namespace.helperFoo');

goog.require('an.extremelyLongNamespace.thatSomeoneThought.wouldBeNice.andNowItIsLonger.Than80Columns');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.classes');
goog.require('goog.dominoes');

All members defined on a class should be in the same file. Only top-level classes should be provided in a file that contains multiple members defined on the same class (e.g. enums, inner classes, etc).

Do this:

goog.provide('namespace.MyClass');

Not this:

goog.provide('namespace.MyClass');
goog.provide('namespace.MyClass.CONSTANT');
goog.provide('namespace.MyClass.Enum');
goog.provide('namespace.MyClass.InnerClass');
goog.provide('namespace.MyClass.TypeDef');
goog.provide('namespace.MyClass.staticMethod');

Members on namespaces may also be provided:

goog.provide('foo.bar');
goog.provide('foo.bar.CONSTANT');
goog.provide('foo.bar.method');
9.4.4.2 Aliasing with goog.scope

goog.scope is deprecated. New files should not use goog.scope even in projects with existing goog.scope usage.

goog.scope may be used to shorten references to namespaced symbols in code using goog.provide/goog.require dependency management.

Only one goog.scope invocation may be added per file. Always place it in the global scope.

The opening goog.scope(function() { invocation must be preceded by exactly one blank line and follow any goog.provide statements, goog.require statements, or top-level comments. The invocation must be closed on the last line in the file. Append // goog.scope to the closing statement of the scope. Separate the comment from the semicolon by two spaces.

Similar to C++ namespaces, do not indent under goog.scope declarations. Instead, continue from the 0 column.

Only make aliases for names that will not be re-assigned to another object (e.g., most constructors, enums, and namespaces). Do not do this (see below for how to alias a constructor):

goog.scope(function() {
var Button = goog.ui.Button;

Button = function() { ... };
...

Names must be the same as the last property of the global that they are aliasing.

goog.provide('my.module.SomeType');

goog.require('goog.dom');
goog.require('goog.ui.Button');

goog.scope(function() {
var Button = goog.ui.Button;
var dom = goog.dom;

// Alias new types after the constructor declaration.
my.module.SomeType = function() { ... };
var SomeType = my.module.SomeType;

// Declare methods on the prototype as usual:
SomeType.prototype.findButton = function() {
  // Button as aliased above.
  this.button = new Button(dom.getElement('my-button'));
};
...
});  // goog.scope


원글 : https://programmer-seva.tistory.com/37?category=615259

1
2
3
4
5
6
7
8
function outerFunc(){
    var x = 10;
    var innerFunc = function() { console.log(x); }
    return innerFunc;
}
 
var inner = outerFunc();
inner();
cs


위 예제를 그림으로 표현하면 아래와 같다.

 

예제와 그림을 보면 알 수 있듯이 outerFunc 실행 컨텍스트는 사라졌지만, outerFunc 변수 객체는 여전히 남아있고, innerFunc의 스코프 체인으로 참조되고 있다.

이것이 바로 자바스크립트에서 구현한 "클로저"라는 개념이다.


자바스크립트 함수는 일급 객체로 취급된다.

이는 함수를 다른 함수의 인자로 넘길 수도 있고, return으로 함수를 통째로 반환받을 수도 있다.

앞의 예제에서 중요하게 볼 점은 최종 반환되는 함수가 외부 함수의 지역변수에 접근하고 있다는 것이 중요하다.


이 지역변수에 접근하려면, 함수가 종료되어 외부 함수의 컨텍스트가 반환되더라도 변수 객체는 반환되는 내부 함수의 스코프 체인에 그대로 남아있어먄 접근할 수 있다. 이것이 바로 클로저이다.


쉽게 풀어 말하면, "이미 생명 주기가 끝난 외부 함수의 변수를 참조하는 함수를 클로저라고 한다"

따라서 위의 예제에서는 outerFunc에서 선언된 x를 참조하는 innerFunc가 클로저가 된다.

클로저로 참조되는 외부 변수, 앞 예제에서는 outerFunc의 x와 같은 변수를 "자유 변수(Free variable)"라고 한다.

클로저는 "자유 변수에 엮여있는 함수"로 많이들 표현한다.


1
2
3
4
5
6
7
8
9
10
11
function outerFunc(arg1, arg2){
    var local = 8;
    function innerFunc(innerArg){
        console.log((arg1 + arg2)/(innerArg + local));
    }
    
    return innerFunc;
}
 
var exam1 = outerFunc(24);
exam1(2);
cs

위 예제에서는 outerFunc() 함수를 호출하고 반환되는 함수 객체인 innerFunc()가 exam1으로 참조된다.

이것은 exam1(n)의 형태로 실행될 수 있다.


여기서 outerFunc()가 실행되면서 생성되는 변수 객체가 스코프 체인에 들어가게 되고, 이 스코프 체인은 innerFunc의 스코프 체인으로 참조된다.


즉, outerFunc() 함수가 종료되었지만, 여전히 내부 함수(innerFunc())의 [[scope]]으로 참조되므로 가비지 컬렉션의 대상이 되지 않고 여전히 접근이 가능하게 살아있다.


innerFunc()에서 참조하고자 하는 변수 local에 접근이 가능하도록 클로저가 만들어 진다.

outerFunc 변수 객체의 프로퍼티 값은 여전히 읽기 및 쓰기까지 가능하다.


위 코드 동작을 그림으로 나타내면 아래와 같다.

 


※ 클로저에서 접근하는 변수는 대부분이 스코프 체인 첫 번째 객체가 아닌 그 이후 객체에 존재한다.

   이는 성능적인 면과 자원적인 면에서 문제를 유발시킬 수 있는 여지가 있다.

   이러한 성능 이슈를 잘 해결하여 클로저를 사용해야 한다. 

   너무 많은 식별자를 인식하지 않도록 설계해서 사용하도록 한다.

Posted by 프로그래머세바 박현진

자바스크립트도 다른 언어와 마찬가지로 스코프, 즉 유효 범위가 있다.

자바스크립트에서는 for() {}, if {}와 같은 구문은 유효 범위가 없다.

오직 함수만이 유효 범위의 한 단위가 된다.


유효 범위를 나타내는 스코프가 [[Scope]] 프로퍼티로 각 함수 객체 내에서 연결리스트 형식으로 관리되는데 이를 "스코프 체인" 이라고 한다.


각의 함수는 [[scope]] 프로퍼티로 자신이 생성된 실행 컨텍스트의 스코프 체인을 참조한다.

함수가 실행되는 순간 실행 컨텍스트가 만들어지고, 이 실행 컨텍스트는 실행된 함수의 [[scope]] 프로퍼티를 기반으로 새로운 스코프 체인을 만든다. 함수의 실행이 완료되면 실행 컨텍스트는 사라진다.

함수가 생성될때 스코프 생성 -> 함수가 실행될때 컨텍스트 생성(이때 생성된 스코프를 참조)



1. 전역 실행 컨텍스트의 스코프 체인

1
2
3
4
var var1 = 1;
var var2 = 2;
console.log(var1);  // 1
console.log(var2);  // 2
cs

위 예제에는 현재 전역 실행 컨텍스트 단 하나만 실행되고 있어 참조할 상위 컨텍스트가 없다.

자신이 최상위에 위치하는 변수 객체인 것이다.

따라서 이 변수 객체의 스코프 체인은 자기 자신만을 가진다.

다시 말해서, 변수 객체의 [[scope]]는 변수 객체 자신을 가리킨다.

이 변수 객체가 곧 전역 객체가 되는 것이다.




2. 함수를 호출한 경우 생성되는 실행 컨텍스트의 스코프 체인

1
2
3
4
5
6
7
8
9
10
11
var var1 = 1;
var var2 = 2;
function func() {
    var var1 = 10;
    var var2 = 20;
    console.log(var1); // 10
    console.log(var2); // 20
}
func();
console.log(var1);  // 1
console.log(var2);  // 2
cs

함수 객체가 생성될 때, 그 함수 객체의 [[scope]]는 

현재 실행되는 컨텍스트의 변수 객체에 있는 [[scope]]를 그대로 가진다.

따라서, func 함수 객체의 [[scope]]는 전역 변수 객체가 된다.


func() 함수를 실행하면 새로운 컨텍스트가 만들어진다.

func() 함수 컨텍스트의 스코프 체인은 실행된 함수의 [[scope]] 프로퍼티를 그대로 복사한 후,

현재 생성된 변수 객체를 복사한 스코프 체인의 맨 앞에 추가한다.


위 과정을 정리해보자.

1) 각 함수 객체는 [[scope]] 프로퍼티로 현재 컨텍스트의 스코프 체인을 참조한다.

2) 한 함수가 실행되면 새로운 실행 컨텍스트가 만들어지는데, 이 새로운 실행 컨텍스트는 자신이 사용할 스코프 체인을 다음과 같은 방법으로 만든다.

 - 자신을 생성한 함수 객체의 [[scope]] 프로퍼티를 복사하고, 

 - 새롭게 생성된 변수 객체를 해당 체인의 제일 앞에 추가한다.

3) 요약 하면, 스코프 체인 = 현재 실행 컨텍스트의 변수 객체 + 상위 컨텍스트의 스코프 체인



다음 두 예제를 통해 스코프 체인에 대해서 확실히 알아보자!

1
2
3
4
5
6
7
8
9
10
11
12
13
var value = "value1";
 
function printFunc(func) {
    var value = "value2";
    
    function printValue() {
        return value;
    }
    
    console.log(printValue());
}
 
printFunc();
cs

앞서 설명한 스코프 체인에 대해 제대로 이해했다면, 결과 값이 "value2"가 된다는 것을 바로 알 수 있다.


그림으로 표현하면 아래와 같다.


다음 예제의 결과는 조금 다를 것이다.

1
2
3
4
5
6
7
8
9
10
11
var value = "value1";
 
function printValue() {
    return value;
}
function printFunc(func) {
    var value = "value2";
    console.log(func());
}
 
printFunc(printValue);
cs

위 예제는 각 함수 객체가 처음 생성될 당시 실행 컨텍스트가 무엇인지를 생각해야 한다.

각 함수 객체가 처음 생성될 때 [[scope]]는 전역 객체의 [[scope]]를 참조한다.

따라서, 각 함수가 실행될 때 생성되는 실행 컨텍스트의 스코프 체인은 전역 객체와 그 앞에 새롭게

만들어진 변수 객체가 추가 된다. 결과 값으로는 "value1" 이 나올 것이다!


그림으로 표현하면 다음과 같다.



지금까지 실행 컨텍스트가 만들어지면서 스코프 체인이 어떻게 형성되는지 살펴보았다.

이렇게 만들어진 스코프 체인으로 식별자 인식(identifier resolution)이 이루어진다.

식별자와 대응되는 이름을 가진 프로퍼티가 존재하는지 확인 한다.


함수를 호출할 때 스코프 체인의 가장 앞에 있는 객체가 변수 객체이므로, 이 객체에 있는 공식 인자, 내부 함수, 지역 변수에 대응되는지 먼저 확인한다.

대응 되는 이름의 프로퍼티를 찾을 때까지 계속해서 다음 객체로 이동하며 찾는다.



스코프 체인이 생성되어도 사용자가 임의로 수정이 가능하다.

with 구문을 활용해서 표현식을 실행할 때, 표현식이 객체이면 객체는 현재 실행 컨텍스트의 스코프 체인(활성화 객체 바로 앞)에 추가된다.

with 구문은 다른 구문을 실행하고 실행 컨텍스트의 스코프 체인을 전에 있던 곳에 저장한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var y = { x:5 };
 
function withExamFunc() {
    var x = 10;
    var z;
 
    with(y) {
        z = function() {
            console.log(x);    
        }
    }
    z();
}
withExamFunc();
cs


함수 선언은 with 구문의 영향을 받지 않고 함수 객체가 생성되지만, 함수 표현식은 안에서 with 구문과 함께 실행될 수 있다.

위 코드에서는 with 구문의 실행으로 전역 변수 y에 의해 참조되는 객체를 함수 표현식이 실행되는 동안 스코프 체인의 맨 앞에 추가한다.


with 구문은 성능 이슈로 인해 자제를 해야한다~



1. 실행 컨텍스트의 개념

기존 여러 언어들에는 콜 스택(call stack)이란 것이 존재한다.

콜 스택이란 함수를 호출할 때 해당 함수의 호출 정보가 차곡차곡 쌓여있는 스택을 의미한다.


ECMAScript에서는,

실행 컨텍스트를 "실행 가능한 코드를 형상화하고 구분하는 추상적인 개념"으로 기술한다.

이를 다시 정의하면 "실행 가능한 자바스크립트 코드 블록이 실행되는 환경"이라고 할 수 있다.

이 컨텍스트 안에 실행에 필요한 여러 가지 정보를 담고 있다.


ECMAScript에서는,

실행 컨텍스트가 형성되는 경우를 세 가지로 규정하는데

 - 전역 코드

 - eval() 함수로 실행되는 코드

 - 함수 안의 코드를 실행 할 경우 

 

대부분 프로그래머는 함수로 실행 컨텍스트를 만든다.

그리고 이 코드 블록 안에 변수 및 객체, 실행 가능한 코드가 들어있다.

이 코드가 실행되면 실행 컨텍스트가 생성되고, 실행 컨텍스트는 스택 안에 하나씩 차곡차곡 쌓이고,

제일 위(top)에 위치하는 실행 컨텍스트가 현재 실행되고 있는 컨텍스트이다.


ECMAScript에서는, 

실행 컨텍스트의 생성은 "현재 실행되는 컨텍스트에서 이 컨텍스트와 관련 없는 실행 코드가 실행되면,

새로운 컨텍스트가 생성되어 스택에 들어가고 제어권이 그 컨텍스트로 이동한다" 로 설명한다.

1
2
3
4
5
6
7
8
9
10
11
12
console.log("This is global context");
 
function ExContext1() {
    console.log("This is ExContext1");
};
 
function ExContext2() {
    ExContext1();
    console.log("This is ExContext2");
};
 
ExContext2();
cs


 

위 예제에서 함수 호출로 본 컨텍스트 변화 과정을 그림으로 알아보겠다.




2. 실행 컨텍스트 생성 과정

1) 활성 객체 생성

실행 컨텍스트가 생성되면 자바스크립트 엔진은 해당 컨텍스트에서 실행에 필요한 여러가지 정보를 담은 객체를 생성한다. 

이를 활성 객체라고 한다.

이 객체에 앞으로 매개변수나 사용자가 정의한 변수 및 객체를 저장하고, 새로 만들어진 컨텍스트로 접근 가능하게 되어 있다.

이는 엔진 내부에서 접근할 수 있다는 것이지 사용자가 접근할 수 있다는 것은 아니다.


2) arguments 객체 생성

앞서 만들어진 활성 객체는 arguments 프로퍼티로 이 arguments 객체를 참조한다.


3) 스코프 정보 생성

현재 컨텍스트의 유효 범위를 나타내는 스코프 정보를 생성한다.

이 스코프 정보는 현재 실행 중인 실행 컨텍스트 안에서 연결 리스트와 유사한 형식으로 만들어진다.

현재 컨텍스트에서 특정 변수에 접근해야 할 경우, 이 리스트를 활용한다.

이 리스트로 현재 컨텍스트의 변수뿐 아니라, 상위 실행 컨텍스트의 변수도 접근이 가능하다.

이 리스트에서 찾지 못한 변수는 결국 정의되지 않은 변수에 접근하는 것으로 판단하여 에러를 검출한다.

이 리스트를 스코프 체인이라고 하는데, [[Scope]] 프로퍼티로 참조한다.

현재 생성된 활성 객체가 스코프 체인의 제일 앞에 추가되며 함수의 인자나 지역 변수 등에 접근 가능하다.


4) 변수 생성

현재 실행 컨텍스트 내부에서 사용되는 지역 변수의 생성이 이루어진다.

실제적으로 앞서 생성된 활성 객체가 변수 객체로 사용된다.

활성 객체나 변수 객체는 같은말이다.

이 과정에서 함수 안에 정의된 지역 변수나 내부 함수가 생성된다.

주의할 점은 변수나 내부 함수들은 단지 메모리에 생성되는 것이지 초기화는 각 변수나 함수에 해당하는 표현식이 실행되기 전까지 이루어지지 않는 다는 점이다.

함수 호이스팅이 궁금증이 풀리는 부분이다.


5) this 바인딩

마지막 단계에서는 this 키워드를 사용하는 값이 할당된다.

this가 참조하는 객체가 없으면 전역 객체를 참조한다.


6) 코드 실행

위 과정으로 하나의 실행 컨텍스트가 생성되고, 변수 객체가 만들어 진 후에, 코드에 있는 여러 가지 표현식 실행이 이루어진다.

이렇게 실행되면서 변수의 초기화 및 연산, 또 다른 함수 실행 등이 이루어진다.

여기서 전역 실행 컨텍스트는 arguments 객체가 없으며, 전역 객체 하나만을 포함하는 스코프 체인이 있다.

ECMAScript에서 언급된 바에 의하면 실행 컨텍스트가 형성되는 세 가지 중 하나로서 전역 코드가 있는데,

이 전역 코드가 실행될 때 생성되는 컨텍스트가 전역 실행 컨텍스트다.

전역 실행 컨텍스트에서는 변수 객체가 곧 전역 객체이다.

따라서 전역적으로 선언된 함수와 변수가 전역 객체의 프로퍼티가 된다.

전역 실행 컨텍스트 역시, this를 전역 객체의 참조로 사용한다.


Posted by 프로그래머세바 박현진

예1

  • 아래의 코드에서는 'result_async : Promise<pending> 을 반환한다. 그 이유는, testFunc()를 기다려 주지 않기 때문이다. 이러한 실수가 빈번하고 또 자주 까먹는데, 동일한 스코프에서 await하지 않으면 기다려주지 않는다.
    async function testFunc() {
      const test = await syncSetTimeout();
      return test;
    }
    function syncSetTimeout(){
      return new Promise(function(resolve){
          setTimeout(function(){
                  console.log(1);
                  resolve(2);
              }
              , 10000)
      });
    }
    const result_async = testFunc();
    console.log('result_async : ', result_async);
  • 아래의 코드에서는 예상대로 10초후 'result_async : haha을 반환 한다. testFunc() 앞에 await가 있기 때문에 기다린다.
    async function testFunc() {
      const test = await syncSetTimeout();
      return test;
    }
    function syncSetTimeout(){
      return new Promise(function(resolve){
          setTimeout(function(){
                  console.log('1');
                  resolve('2');
              }
              , 10000)
      });
    }
    (async function(){
    const result_sync = await testFunc();
    console.log('result_sync: ', result_sync);
    })();

예2

 class RestApiChannel {
     commonErrorHandle(param: any): void | Promise<void> {
         return;
     }
}

class LineChannel extends RestApiChannel {
    async commonErrorHandle(param: any) {
        await Promise.resolve();
        return Promise.resolve();
    }
}

const lineChannel = new LineChannel();
const returns = lineChannel.commonErrorHandle(1);
console.log(returns);

if (returns instanceof Promise) {
    console.log('returns instanceof Promise is True');
}

console.log(typeof returns);


JS


함수(Function)


1. 함수 선언(Function declaration 혹은 Function statement)

함수 선언(Function declaration)을 MDS에서 밑에와 같이 정의 하였습니다.


문법

1
2
3
function name([param,[, param,[..., param]]]) {
   [statements]
}

name

The function name.


param

The name of an argument to be passed to the function. Maximum number of arguments varies in different engines.


statements

3

     The statements which comprise the body of the function.

0


함수 선언 호이스팅(Function declaration hoisting)

함수 선언은 호이스팅이 됩니다. ([JavaScript] 유효범위(Scope)와 호이스팅(Hoisting) 참고)

1
2
3
4
5
hoisted(); // logs "foo"
 
function hoisted() {
  console.log("foo");
}

함수 선언 호이스팅함수 선언 호이스팅


알게 모르게 저희는 함수 선언 호이스팅을 사용하고 있었습니다. 함수는 호출 먼저 하고, 함수 정의는 나중에 정의하는..


하지만, 다음으로 이야기할 함수 표현은 호이스팅이 되지 않습니다.

1
2
3
4
5
notHoisted(); // TypeError: notHoisted is not a function
 
var notHoisted = function() {
   console.log("bar");
};

함수 표현은 호이스팅이 되지 않는다함수 표현은 호이스팅이 되지 않는다


호이스팅된 코드를 보면 이해하기 쉽습니다.

1
2
3
4
5
6
7
var notHoisted;
 
notHoisted(); // TypeError: notHoisted is not a function
 
notHoisted = function() {
   console.log("bar");
};

정의 되어 있지 않는 변수를 사용하려 하여 에러가 출력되는 것은 당연합니다.



2. 함수 표현(Function expression)

함수 표현(Function expression)을 MDS에서 밑에와 같이 정의 하였습니다.


문법

1
2
3
function [name]([param1[, param2[, ..., paramN]]]) {
   statements
}

name

The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.


paramN

The name of an argument to be passed to the function.


statements

The statements which comprise the body of the function.


익명 함수 표현 (Anonymous function expression)

익명 함수 표현의 예를 들어보겠습니다.

1
2
3
4
var x = function(y) {
   return y * y;
};
console.log(x(2)); // 4

익명 함수 표현익명 함수 표현


기명 함수 표현 (Named function expression)

기명 함수 표현의 예를 들어보겠습니다.

1
2
3
4
var x = function square(y) {
   return y * y;
};
console.log(x(2)); // 4

기명 함수 표현기명 함수 표현


여기서 저는 궁금한 점이 하나 생겼습니다. 기명 함수 표현으로 함수의 이름이 있다면 함수 이름으로 함수 실행이 가능 할까..?

1
2
3
4
var x = function square(y) {
   return y * y;
};
square(2);

기명 함수 표현함수이름으로 함수 실행이 되지 않는다


안됩니다.... 그렇다면, 왜 기명 함수 표현을 사용하는 걸까요?


One of the benefit of creating a named function expression is that in case we encounted an error,

the stack trace will contain the name of the function, making it easier to find the origin of the error.


MDS에서는, 장점 하나는 에러가 발생 했을 때, stack trace가 함수의 이름을 포함하여 출력하기 때문에 에러를 찾기 쉽운것이 기명 함수 표현의 장점이라고 이야기 함니다.


MDS에서 함수 정의에 몇가지 방법을 더 이야기 하는데, 이번 포스팅에서 2가지만 이야기하겠습니다.

(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions 참고)



즉시 실행 함수 (Immediately-invoked function expression)



즉시 실행 함수의 기본 형태는 아래와 같습니다.

1
2
3
(function () {
    // statements
})()

함수 표현(Function expression)은 함수를 정의하고, 변수에 함수를 저장하고 실행하는 과정을 거칩니다. 하지만 즉시 실행 함수는 함수를 정의하고 바로 실행하여 이러한 과정을 거치지 않는 특징이 있습니다. 함수를 정의하자마자 바로 호출하는 것을 즉시 실행 함수라고 이해하면 편할 것 같습니다.


Immediately-invoked function expression 영어를 해석하면 즉시-호출 함수 표현 입니다. 즉시 실행 함수(IIFE)는 함수 표현(function expression)과 같이 익명 함수 표현, 기명 함수 표현으로 할 수 있습니다.



1. 즉시 실행 함수 사용법

기명 즉시 실행 함수

1
2
3
4
5
6
7
(function square(x) {
    console.log(x*x);
})(2);
 
(function square(x) {
    console.log(x*x);
}(2));

위의 두가지 예는 괄호의 위치가 조금 다를 뿐 같은 기능의 즉시 실행 함수 입니다.


익명 즉시 실행 함수

1
2
3
4
5
6
7
(function (x) {
    console.log(x*x);
})(2);
 
(function (x) {
    console.log(x*x);
}(2));


변수에 즉시 실행 함수 저장

즉시 실행 함수도 함수이기 때문에, 변수에 즉시 실행 함수 저장이 가능합니다. 예를 들어 보겠습니다.

1
2
3
4
(mySquare = function (x) {
    console.log(x*x);
})(2);
mySquare(3);

변수에 즉시 실행 함수 저장변수에 즉시 실행 함수 저장


함수를 mySquare에 저장하고 이 함수를 바로 실행하게 됩니다. mySquare는 즉시 실행 함수를 저장하고 있기 때문에 재호출이 가능하게 됩니다.


마찬가지로 즉시 실행 함수도 함수이기 때문에, 변수에 즉시 실행 함수의 리턴 값 저장도 가능합니다.

1
2
3
4
var mySquare = (function (x) {
    return x*x;
})(2);
console.log(mySquare)

변수에 즉시실행함수 리턴값 저장변수에 즉시실행함수 리턴값 저장


위의 두가지는 형태가 유사하지만 엄연히 다른 기능입니다. 괄호의 위치에 주의가 필요할 것 같습니다.



2. 즉시 실행 함수를 사용하는 이유

초기화

즉시 실행 함수는 한 번의 실행만 필요로 하는 초기화 코드 부분에 많이 사용됩니다.

그렇다면 왜 초기화 코드 부분에 많이 사용 할까요? 변수를 전역(global scope)으로 선언하는 것을 피하기 위해서 입니다. 전역에 변수를 추가하지 않아도 되기 때문에 코드 충돌 없이 구현 할 수 있어, 플러그인이나 라이브러리 등을 만들 때 많이 사용됩니다.


예를 하나 들어보겠습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
var initText;
 
(function (number) {
    var textList = ["is Odd Text", "is Even Text"];
    if (number % 2 == 0) {
        initText = textList[1];
    } else {
        initText = textList[0];
    }
})(5);
 
console.log(initText);
console.log(textList);

즉시실행함수 이용한 초기화즉시실행함수 이용한 초기화



전역에 textList가 저장되지 않고, initText만 초기화 된 것을 확인 할 수 있습니다. 또한 textList는 지역 변수로, 전역 변수와 충돌없이 초기화 할 수 있게 됩니다.


라이브러리 전역 변수의 충돌

jQuery나 Prototype 라이브러리는 동일한 $라는 전역 변수를 사용합니다. 만약, 이 두개의 라이브러리를 같이 사용한다면 $ 변수 충돌이 생기게 됩니다.

즉시 실행 함수를 사용하여 $ 전역 변수의 충돌을 피할 수 있습니다.

1
2
3
(function ($) {
    // $ 는 jQuery object
})(jQuery);

즉시 실행 함수 안에서 $는 전역변수가 아닌 jQuery object의 지역 변수가 되어, Prototype 라이브러리의 $와 충돌 없이 사용할 수 있습니다.



출처: https://beomy.tistory.com/9 [beomy]

스코프와 클로저는 자바스크립트에서 굉장히 중요합니다. 하지만 제가 처음 자바스크립트를 시작할 때 이 두 개념이 굉장히 헷갈렸어요. 대체 스코프와 클로저가 무엇인지, 여러분이 이해할 수 있도록 도와드리고자 이 글을 준비했습니다.

그럼, 스코프부터 시작해 보도록 하죠.

스코프(Scope)

자바스크립트에서 스코프란 어떤 변수들에 접근할 수 있는지를 정의합니다. 스코프엔 두 가지 종류가 있는데요, 전역 스코프(global scope)와 지역 스코프(local scope)가 있죠.

전역 스코프(Global Scope)

변수가 함수 바깥이나 중괄호 ({}) 바깥에 선언되었다면, 전역 스코프에 정의된다고 합니다.

이 설명은 웹 브라우저의 자바스크립트에만 유효합니다. Node.js에서는 전역 스코프를 다르게 정의하지만, 이번 글에서는 다루지 않겠습니다.
const globalVariable = 'some value'

전역 변수를 선언하면, 여러분의 코드 모든 곳에서 해당 변수를 사용할 수 있습니다. 심지어 함수에서도 말이죠.

const hello = 'Hello CSS-Tricks Reader!'
function sayHello () {
console.log(hello)
}
console.log(hello) // 'Hello CSS-Tricks Reader!'
sayHello() // 'Hello CSS-Tricks Reader!'

비록 전역 스코프에 변수를 선언할 수는 있어도, 그러지 않는 것이 좋습니다. 왜냐하면, 두 개 이상의 변수의 이름이 충돌하는 경우가 생길 수도 있기 때문이죠. 만약 변수를 const나 let을 사용하여 선언했다면, 이름에 충돌이 발생할 때마다 에러가 발생합니다. 이렇게 되면 안 되죠.

// Don’t do this!
let thing = 'something'
let thing = 'something else' // Error, thing has already been declared

만약 var를 이용하여 변수를 선언했다면, 두 번째 변수가 첫 번째 변수를 덮어쓰게 됩니다. 이러면 디버깅이 어려워지기 때문에 이런 식으로 사용하면 안 됩니다.

// Don’t do this!
var thing = 'something'
var thing = 'something else' // perhaps somewhere totally different in your code
console.log(thing) // ‘something else’

그래서 여러분은 언제나 전역 변수가 아닌, 지역 변수로써 변수를 선언해야 합니다.

지역 스코프 (Local Scope)

여러분 코드의 특정 부분에서만 사용할 수 있는 변수는 지역 스코프에 있다고 할 수 있습니다. 이런 변수들은 지역 변수라고 불리죠.

자바스크립트에서는 두 가지의 지역 변수가 존재합니다. 바로 함수 스코프(function scope)와 블록 스코프(block scope)죠.

먼저 함수 스코프부터 알아보도록 합시다.

함수 스코프(Function Scope)

여러분이 함수 내부에서 변수를 선언하면, 그 변수는 선언한 변수 내부에서만 접근할 수 있습니다. 함수 바깥에서는 해당 변수에 접근할 수 없죠.

->함수스코브 :var let const어떤 걸로 선언하든 선언한 함수내부에서 선언한 것은 함수내부에서만 사용가능

아래의 예제를 살펴보면 변수 hello는 sayHello의 스코프 내에 존재한다는 것을 알 수 있습니다.

function sayHello () {
const hello = 'Hello CSS-Tricks Reader!'
console.log(hello)
}
sayHello() // 'Hello CSS-Tricks Reader!'
console.log(hello) // Error, hello is not defined

블록 스코프(Block Scope)

여러분이 중괄호({}) 내부에서 const 또는 let으로 변수를 선언하면, 그 변수들은 중괄호 블록 내부에서만 접근할 수 있습니다.

->블록스코프:블록 내부에서 let const로 선언한 것은 블록 내부에서만 사용가능. 단 var은 블록 내부에서 선언해도 밖에서 사용가능

다음 예제에서 볼 수 있듯이 변수 hello는 중괄호 내부의 스코프에 존재합니다.

{
const hello = 'Hello CSS-Tricks Reader!'
console.log(hello) // 'Hello CSS-Tricks Reader!'
}
console.log(hello) // Error, hello is not defined

함수를 선언할 때는 중괄호를 사용해야 하므로 블록 스코프는 함수 스코프의 서브셋(subset) 입니다(여러분이 화살표 함수(arrow function)를 사용해서 암시적(implicit) 반환을 하는게 아니라면 말이죠).

함수 호이스팅(Function hoisting)과 스코프

함수가 함수 선언식(function declaration)으로 선언되면, 현재 스코프의 최상단으로 호이스팅(hoist) 됩니다.

다음 예제에서 두 가지 경우는 같은 결과를 보입니다.

// This is the same as the one below
sayHello()
function sayHello () {
console.log('Hello CSS-Tricks Reader!')
}
// This is the same as the code above
function sayHello () {
console.log('Hello CSS-Tricks Reader!')
}
sayHello()

반면 함수가 함수 표현식(function expression)으로 선언되면, 함수는 현재 스코프의 최상단으로 호이스팅되지 않습니다.

sayHello() // Error, sayHello is not defined
const sayHello = function () {
console.log(aFunction)
}

이렇게 두 방식의 행동이 다르기 때문에, 함수 호이스팅은 혼란스러울 수 있으므로 사용하면 안 됩니다. 언제나, 함수를 호출하기 전에 선언해놓아야 합니다.

+ Recent posts