Sítios Web II [SW2]

Boas práticas no JavaScript

ProfºEduardo Pezutti

http://maverick.td.utfpr.edu.br/slides/sw2 link

Boas práticas no JavaScript

Cuidado com as variáveis globais

E sempre declare as variáveis locais (usando o var)

Não use new Object()

Nunca declare números, strings e booleanos como objetos

  • Use {} - new Object()
  • Use "" - new String()
  • Use 0 - new Number()
  • Use false - new Boolean()
  • Use [] - new Array()
  • Use /(:)/ - new RegExp()
  • Use function (){} - new function()

Como criar tipo de dados


var x = {};           // new object
var x = "";           // new primitive string
var x = 0;            // new primitive number
var x = false;        // new primitive boolean
var x = [];           // new array object
var x = /()/;         // new regexp object
var x = function(){}; // new function object

Cuidado com as mudanças automáticas de tipo de dados

Mudanças automáticas


var x = 5 + 7;       // x.valueOf() is 12,  typeof x is a number
var x = 5 + "7";     // x.valueOf() is 57,  typeof x is a string
var x = "5" + 7;     // x.valueOf() is 57,  typeof x is a string
var x = 5 - 7;       // x.valueOf() is -2,  typeof x is a number
var x = 5 - "7";     // x.valueOf() is -2,  typeof x is a number
var x = "5" - 7;     // x.valueOf() is -2,  typeof x is a number
var x = 5 - "x";     // x.valueOf() is NaN, typeof x is a number

"Hello" - "Dolly"    // returns NaN

Nunca termine uma definição com vírgula


points = [40, 100, 1, 5, 25, 10, ];

person = {firstName:"John", lastName:"Doe", age:46, }

Define valores padrões para os parâmetros


function myFunction(x, y) {
    if (y === undefined) {
          y = 0;
    }
}

function myFunction(x, y) {
    y = y || 0;
}

Use a comparação ===


0 == "";        // true
1 == "1";       // true
1 == true;      // true

0 === "";       // false
1 === "1";      // false
1 === true;     // false

Cuidado com o eval()

Performance

Coloque o script no fim do body

Deixe o html carregar primeiro

Reduza o acesso ao DOM


obj = document.getElementByID("demo");
obj.innerHTML = "Hello";

Não crie variáveis desnecessárias


var fullName = firstName + " " + lastName;
document.getElementById("demo").innerHTML = fullName;
/*------------------------------------------------------------------------------------*/
document.getElementById("demo").innerHTML = firstName + " " + lastName;

Cuidado com os loops

bookmarklets

Criando [EN]
Usar [PT-BR]

Links

Evoluindo

Criando plugins para o Chrome.


Firefox Developer e Doc.

ProfºEduardo Pezutti

epsantos@utfpr.edu.br link