For else loop in Javascript?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)