Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

386
Vistas
JS: Switch statement default versus having the default outside of the switch?

if there is a switch statement that has a default, would the same be achieved by just putting whatever is in the default under the switch statement?

1)

function test(foo) {
   switch(foo.num) {
      case "1": 
        return "hello"
      case "2":
        return "bye"
      default: 
        return "neither"
   }
}
function test(foo) {
   switch(foo.num) {
      case "1": 
        return "hello"
      case "2":
        return "bye"
   }
   return "neither"
}

do these both always operate the same way or is there something I am overlooking?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

For what you're doing, they're the same, but only because you're returning. Switch is often used for other statements other than return though, eg:

function test(foo) {
   switch(foo.num) {
      case "1": 
        console.log('1');
        break;
      case "2":
        console.log('2');
        break;
      default: 
        console.log('nope');
   }
}

Above, it'll log exactly one value when the function is called. But if you do

function test(foo) {
   switch(foo.num) {
      case "1": 
        console.log('1');
        break;
      case "2":
        console.log('2');
        break;
   }
   console.log('nope');
}

it may log 1 or 2, but then it'll also log nope regardless - because you aren't returning inside the switch.

In the case that you just want to return a value depending on another value, consider using an object instead - it's a lot more concise (and easier to understand).

const returnValues = {
  1: 'hello',
  2: 'bye',
};
const test = foo => returnValues[foo] ?? 'neither';
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda