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

Javascript Best Practices

Javascript Best Practices

Talk about some Javascript features that should be used with caution.

Jonathan Alvarez

March 19, 2015
Tweet

Other Decks in Technology

Transcript

  1. '5' + - + - - + - - +

    + - + - + - - - '3'
  2. '5' + - + - - + - - +

    + - + - + - - - '3' '53'
  3. var foo = "value";! ! var moo = function() {!

    ! foo = "Change global";! } // Place a var statement! // outside of any function
  4. var moo = function() {! ! ! var foo =

    "yay!";! ! // ....! ! } // The right way
  5. var MYAPP = {};! ! var MYAPP.author = {! "first-name"

    : "Jonathan",! "username" : "@jonalvarezz"! };! ! var MYAPP.speakAt = {! "name" : "PereiraJS",! "location" : "Pereira"! };! // Need globals?
  6. function moo() {! ! } // function statement var moo

    = function() {! ! } // function expression
  7. moo(); // Prints "foo"! ! function moo() {! ! console.log("foo");!

    } // function statement! // defined at run-time
  8. moo(); // Error! ! var moo = function() {! !

    console.log("foo");! } // function expression! // defined at parse-time
  9. if (true) { ! ! function foo() {! ! !

    return 1;! }! }! else { ! ! function foo() {! ! ! return 2;! }! }! ! foo(); ! // function statement
  10. if (true) { ! ! function foo() {! ! !

    return 1;! }! }! else { ! ! function foo() {! ! ! return 2;! }! }! ! foo(); // 2 ! // function statement
  11. var foo;! ! if (true) { ! ! foo =

    function() {! ! ! return 1;! }! }! else { ! ! foo = function() {! ! ! return 2;! }! }! ! foo(); // 1 ! // function expression
  12. var myMath = {! ! add: function( a, b )

    {! ! ! return a + b;! ! }! };! ! myMath.add( 2, 4 ); // 6 ! // function expression
  13. (function() {! ! ! ! 'use strict';! ! ! var

    a, b, c;! ! ! // ...! ! })(); // function statement! // Anonymous function! // Self invoked function
  14. ! var foo = function() {! ! var a =

    3, b = 5;! ! ! var bar = function() {! ! ! var b = 7, c = 11;! ! ! ! a += b + c;! ! };! ! ! bar();! ! ! return a;! }
  15. ! var foo = function() {! ! var a =

    3, b = 5;! ! ! var bar = function() {! ! ! var b = 7, c = 11;! ! ! ! a += b + c;! ! };! ! ! bar();! ! ! return a;! } // 21
  16. ! var foo = function() {! ! var a =

    3, b = 5;! ! ! var bar = function() {! ! ! var b = 7, c = 11;! ! ! ! a += b + c;! ! };! ! ! bar();! ! ! return a;! } // 21 Function Scope!
  17. var seria_maker = function() {! ! var prefix = '';!

    ! var seq = 0;! ! return {! ! ! set_prefix: function(p) {! ! ! ! prefix = String(p);! ! ! },! ! ! set_seq: function(s) {! ! ! ! seq = s;! ! ! },! ! ! gensym: function() {! ! ! ! var result = prefix + seq;! ! ! ! seq += 1;! ! ! ! return result;! ! ! }! ! };! }; // Object that generates uniques strings
  18. var sm = seria_maker();! ! sm.set_prefix('Q');! ! sm.set_seq(1000);! ! var

    unique = sm.gensym();! ! // Q1000 // Object that generates uniques strings