Hello,
I’m very new to JS and I just begin this great tutorial from freecodecamp.org.
But I rich my first bottleneck on step 41 where the info advise me to use const to declare a variable.
" Create a for...of
loop to iterate through your rows
array, assigning each value to a row
variable."
“You should use const to declare your row variable.” is the message if I use let to declare row.
const = constant/unchangeable
variable = changeable
My code is blow,
const row=""
let y=0;
for(y of rows) row = rows[y];
And this is the message: “TypeError: “row” is read-only”
What could be the solution?
Thank you
Please share a link to the step you are on with the instructions.
for(y of rows) row = rows[y];
I would examine the syntax here and look again if there is an example.
Hello,
I think you are confusing between the for of
loop and a traditional for
loop and how they work with arrays
- the traditional
for
loop takes a variable with an initial value and keeps updating that value according to a provided expression until this value no longer validates the given condition
- See the example below when working with an array
const arr = [1, 2, 3,];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Notice how we use the given index to access the array elements
- The
for of
loops behave differently with arrays, the variable that we use to iterate over an array is not the corresponding index of the array element, it is the corresponding array element itself, which means if we want to use the for of
to make the first example again, it is going to be like this
const arr = [1, 2, 3];
for (const element of arr) {
console.log(element);
}
the for of
loops do not work with objects
One last thing, you are declaring a constant variable named row
then you are trying to change it resulting in the error shown in the console, you should instead make the variable y
constant and declare it inside the for of
loop
(https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures-v8/learn-introductory-javascript-by-building-a-pyramid-generator/step-41)
Magic key:
for(const row of rows){}
“for…of” loop body should be empty = {}.
I learn something good today.
Thank you all for your support.
1 Like