Search code examples
javascriptreturntry-catch

return statement does not work in javascript try block


return statement normally terminate function execution. But I have been realized that return statement does not work like what I expected? Where is the problem?

function SimpleSymbols() {
    ["a", "b", "c", "d"].forEach(function (char, index) {
        try {
            console.log("alert");
            return "false";  //this line does not work?
        } catch (err) {

        }
    });
}

SimpleSymbols();

Solution

  • forEach() does not return. You can return from outside of the loop once the loop is completed:

    function SimpleSymbols() { 
      var r;
      ["a", "b", "c", "d"].forEach(function (char, index) {
        try {
            console.log("alert");
            r = "false";  //this line does not work?
        } catch (err) {
        }
      });
      return r
    }
    
    console.log(SimpleSymbols());

    Instead you can use normal for loop:

    function SimpleSymbols() { 
      var arr = ["a", "b", "c", "d"]
      for(var i=0; i<arr.length; i++){
        try {
            console.log("alert");
            return "false";  //this line does not work?
        } catch (err) {
        }
      }
    }
    
    console.log(SimpleSymbols());