Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a try..finally for loop with continue work in JavaScript?

Here is the example from You Don't 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 is it able to print all numbers if continue makes the loop jump over that iteration? To add to that, "console.log(i) runs at the end of the loop iteration but before i++" which should explain why it prints from 0 to 9?

like image 246
p1xel Avatar asked Aug 15 '16 08:08

p1xel


2 Answers

In fact in a try ... catch statement, 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 be executed every iteration whatever you do in the try block, that's why all the numbers were printed.

Documentation:

You can see from the MDN try...catch Documentation that:

The finally clause contains statements to execute after the try block and catch clause(s) execute, but before the statements following the try statement. The finally clause executes regardless of whether or not an exception is thrown. If an exception is thrown, the statements in the finally clause execute even if no catch clause handles the exception.

like image 120
cнŝdk Avatar answered Nov 04 '22 11:11

cнŝdk


Doc:

The finally clause contains statements to execute after the try block and catch clause(s) execute, but before the statements following the try statement. The finally clause executes regardless of whether or not an exception is thrown. If an exception is thrown, the statements in the finally clause execute even if no catch clause handles the exception.

So finally is always called after the catch statement.

like image 29
Marco Santarossa Avatar answered Nov 04 '22 12:11

Marco Santarossa