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

97
Views
Counting up and then back down in a for loop javascript
Function oddNumbers(){
Var odds ="";
For(index=0; index <=10; index ++){
If(index%2 !=0){odds+=index +"."}
}
}

OddNumbers();

Trying to count all odd counting numbers up then back down again in a for loop. I can get it to go up with the code again. But when I try nested for I cannot get it to go back down again in the same loop. How would I get it to loop up then back down?

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

0

Assuming you want to use only one loop definition, you have to define custom conditionExpression and incrementExpression.

Here is a quick example.

var direction = 1;

//REM: What gets added on each iteration?
function incrementExpression(){
  //REM: Increase or decrease depending on direction
    return 1*direction
}

//REM: What gets evaluated on each iteration?
function conditionExpression(i){
    if(i < 10 && direction === 1){
        return true
    }
    if(i === 10 && direction === 1){
        direction = -1
        return true
    }
    if(i >= 0 && direction === -1){
        direction = -1
        return true
    };

    //REM: Returns false if direction downwards and i lower zero
    return false
}

for(var i=0; conditionExpression(i); i+=incrementExpression(i)){
    console.log(i)
}

about 4 years ago · Juan Pablo Isaza Report

0

You can reverse your for loop on your use-case. See code snippet below:

function oddNumbers() {
var odds = "";
  
  for(index=0; index <=10; index ++){
    if(index%2 !=0) {
      odds+=index +"."
      console.log(odds);
    }
  }
  
  for(index = 10; index > 0; index--) {
    if(index % 2 != 0) {
    odds+=index +"."
        console.log(odds);
    }
  }
}

oddNumbers();

Im not sure if that's what you want but that's what I understand on your given code on your question.

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!