How to try ... to continue the loop with continued work in JavaScript?

Here is an example from You Do not Know JS:

for (var i=0; i<10; i++) { try { continue; } finally { console.log( i ); } } // 0 1 2 3 4 5 6 7 8 9 

How can it print all numbers, if you continue, makes the loop jump over this iteration? To add to this, "console.log (i) executes at the end of the loop, but until I ++," which should explain why it prints from 0 to 9?

+5
source share
2 answers

In fact, in the try ... catch the finally block will always be reached and executed.

So here in your case:

 for (var i=0; i<10; i++) { try { continue; } finally { console.log( i ); } } 

The finally block will run every iteration, whatever you do in the try block, so all numbers have been printed.

Documentation:

You can see from MDN try ... catch Documentation , which:

The finally clause contains statements to execute after the try and catch block have been executed, but before the statements following the try statement. The finally clause is executed regardless of whether an exception is thrown. If an exception is thrown, the statements in the finally clause are executed even if the catch clause does not handle the exception.

+4
source

Doc :

The finally clause contains instructions to execute after the try block and catch (s), but before the operations following the try. The finally clause is executed regardless of whether it is an exception. If an exception is thrown, statements in the finally clause are executed, even if no catch clause handles the exception.

So finally, it is always called after the catch statement.

+1
source

All Articles