Home>

Thanks for your reply.
I stumbled upon a JavaScript variable, so please let me know.

Contents of question

In the answer code, const = character (s) is defined at the beginning, but in the for statement,
Why is it redefined to another constant character?

In my code, I don't redefine it, I use the character (s) I defined first,
The output result is the same as the answer.

If anyone knows about it, please let me know.

Answer code
code
const characters = [
  {name: "Ninja Wanko", age: 14},
  {name: "Sheep Sennin", age: 100},
  {name: "Baby dog", age: 5},
];;

for (let i = 0;i<characters.length;i ++) {
  console.log ("--------------------");
  const character = characters [i];
  console.log (`name is ${character.name}`);
  console.log (`${character.age} years old`);
}
My code
const characters = [
  {name: "Ninja Wanko", age: 14},
  {name: "Sheep Sennin", age: 100},
  {name: "Baby dog", age: 5},
];;

for (let i = 0;i<characters.length;i ++) {
  console.log ("------------------------------");
  console.log (`name is ${characters [i] .name}`);
  console.log (`${characters [i] .age} years old`);


}
My thoughts

After determining the variable i, if you embed character (s) in the sentence as it is,
Since it is necessary to write up to the specification of the index number, by redefining it as character
I think this is because the constants to be embedded can be refreshed.

  • Answer # 1

    I'm just (probably) defining variables for reuse
    It's easy to interpret logically, isn't it?
    Of course, the one presented by the questioner is fine.

  • Answer # 2

    It defines another variable and assigns it there
    Well, it's just the creator's taste

  • Answer # 3

    Why is it redefined to another constant character?

    There are various reasons,
    Is it possible to reduce the amount of description and emphasize object-oriented writing?
    (To reduce the number of parts that need to be corrected when making corrections)

    I don't think you can feel much benefit in a situation like this one,
    As the amount of code increases, it becomes a really useful way of writing.