Mejores prácticas de JavaScript


Tabla de contenido

    Mostrar tabla de contenidos


Evite las variables globales, evite new, evite ==, evite evaluación()


Evite las variables globales

Minimizar el uso de variables globales.

Esto incluye todos los tipos de datos, objetos y funciones.

Otras secuencias de comandos pueden sobrescribir las variables y funciones globales.

Utilice variables locales en su lugar y aprenda a utilizarlas. cierres.


Declarar siempre variables locales

Todas las variables utilizadas en una función deben declararse como variables locales.

Las variables locales deben declararse con var, la palabra clave let, o la palabra clave const, de lo contrario se convertirán en variables globales.

El modo estricto no permite variables no declaradas.


Declaraciones en la cima

Es una buena práctica de codificación colocar todas las declaraciones en la parte superior de cada script. o función.

Esta voluntad:

  • Dar código más limpio

  • Proporcionar un lugar único para buscar variables locales.

  • Facilite la prevención de variables globales no deseadas (implícitas)

  • Reducir la posibilidad de nuevas declaraciones no deseadas

// Declare at the beginning
let firstName, lastName, price, discount, fullPrice;
 
// Use later
firstName = "John";
lastName = "Doe";
price = 19.90;
discount = 0.10;
fullPrice = price - discount;

Esto también se aplica a las variables de bucle:

for (let i = 0; i < 5; i++) 
 {


Inicializar variables

Es una buena práctica de codificación inicializar las variables cuando las declaras.

Esta voluntad:

  • Dar código más limpio

  • Proporcionar un único lugar para inicializar variables.

  • Evite valores indefinidos

// Declare and initiate at the beginning
let firstName = "";
let lastName = "";
let price = 0;
let discount = 0;
let fullPrice = 0,
const myArray = [];
const myObject = {};

La inicialización de variables proporciona una idea del uso previsto (y del tipo de datos previsto).


Declarar objetos con const

Declarar objetos con const evitará cualquier cambio accidental de tipo:

Ejemplo

let car = {type:"Fiat", model:"500", color:"white"};
car = "Fiat";      // Changes object to string
const car = {type:"Fiat", model:"500", color:"white"};
car = "Fiat";      // Not possible

Declarar matrices con const

Declarar matrices con const evitará cualquier cambio accidental de tipo:

Ejemplo

let cars = ["Saab", "Volvo", "BMW"];
cars = 3;    // Changes array to number
const cars = ["Saab", "Volvo", "BMW"];
cars = 3;    // Not possible

No utilices un nuevo objeto()

  • Utilice "" en lugar de new String()

  • Utilice 0 en lugar de new Number()

  • Utilice false en lugar de new Boolean()

  • Utilice {} en lugar de new Object()

  • Utilice [] en lugar de new Array()

  • Utilice /()/ en lugar de new RegExp()

  • Utilice función(){} en lugar de nueva función()

Ejemplo

let x1 = "";             // new primitive string
let x2 = 0;              // new primitive number
let x3 = false;          // new primitive boolean
const x4 = {};           // new object
const x5 = [];           // new array object
const x6 = /()/;         // new regexp object
const x7 = function(){}; // new function object

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Literal Constructors</h2>
<p id="demo"></p>

<script>
let x1 = "";
let x2 = 0;
let x3 = false;
const x4 = {};
const x5 = [];
const x6 = /()/;
const x7 = function(){};

document.getElementById("demo").innerHTML =
"x1: " + typeof x1 + "<br>" +
"x2: " + typeof x2 + "<br>" +
"x3: " + typeof x3 + "<br>" +
"x4: " + typeof x4 + "<br>" +
"x5: " + typeof x5 + "<br>" +
"x6: " + typeof x6 + "<br>" +
"x7: " + typeof x7 + "<br>";
</script>

</body>
</html>

Cuidado con las conversiones automáticas de tipos

JavaScript está escrito libremente.

Una variable puede contener todos los tipos de datos.

Una variable puede cambiar su tipo de datos:

Ejemplo

let x = "Hello";     // typeof x is a string
x = 5;               // changes typeof x to a number

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p>A variable can chang its type. In this example x is first a string then a number:</p>

<p id="demo"></p>

<script>
let x = "Hello";
x = 5;
document.getElementById("demo").innerHTML = typeof x;
</script>

</body>
</html>

Tenga en cuenta que los números pueden convertirse accidentalmente en cadenas o NaN (no es un Número).

Al realizar operaciones matemáticas, JavaScript puede convertir números en cadenas:

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p>Remove the comment (at the beginning of the lines) to test each case:</p>

<p id="demo"></p>

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

document.getElementById("demo").innerHTML = x.valueOf() + " " + typeof x;
</script>

</body>
</html>

Restar una cadena de una cadena, no genera un error pero devuelve NaN (no es un número):

Ejemplo

"Hello" - "Dolly"    // returns NaN

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p>Subtracting a string from a string, does not generate an error but returns NaN (Not a Number):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello" - "Dolly";
</script>

</body>
</html> 

Uso === Comparación

El operador de comparación == siempre convierte (a tipos coincidentes) antes comparación.

El operador === fuerza la comparación de valores y tipos:

Ejemplo

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

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comparisons</h2>

<p>Remove the comment (at the beginning of each line) to test each case:</p>

<p id="demo"></p>

<script>
let x;
//x = (0 == "");   // true
//x = (1 == "1");  // true
//x = (1 == true);   // true
//x = (0 === "");  // false
//x = (1 === "1");   // false
//x = (1 === true);  // false
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>


Usar parámetros predeterminados

Si se llama a una función con un argumento faltante, el valor del argumento faltante El argumento se establece en indefinido.

Los valores no definidos pueden romper su código. Es un buen hábito asignar valores predeterminados valores a argumentos.

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>Setting a default value to a function parameter.</p>
<p id="demo"></p>

<script>
function myFunction(x, y) {
  if (y === undefined) {
    y = 0;
  }  
  return x * y;
}
document.getElementById("demo").innerHTML = myFunction(4);
</script>

</body>
</html>


ECMAScript 2015 permite parámetros predeterminados en la definición de función:

function (a=1, b=1) { /*function code*/  }

Lea más sobre los parámetros y argumentos de funciones en Parámetros de funciones


Termine sus cambios con los valores predeterminados

Siempre finalice sus declaraciones switch con un default. Incluso si crees que hay no es necesario.

Ejemplo

switch (new Date().getDay()) {
   
case 0:
      day = "Sunday";
      break;
  case 1:
      day = "Monday";
      break;
  case 2:
    day = "Tuesday";
     break;
   
case 3:
    day = "Wednesday";
      break;
   
case 4:
    day = "Thursday";
     break;
  case 5:
      day = "Friday";
      break;
  case 6:
    day = "Saturday";
      break;
  default:
    day = 
 "Unknown";
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
let day;
switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case  6:
    day = "Saturday";
    break;
  default:
     day = "unknown";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>

</body>
</html>

Evite números, cadenas y booleanos como objetos

Trate siempre los números, cadenas o valores booleanos como valores primitivos. No como objetos.

Declarar estos tipos como objetos ralentiza la velocidad de ejecución. y produce efectos secundarios desagradables:

Ejemplo

let x = "John";             
let y = new String("John");
(x === y) // is false because x is a string and y is an object.

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Objects</h2>
<p>Never create strings as objects.</p>
<p>Strings and objects cannot be safely compared.</p>

<p id="demo"></p>

<script>
let x = "John";        // x is a string
let y = new String("John");  // y is an object
document.getElementById("demo").innerHTML = (x === y);
</script>

</body>
</html>

O peor aún:

Ejemplo

let x = new String("John");             
let y = new String("John");
(x == y) // is false because you cannot compare objects.

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Objects</h2>
<p>Never create strings as objects.</p>
<p>JavaScript cannot compare objects.</p>

<p id="demo"></p>

<script>
let x = new String("John"); 
let y = new String("John");
document.getElementById("demo").innerHTML = (x == y);
</script>

</body>
</html>

Evite el uso de evaluación()

La función eval() se utiliza para ejecutar texto como código. En casi todos los casos, es No debería ser necesario utilizarlo.

Debido a que permite ejecutar código arbitrario, también representa una garantía de seguridad. problema.