{ Buenas prácticas Javascript }

Es el único lenguaje en el que me doy cuenta que las personas sienten que no necesitan aprenderlo antes de empezar a utilizarlo.

Douglas Crockford

<script>

<!doctype html>
<html class="no-js" lang="">
    <head>
        ...
        <link rel="stylesheet" href="css/main.css">
        <script src="js/vendor/modernizr-2.8.3.min.js"></script>
    </head>
    <body>
        

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

        <script src="js/main.js"></script>

        <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
        <script>
            (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
            function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
            e=o.createElement(i);r=o.getElementsByTagName(i)[0];
            e.src='//www.google-analytics.com/analytics.js';
            r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
            ga('create','UA-XXXXX-X','auto');ga('send','pageview');
        </script>
    </body>
</html>

<script> position

Browser Render

Browser Render

Browser Render

Browser Render

<a id="sign_in" href="..." onclick="customFunction('userSignin');">Sing In</a>

Javascript --> html

Bad

<a id="sign_in" href="...">Sing In</a>

Good

$('#sing_in').on('click', function(event) {

    // Code...

    event.preventDefault()
    return false;            // Fix Firefox

});

html

js

Javascript JIT

Just-In-Time Compiler

function f() {
    eval("");
    var sum = 0;
    for (var i = 0; i < N; ++i) {
        sum += i;
    }
}
function f() {
    var sum = 0;
    for (var i = 0; i < N; ++i) {
        sum += i;
    }
}

Eval

Bad

Good

var a = 1;
var b;
var n = 100;
function sumNumberToUndefined() {
    var sum = 0;
    for (var i = 0; i < n; ++i) {
        sum += (a + b);
    }
}
var a = 1;
var c = 2;
var n = 100;

function sumNumberToNumber() {
    var sum = 0;
    for (var i = 0; i < n; ++i) {
        sum += (a + c);
    }
}

Type of variable

Bad

Good

var N = 100;
var popdata = { 'New York': 6 };
var NY = {
    id: 'New York',
    population: '5M'
};

function getPop(city) {
    return popdata[city.id];
}

function noOptimized(city) {
    var total = 0;
    for (var i = 0; i < N; ++i) {
        total += getPop(city);
    }
}
var N = 100;
var popdata = { 'New York': 6 };
var NY = {
    id: 'New York',
    population: '5M'
};

function optimized(city) {
    var total = 0;
    for (var i = 0; i < N; i++) {
        total += popdata[city.id];
    }
}

Functions

Bad

Good

Javascript language

var test = 'pf';                        // Space before and after =
                                        // Add a line between your different code parts
function test() {                       // Space between function keyword and the name 
				        // of the function itself - Space between function 
					// name and the parenthesis.
    return {                            // Indent with four or 2 spaces more on each new block.
        test: 'test'                    // Space after : in objects.
    };
}

function () {                           // Space between function keyword and the parenthesis 
					// if its an anonymous function
    console.log('hei');                 // Space after opening parenthesis and before closing 
    					// parenthesis in function calls.
}

function test2(argument1, argument2) {  // Space between function keyword and the name of the
					// function itself - Space
    return argument1 + argument2;
}

if (test === 'pf') {
    console.log('pf');
}

for (var i = 0; i < 10; i++) {

}

Spaces & indentation

var x = 'john';
var y = 'o\'connor';
var z = 'Hello World!';
var this_is_a_...developer = 'John';
var name = 'john';
var surname = 'o\'connor';
var message = 'Hello World!';
var fullname = 'John O\'connor';

Variables | basic

Bad

Good

var i = 0;
var len = [ 1, 2, 3, 4, 5].length;
var o = document.getElementById('item_1');
var indexIterationNumbers = 0;
var lenNumbers = [ 1, 2, 3, 4, 5].length;
var domItemElement = document.getElementById('item_1');

Variables | camelCase

Bad

Good

Check variables

== vs ===

console.log( false == 0 );              // true
console.log( false == '' );             // true
console.log( 0 == "" );                 // true
console.log( undefined == undefined );  // true
console.log( undefined == null );       // true
console.log( NaN == null );             // false
console.log( NaN == NaN );              // false

Check variables

console.log( false === 0 );              // false
console.log( false === '' );             // false
console.log( 0 === "" );                 // false
console.log( undefined === undefined );  // true
console.log( undefined === null );       // false
console.log( NaN === null );             // false
console.log( NaN === NaN );              // false

Bad

Good

var name;
if ( name === undefined || name === null) {
	// Code...
}

var name;
if ( name == null) {
	// Code...
}

'use strict'
var name;
if ( typeof name === 'undefined') {
	// Code...
}

Compare type

;

;(function ( $, window, document, undefined ) {

    // Code...

})( jQuery, window, document );

Protect our code

jQuery

$('.modal-layer').addClass('modal-fade-in');
$('.modal-layer').removeClass('modal-fade-out');
$('.modal-layer').click( function(event) {
		...
});

jQuery syntax

Bad

var $modalLayer = $('.modal-layer');

$modalLayer.addClass('modal-fade-in').removeClass('modal-fade-out').click( function(event) {
		...
});

jQuery sintax

Good

var $modalLayer = $('.modal-layer');

$modalLayer
	.addClass('modal-fade-in')
	.removeClass('modal-fade-out')
	.on('click', function(event) {
		...
	}
});

jQuery syntax

Very Good

Performance

var $elements = $('.element');

// [Doc] Type: Function( Integer index, Element element )
$elements.each( function(index, element) {

    console.log( element[index] );

});
var $elements = $('.element');

for ( var i = 0; i <= $elements.length; i++ ) {
    
    console.log( $element[i] );

}

$.each vs for

Bad

Good

console.time('Loop');

for ( var i = 0; i < 1000000; i++ ) {
    var sum = 0;
    sum = sum + i;	
}

console.timeEnd('Loop');

Tip | Console.Time

(function () {
    var test1 = 'test';
    var test2 = 'test2';
    var test3 = 'test3';
    var test4 = 'test4';
    var concatenate = function (name) {
        return test1 + test2 + test3 + test4 + name;
    };
}());
(function () {
    var e = "test";
    var d = "test2";
    var c = "test3";
    var b = "test4";
    var a = function (f) {
        return e + d + c + b + f
    }
}());

Minification

Bad

Minimized

(function () {
  var test1 = 'test',
      test2 = 'test2',
      test3 = 'test3',
      test4 = 'test4',
      concatenate = function (name) {
          return test1 + test2 + test3 + test4 + name;
      };
}());
(function () {
    var e = "test", d = "test2", c = "test3", b = "test4", a = function (f) {
        return e + d + c + b + f
    }
}());

Minification

Good

Minimized

var person = new Object(Object.prototype);

person.firstName = "Joan";
person.lastName = "Leon";
person.mail = "joan.leon@gmail.com";
var person = {};

person.firstName = "Joan";
person.lastName = "Leon";
person.mail = "joan.leon@gmail.com";

Minification

Bad

Good

var aArr = new Array();

aArr[0] = "Joan";
aArr[1] = "Leon";
aArr[2] = "joan.leon@gmail.com";
var aArr = [];

aArr[0] = "Joan";
aArr[1] = "Leon";
aArr[2] = "joan.leon@gmail.com";

attribute Async

<script>
	var script = document.createElement('script');
	script.src = "http://domain.com/awesom-lib.js";
	document.getElementById('head')[0].appendChild(script);
</script>

Async | external libs

<script src="http://udacity-crp.herokuapp.com/time.js?rtt=1&a" async></script>
<script src="http://udacity-crp.herokuapp.com/time.js?rtt=1&b" async></script>

Async | external libs

Async | external libs

Conclutions

Escribe código como si el boss final del juego Q lo tuvieras en la nuca...

Game Over

Algunos de los códigos de ejemplo están extraídos de https://github.com/tcorral/Javascript-Best-Practices de Tomás Corral

Las imágenes de fondo de cada sección pertenecen a http://platformerpower.com/

 

Buenas-Practicas-Javascript

By Joan León

Buenas-Practicas-Javascript

  • 2,765
Loading comments...

More from Joan León