Saw this short paragraph from MDN JavaScript reference page on for...of statement, at around the end of Description section, it says:
You can use destructuring to assign multiple local variables, or use a property accessor like for (x.y of iterable) to assign the value to an object property.
What does it mean? You can't have x.y
syntax for defining the local variable in a for...of
statement.
I tried this verbatimly in a short script file using node. Error message was ReferenceError: x is not defined
What I'd missed?
You can use destructuring to assign multiple local variables,
This means that we can destructure the array of object in the for loop.
For example,
const iterable = [{a:'1', b:'10'}, {a:'2', b:'20'}, {a:'3', b:'30'}];
for (let {a, b} of iterable) {
console.log(a);
console.log(b);
}
or use a property accessor like for (x.y of iterable) to assign the value to an object property.
This means that we can use property accessor to assign the value from the array to our object's property.
For example,
const iterable = [{a:'1', b:'10'}, {a:'2', b:'20'}, {a:'3', b:'30'}];
let obj = {iterateValue:'', anyOtherValue:'Anything'}
// let obj = {}
// can be an empty object
for (obj.iterateValue of iterable) {
console.log(obj);
}
You can't have x.y syntax for defining the local variable in a for...of statement.
You need to define the object x before the for loop. Not in the for...of statement
.
ReferenceError: x is not defined
This error means you have not defined x and trying to use it. You need to define it before the for loop.