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

115
Views
Swapping Two Numbers, but only in a special case

I guess we all know about destructuring to swap two variables a and b, namely: [a, b] = [b, a] and other clever ways like a = b + (b = a, 0). However, I have a different situation which I feel should have a simple answer.

I have a variable a that can be one of 0, 1, 2, 3, 4, 5, or 6. If it is a===3 then I want a to reassign to 4. If a===4 then I want a to reassign to 3. BUT if a is any of the other values, I want it to remain the same.

So is there a clever, 1 line bit of code that can do this? For completeness, I want a short version of this:

switch(a){
    case 3: a = 4; break;
    case 4: a = 3; break;
    // default: a = a; break; // Hashed out, because it is not needed
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You could take an object for swapping the values and the value directly as default value, like

a = { 3: 4, 4: 3 }[a] || a;

If you like to work with a falsy value, like zero, you could take the Nullish coalescing operator ?? instead of logical OR ||.

a = { 3: 4, 4: 3 }[a] ?? a;
about 4 years ago · Juan Pablo Isaza Report

0

Using a Computed Property Name

function test(a) {
  a = { [a]: a, 3: 4, 4: 3 }[a]; 
  return a;
}


[0, 1, 2, 3, 4, 5].forEach(n =>console.log(n, test(n)));

about 4 years ago · Juan Pablo Isaza Report

0

You could use nested ternary operators, but I think your current switch code is easier to understand:

a = a === 3 ? 4 : a === 4 ? 3 : a;
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!