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

124
Views
Why does assignment with help from ternary operator doesn't work as expected in JS?
var a = 0;
var param = 'add';
while(a < 50){
    console.log(a); //prints out values from 0 to 49
    if(param === 'add'){
        a = a + 1;
    }else{
        a = a - 1;
    }
}

While being very simple and doing its job, I would like to make this code shorter

while(a < 50){
    console.log(a);
    a = a + (param === 'add')? 1 : -1;
}

But a never grows and stays 1. Could anyone explain such behavior?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The expression is evaluated as

a = (a + (param === 'add')) ? 1 : -1;

which boils down to

a = 1;

You may solve this by writing

a = a + ((param === 'add') ? 1 : -1);

or even shorter:

a += (param === 'add') ? 1 : -1;
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!