Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

378
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!