简体   繁体   中英

In ES6 JavaScript, we can use `let` in a for-loop but not in a while-loop?

The following works:

 let re = /\\d/g; while (result = re.exec("654 321")) console.log(result);

However, if we follow the way how a for-loop is written:

 for (let i = 0; i < 10; i++) console.log(i);

 for (const a of [1,3,5]) console.log(a);

and use (with the expected result of an error):

 let re = /\\d/g; while (let result = re.exec("654 321")) console.log(result);

then the let will break the code. What rule in ES6 governs that we cannot use let in this case? While usually, we declare a variable before the while statement, in this case, it makes sense not to. It might appear using a let or even const can make sense?

It's because everything inside the braces in your while-Statement is a condition. You cannot define new variables inside a condition.

You can use let inside the for loop, because of the structure:

for (<declare variable>;<condition>;<iterator>)

The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement:

 while (condition) statement

condition An expression evaluated before each pass through the loop. If this condition evaluates to true, statement is executed. When condition evaluates to false, execution continues with the statement after the while loop.

statement An optional statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements.

So having a statement in while in-place of a condition expression is not right syntactically. Please see this for more details .

the code snippet doesn't run for me. (edit: tried it again and it threw an error). but anyway it seems wrong: the initial statement of a for loop is executed only once. which means it defines i only once. but in the case of a while you are defining result again and again. Which is probably why it isn't allowed and throws an error

The let returns undefined, while the assignment to an undefined variable will return the value.

let a = 3;
// undefined;
b = 4;
// 4;

So your while loop will never run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM