For example, in the code below I use ; instead of leaving, var or const. What is the name of this operator?
var cars = ["Audi", "BMW", "Corolla", "Honda"]
let i = 2;
let len = cars.length;
let text = "";
for (; i < len; i ) {
text = cars[i] "<br>";
}
Does it serve to clone other variables?
CodePudding user response:
Normal for loops have 3 components inside the brackets, all of which are optional and you can have any combination of them:
for ([initialExpression]; [conditionExpression]; [incrementExpression])
statement
The semicolon ;
is not an omission operator as much as it is a separator for the 3 components. If you omit any component, the separating semicolon stays, otherwise it would be ambiguous which component was omitted.
Your example omitted the initialization statement component. This is not an operator, does not have an established name, and it does nothing (i.e. avoids defining a variable exclusively for the loop as is typically the case).
As Nick mentioned, omitting components in for loops is often bad practice and should be avoided. But it can be fine in some situations like when re-using a variable across multiple for loops.
Relevant Resource: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement
CodePudding user response:
It's not an operator. It's just not putting anything in the initialization statement of your loop.
Note that doing this is bad practice. It's confusing and almost never actually useful.
CodePudding user response:
first part of head of for is for variable initialization and can be omitted and run only once
you can define your variable there or above and use it in other parts or body of for.
in facts, all 3 parts of for head is optional and can be omitted:
- if you remove condition part: for run forever
- if you remove change (increment) part: your variable doesnt change in head and you must change it in body...
- if you remove first part: you must use another variable that you defined before