Check for loop is moving in the right direction

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

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

PREVIEWING: rtrieu/product-analytics-ui-changes