DEV Community

Cristian Fernando
Cristian Fernando

Posted on

4 1

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

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.


Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong · web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌶️🔥

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay