Try/catch on JS

Asked

Viewed 558 times

6

I own a array called agenciasUri, which format the data before inserting into it. After that, I mount JSON jsonObjto send a request. What I found strange is that it is working properly.

Why can I access agenciasUri? How the visibility of a variable within a Javascript loop works)?

$scope.salvar = function () {
        var agenciasSeparadas = $scope.opcoes + '';
        agenciasSeparadas = agenciasSeparadas.split(',');
        try {
            var agenciasUri = [];
            for (var i = 0; i < $scope.listaAgencias.length; i++) {
                var json = $scope.listaAgencias[i];
                for (var k = 0; k < agenciasSeparadas.length; k++) {
                    if (json.nome == agenciasSeparadas[k]) {
                        agenciasUri.push(json._links.self.href);
                    }
                }
            }
        } catch (err) {
            alert(err);
        }

        var jsonObj = {
            nome: $scope.nome,
            tipo: $scope.tipo,
            agencias: agenciasUri
        };



        alert(JSON.stringify(jsonObj));
        veiculosAPI.postVeiculo(jsonObj)
            .success(function (data, status, headers, config) {
                $scope.nome = null;
                $scope.tipo = null;
            }).error(function (data, status, headers) {
                alert("Erro ao salvar dados do veiculo!");
                alert(data + "\t" + JSON.stringify(data));
            });

    };

1 answer

8


The point is that Javascript has the variable scope declared with var location to the function and not to the execution block, as occurs in other languages. This phenomenon is known to Hoisting.

So no matter where you declare the variable, it will exist in the entire function. But not outside it.

Only variables declared outside the function are global or at least regional. By regional understand that a variable can be accessible within the function where it was declared and within functions contained in this function.

With Ecmascript 6 you can use the let which allows the use of block scope, as found in other languages. More details on the difference between them can be found in that question.

The idea of the scope of var It’s not bad, the problem is that it was poorly implemented. If you declare twice the same variable within a function, in different blocks, it is accepted without errors. This should not happen. But by the philosophy of language the second statement normally functions as if it were an assignment. This is confusing. Another problem is that the variable exists even if it has been declared after its use.

In this way, the "modern" style of programming is to use whenever possible, and always is in modern browsers, the let. It’s a pity that there is still no guaranteed support in browsers that are in full use (this has changed since this answer, almost no longer has this problem).

I mean, this is not something specific to try-catch, is valid for any block.

More information on this question in the OS.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.