Paracetamol.js💊| #96: Explica este código JavaScript

Cristian Fernando - Apr 8 '22 - - Dev Community

Explica este código JavaScript

const sumar = (a,b) => {
  if(!a || !b){
    throw new Error("faltan parametros");
  }
  return a + b;
}

console.log(sumar(2,2));
console.log(sumar(2,true));
console.log(sumar(2,0));
Enter fullscreen mode Exit fullscreen mode

A. 4, "2true", 2
B. 4, 3, Error: falta de parametros
C. "22", "3true", "20"
D. 4, 3, 2

➡ Respuesta ⬅

B. 4, 3, Error: falta de parametros

Primer caso:
Simple suma de números enteros.

Segundo caso:
Por inferencia de tipos, el parámetro true se convierte en 1, por ello el resultado es 3.

Tercer caso:
En el if usamos el operador de negación para la validación de parámetros, esto hace que los valores falsy también se vean afectados y nos arroje la excepción. Para arreglar esto podríamos hacer lo siguiente:

const sumar = (a,b) => {
  if(a === undefined || b === undefined){
    throw new Error("faltan parametros");
  }
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

De esa manera no solo cuando alguno de los parámtros no este definido en la llamada de la función se lanza la excepción.


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .