Is there a Javascript equivalent of the python \'for-else\' loop, so something like this:
searched = input(\"Input: \");
for i in range(5):
if i==searched:
Yes, it is possible to do this without a flag variable. You can emulate for … else statements using a label and a block:
function search(num) {
find: {
for (var i of [0,1,2,3,4]) {
if (i===num) {
console.log("Match found: "+ i);
break find;
}
} // else part after the loop:
console.log("No match found!");
}
// after loop and else
}
That said, I would recommend against doing this. It is a very unconvential way of writing this and will lead to poor understanding or confusion. An early return is acceptable though, and can be used in a helper function if you need to continue with execution after the loop.