Check for loop is moving in the right direction

Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

Metadata

ID: javascript-best-practices/for-direction

Language: JavaScript

Severity: Error

Category: Best Practices

Description

This rule prevents you from creating conditions in which a for loop might end up in an infinite loop. If you need an infinite loop, use while statements.

Non-Compliant Code Examples

// test if '++', '--'
for(var i = 0; i < 10; i--){}
for(var i = 0; i <= 10; i--){}
for(var i = 10; i > 10; i++){}
for(var i = 10; i >= 0; i++){}

// test if '+=', '-='
for(var i = 0; i < 10; i-=1){}
for(var i = 0; i <= 10; i-=1){}
for(var i = 10; i > 10; i+=1){}
for(var i = 10; i >= 0; i+=1){}
for(var i = 0; i < 10; i+=-1){}
for(var i = 0; i <= 10; i+=-1){}
for(var i = 10; i > 10; i-=-1){}
for(var i = 10; i >= 0; i-=-1){}

Compliant Code Examples

// test if '++', '--'
for(var i = 0; i < 10; i++){}
for(var i = 0; i <= 10; i++){}
for(var i = 10; i > 0; i--){}
for(var i = 10; i >= 0; i--){}

// test if '+=', '-=',
for(var i = 0; i < 10; i+=1){}
for(var i = 0; i <= 10; i+=1){}
for(var i = 0; i < 10; i-=-1){}
for(var i = 0; i <= 10; i-=-1){}
for(var i = 10; i > 0; i-=1){}
for(var i = 10; i >= 0; i-=1){}
for(var i = 10; i > 0; i+=-1){}
for(var i = 10; i >= 0; i+=-1){}

// test if no update.
for(var i = 10; i > 0;){}
for(var i = 10; i >= 0;){}
for(var i = 10; i < 0;){}
for(var i = 10; i <= 0;){}
for(var i = 10; i <= 0; j++){}
for(var i = 10; i <= 0; j--){}
for(var i = 10; i >= 0; j++){}
for(var i = 10; i >= 0; j--){}
for(var i = 10; i >= 0; j += 2){}
for(var i = 10; i >= 0; j -= 2){}
for(var i = 10; i >= 0; i |= 2){}
for(var i = 10; i >= 0; i %= 2){}
for(var i = 0; i < MAX; i += STEP_SIZE);
for(var i = 0; i < MAX; i -= STEP_SIZE);
for(var i = 10; i > 0; i += STEP_SIZE);

// other cond-expressions.
for(var i = 0; i !== 10; i+=1){}
for(var i = 0; i === 10; i+=1){}
for(var i = 0; i == 10; i+=1){}
for(var i = 0; i != 10; i+=1){}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis