What does the "do" function in JavaScript do?


I've searched a lot and can't find the functionality of do in JavaScript. Example:

function b(a, b) {
    do a = a[b]; while (a && 1 !== a.nodeType);
    return a


Same as in other languages, it's just a flow control. It is a markup for a loop to know where it starts. It is considered a label . Note that it's not a function, it's a keyword that determines what the code should do, we can say it's a command.

It is used in a while that we can call inverted. That is, it first enters the loop, without any conditions, executes all of it and at its end it is checked whether or not to continue repeating this loop. If the decision is to continue then the repetition returns exactly to the do line. So the loop will always be executed at least once.

Without it, using the normal while , it may not even be executed the first time, if the condition is false.

You can live without it, but the code can get more confusing, nothing serious, but it's possible that you have to "juggle" or use a flag variable so that the first time it runs guaranteed.

The braces were omitted because the code block is only one line, so it's a simplified form. In general it is better to avoid this style, it is more difficult to read. You could do it in one line with braces:

do { a = a[b]; } while (a && 1 !== a.nodeType);

Easier to understand:

do { //marca o ínico do laço
    a = a[b];  //faz o que tem que fazer
} while (a && a.nodeType !== 1); //só agora verificará se deve repetir

without the do :

a = a[b];
while (a && a.nodeType !== 1) { //a condição é a mesma, só é executada em outro momento
    a = a[b];
} //aqui marca o fim, certamente voltará para o início para decidir se continuará

I put it on GitHub for future reference .

Whenever you want to know something about JavaScript the MDN can be considered the official documentation .

Scroll to Top