I have a question that’s been nagging at me for quite a while now:
I’ve noticed when referencing example code in lessons about array iteration that the array can have a title implying plurality, while the iterator implies singularity. I created an example below to illustrate this. Is this normal behavior for js, in that the language is sophisticated enough to connect singular and plural versions of the same word (perhaps only in this context)? Thank you in advance!
let cookies = [ "tollhouse", "snickerdoodle", "thumbprint", "teacake" ];
cookies.forEach(cookie => {
console.log(cookie);
})
Not quite. This is more a case of using clear and logical names for your variables.
Methods like the .forEach take a callback function, which accepts parameters. The first parameter is the element of each iteration.
const array = [0, 1, 2, 3, 4]
array.forEach(element => console.log(element));
// will print each element to the console
However, that example I gave doesn’t work so well in production code, because it’s not maintainable (what type of data does the array hold? What does an element represent?)
If I clarify my variable names, it becomes a bit more readable:
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
Yes, but there is still a distinct difference in that the array is titled as a plural word, but the iterator is using a singular word inside of the function without creating a new variable. The two are technically different, yet it still works. What I’m asking is: is this typical behavior for js, and can I count on this to work in my own code in the future? Thank you.
Yes, that’s what I originally thought. I just had major fundamental misunderstanding of the syntax. Thank you very much for the clarity and tolerating my ignorance.