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

218
Views
Correct way to toggle between two string values with ternary expression

I am trying to have a string that toggle between two values. I have declared as ternary

public position: string = (this.position == "positionOne" ? "positionOne" : "positionTwo");

What I would like to have a function for directly toggle from "positionOne" to "positionTwo" (value of the string). Something like `

togglePosition = function() 
     {this.position = !this.position}

and then it takes the opposite string as value. Or I need to do the complete evaluation also if declared as ternary? and then see if (position = "positionOne")... do whatever.. or else the upside down. You know what I mean? :) What solution you suggest to me?

Thanks a lot from now

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You could use an object and the keys as the wanted value.

function toggle(v) {
    return { positionOne: 'positionTwo', positionTwo: 'positionOne' }[v];
}
 
var position = 'positionOne';
console.log(position);
position = toggle(position);
console.log(position);
position = toggle(position);
console.log(position);

about 4 years ago · Santiago Trujillo Report

0

As an alternative you could use this (in cases where the values do not match "half-way"):

function toggle(pos) {
    return 'positionOnepositionTwo'.replace(pos, '');
}

pos = 'positionOne';
console.log(pos = toggle(pos));
console.log(pos = toggle(pos));
console.log(pos = toggle(pos));

Alternative with find

function toggle(pos) {
    return ['positionOne','positionTwo'].find(x => x !== pos);
}

pos = 'positionOne';
console.log(pos = toggle(pos));
console.log(pos = toggle(pos));
console.log(pos = toggle(pos));

about 4 years ago · Santiago Trujillo Report

0

Of course, you could use Array.find to do the same thing Nina mentioned:

var log = console.log;
function toggle(v) {
   return ['positionOne','positionTwo'].find(s=>s!=v);
}
 
var position = 'positionOne';
log( position );

position = toggle(position);
log( position );

position = toggle(position);
log( position );

about 4 years ago · Santiago Trujillo 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!