Strings

  • 6.1 Use single quotes '' for strings. eslint: quotes

    1. // bad
    2. const name = "Capt. Janeway";
    3. // bad - template literals should contain interpolation or newlines
    4. const name = `Capt. Janeway`;
    5. // good
    6. const name = 'Capt. Janeway';

  • 6.2 Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation.

    Why? Broken strings are painful to work with and make code less searchable.

    1. // bad
    2. const errorMessage = 'This is a super long error that was thrown because \
    3. of Batman. When you stop to think about how Batman had anything to do \
    4. with this, you would get nowhere \
    5. fast.';
    6. // bad
    7. const errorMessage = 'This is a super long error that was thrown because ' +
    8. 'of Batman. When you stop to think about how Batman had anything to do ' +
    9. 'with this, you would get nowhere fast.';
    10. // good
    11. const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';

  • 6.3 When programmatically building up strings, use template strings instead of concatenation. eslint: prefer-template template-curly-spacing

    Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.

    1. // bad
    2. function sayHi(name) {
    3. return 'How are you, ' + name + '?';
    4. }
    5. // bad
    6. function sayHi(name) {
    7. return ['How are you, ', name, '?'].join();
    8. }
    9. // bad
    10. function sayHi(name) {
    11. return `How are you, ${ name }?`;
    12. }
    13. // good
    14. function sayHi(name) {
    15. return `How are you, ${name}?`;
    16. }

  • 6.4 Never use eval() on a string, it opens too many vulnerabilities. eslint: no-eval

  • 6.5 Do not unnecessarily escape characters in strings. eslint: no-useless-escape

    Why? Backslashes harm readability, thus they should only be present when necessary.

    1. // bad
    2. const foo = '\'this\' \i\s \"quoted\"';
    3. // good
    4. const foo = '\'this\' is "quoted"';
    5. const foo = `my name is '${name}'`;