Upgrade to Pro — share decks privately, control downloads, hide ads and more …

JavaScript coding tips

JavaScript coding tips

Conventional and unconventional advice for writing better code.

Axel Rauschmayer

May 16, 2014
Tweet

More Decks by Axel Rauschmayer

Other Decks in Programming

Transcript

  1. JavaScript coding tips
    Axel Rauschmayer
    rauschma.de
    !
    Sud Web 2014

    View Slide

  2. Coding styles
    on GitHub
    Source: sideeffect.kr/popularconvention/#javascript

    View Slide

  3. Comma: first or last?
    var foo = 1
    , bar = 2
    , baz = 3;
    !
    var obj = {
    foo: 1
    , bar: 2
    , baz: 3
    };

    var foo = 1,
    bar = 2,
    baz = 3;
    !
    var obj = {
    foo: 1,
    bar: 2,
    baz: 3
    };
    7% comma first
 93% comma last
    3

    View Slide

  4. Indentation: spaces vs. tabs
    function foo() {
    ␣␣return 'bar';
    }

    function foo() {
    ⇥ return 'bar';
    }
    81% spaces
 19% tabs
    4

    View Slide

  5. Space after function name?
    function foo () {
    return 'bar';
    }

    function foo() {
    return 'bar';
    }
    33% space after
    function name

    67% no space after
    function name
    5

    View Slide

  6. Spaces inside parens?
    function fn( x, y ) {
    ...
    }
    !
    if ( true ) {
    ...
    }

    function fn(x, y) {
    ...
    }
    !
    if (true) {
    ...
    }
    6% spaces inside
    parens

    94% no spaces inside
    parens
    6

    View Slide

  7. Object literals
    {
    foo:1,
    bar:2,
    baz:3
    }

    {
    foo: 1,
    bar: 2,
    baz: 3
    }

    {
    foo : 1,
    bar : 2,
    baz : 3
    }
    22% no space
    after colon

    64% space
    after colon

    14% space
    before & after
    7

    View Slide

  8. Conditional statements
    if (true) {
    ...
    }
    while (true) {
    ...
    }
    switch (v) {
    ...
    }

    if(true) {
    ...
    }
    while(true) {
    ...
    }
    switch(v) {
    ...
    }
    79% space after
    keyword

    21% no space after
    keyword
    8

    View Slide

  9. String literals
    var foo = 'bar';
    !
    var obj = {
    'foo': 'bar'
    };

    var foo = "bar";
    !
    var obj = {
    "foo": "bar"
    };
    57% single quotes
 43% double quotes
    9

    View Slide

  10. General tips

    View Slide

  11. Be consistent
    New project:"
    • Come up with a style
    • Document it
    • Automatically check it (tools: JSLint, JSHint, ESLint)
    • Follow it consistently
    Existing project:"
    • Follow their style (even if you don’t like it)
    11

    View Slide

  12. Code should be easy to
    understand
    Code is written once, read many times. Treat it
    accordingly.
    Programs must be written for people to read, and
    only incidentally for machines to execute.
    —Abelson, Sussman
    12

    View Slide

  13. Code should be easy to
    understand
    • Shorter isn’t always better
    • Familiar + longer > unfamiliar + shorter
    • Humans read tokens, not characters: redBalloon > rdBlln
    • Write code like a textbook
    • A guide to your mental universe
    • Complemented by documentation
    • Don’t be clever
    • Avoid optimizing for speed or code size (esp. early on)
    13

    View Slide

  14. Commonly accepted
    best practices

    View Slide

  15. Best practices
    • Use strict mode
    • Always use strict equality (===). No exceptions!
    • Avoid global variables
    • Always write semicolons
    • Single quotes for strings (common, but not a must)
    15

    View Slide

  16. Use: 1TBS (One True Brace
    Style)
    function foo(x, y, z) {
    if (x) {
    a();
    } else {
    b();
    c();
    }
    }
    16

    View Slide

  17. Don’t use: Allman
    brace style
    function foo(x, y, z)
    {
    if (x)
    {
    a();
    }
    else
    {
    b();
    c();
    }
    }
    17

    View Slide

  18. Literals are better than
    constructors
    var obj = {}; // yes
    var obj = new Object(); // no
    !
    var arr = []; // yes
    var arr = new Array(); // no
    !
    var regex = /abc/; // yes
    var regex = new RegExp('abc'); // avoid
    18

    View Slide

  19. Acceptable cleverness
    // Optional parameter x
    function f(x) {
    x = x || 0;
    ...
    }
    19

    View Slide

  20. Naming entities
    • Not capitalized:
    • Functions, variables: myFunction
    • Methods: obj.myMethod
    • Modules: my_module
    • Capitalized:
    • Constructors: MyConstructor
    • Constants: MY_CONSTANT

    View Slide

  21. Less mainstream rules

    View Slide

  22. Camel case
    Camel case:
    • JavaScript: decodeURIComponent, JSON
    • Shudder: XMLHttpRequest
    • I prefer: processHtmlFile

    View Slide

  23. Four spaces for indentation
    // My preference:
    // 4 spaces
    function abs(x) {
    if (x >= 0) {
    return x;
    } else {
    return -x;
    }
    }

    // Often used:
    // 2 spaces
    function abs(x) {
    if (x >= 0) {
    return x;
    } else {
    return -x;
    }
    }
    23

    View Slide

  24. One variable declaration
    per line
    // no
    var foo = 3,
    bar = 2,
    baz;
    !
    // yes
    var foo = 3;
    var bar = 2;
    var baz;

    Advantages:
    • Protects against some
    typos (forgetting a comma)
    • Easier: insert, delete,
    rearrange lines
    • Every line has context
    information
    • Automatically indented
    correctly
    24

    View Slide

  25. Coercing
    Use Boolean, Number, String (as functions) to
    coerce.
    !
    var bool = Boolean(7); // yes
    var bool = !!7; // no
    !
    var num = Number('123'); // yes
    var num = +'123'; // no
    !
    var str = String(true); // yes
    var str = ''+true; // no
    25

    View Slide

  26. Keep declarations
    local
    Close to where they are used.

    View Slide

  27. Keep declarations local
    // Often recommended:
    var elem;
    for (var i=0; ielem = arr[i];
    ...
    }
    !
    // I prefer:
    for (var i=0; ivar elem = arr[i];
    ...
    }
    27

    View Slide

  28. Keep declarations local
    // Often recommended:
    var tmp;
    if (x < 0) {
    tmp = -x;
    ...
    }
    !
    // I prefer:
    if (x < 0) {
    var tmp = -x;
    ...
    }
    28

    View Slide

  29. Keep declarations local
    Often recommended:"
    !
    // Only used inside loop
    function helperFunc() {
    ...
    }
    arr.forEach(function (x) {
    ...
    });

    I prefer:"
    !
    arr.forEach(function (x) {
    function helperFunc() {
    ...
    }
    ...
    });
    29

    View Slide

  30. Keep declarations local
    Advantages:
    • Code fragments are easier to
    • understand
    • move and reuse
    • delete
    • Often engines optimize automatically

    㱺 no performance penalty
    30

    View Slide

  31. Thanks!
    More info (chapter 26):
    speakingjs.com/es5/

    View Slide

  32. Bonus slides

    View Slide

  33. Object-orientation
    • Prefer constructors over other instance creation patterns
    • Mainstream
    • Optimized
    • Forward-looking (ECMAScript 6 classes are constructors)
    • Avoid closures for private data
    • Less elegant code
    • But: only way to keep data completely private
    • Use parens for constructor calls without arguments:
    var foo = new Foo; // no
    var foo = new Foo(); // yes
    33

    View Slide

  34. Avoid this as
    implicit parameter
    // Avoid
    $('ul.tabs li').on('click',
    function () {
    var tab = $(this);
    highlightTab(tab);
    ...
    });
    !
    // Prefer
    $('ul.tabs li').on('click',
    function (event) {
    var tab = $(event.target);
    highlightTab(tab);
    ...
    });
    34

    View Slide

  35. Avoid this as
    implicit parameter
    // Avoid
    beforeEach(function () {
    this.addMatchers({
    toBeInRange: function (start, end) {
    ...
    }
    });
    });
    !
    // Prefer
    beforeEach(function (api) {
    api.addMatchers({
    toBeInRange(start, end) {
    ...
    }
    });
    });
    35

    View Slide