0
if(case) {
  //statement
} else if {
 //statement
}

for() {
 //loop to create more else if statements
}

else {
}

Just curious to know if this should/can be done.

Example usage: If the user is making a selection from a dropdown list with values from 1-50, and there are different conditions to be executed onchange for each of those 50 values; else-if statements are then dynamically created using the for-loop for all those 50 different conditions.

===============================================================

Edit:

Great, thanks everyone. You just helped me save a great deal of time that I otherwise would've wasted trying to get this to work somehow; until eventually realizing it can't be done.

The only reason I tried something like this was because I didn't want to write 50+ else-if statements for each of my dropdown option.

Thank you Jonas W, Shane_IL for your answers.

7
  • i think u cannot use, usually if else will appear inside for loop Commented Jan 2, 2017 at 9:55
  • for ... else is not valid Commented Jan 2, 2017 at 9:56
  • That will throw a syntax error. Commented Jan 2, 2017 at 9:56
  • 1
    There will be better ways of doing things. what is your case scenario of thinking such a bold one? Commented Jan 2, 2017 at 9:57
  • 1
    Can you give little sample data? Its not straight but there can be ways to validate Commented Jan 2, 2017 at 10:00

2 Answers 2

1

May have a look at switches:

switch(input.value){
 case 1:
    alert("value is one");
 break;
 case 2:
   alert("value is two");
 break;
}

Or recursive functions:

function validate(val,start=0){
 if(val==start){
  alert("val is "+start);
 }else{
  validate(val,start+1);
 }
 }

validate(27);//will go trough 26 elses and one if...

Or create an array to resolve:

var resolve=[" one","two","three"];
alert(resolve[input.value]);
Sign up to request clarification or add additional context in comments.

Comments

0

There is no syntax that can do that.

You can create a unique evaluation function for each value, then you can do something like this:

for(let i=0;i < values.length; i++){
  if(values[i].evaluatorFunc()){
    //doSomething
  }
  else{
    doSomethingElse()  
  }
}

function doSomethingElse(){
  //here you can run the same code anytime the loop enters else
}

2 Comments

If values is an array i<values is a bit weird
Doh! .length, i always forget .length

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.