Javascript Question about

Hey guys. I can’t get how these being connected?
In this for loop

for(var i = 0; i < names.length; i++) {
var currentNames = names[i];
  console.log(currentNames);
}

What I don’t get is this
var currentNames = names[i];
names[i] <- what s going on here?

Hey,

names is an array. And names[ i ] provide the ith value of the array. let say names = [1,2,3], so here 3 elements are there in the array. and when we write names[ 0 ], it will return 1 (index start from 0).

Happy to get the feedback :slightly_smiling_face:

1 Like

But still don’t get why to put i inside an array which already has value?
I don’t understand why it works and how it works. Tutorials just use it or explain like you you are a pro coder.

I feel like coding isn’t for me. I can’t get 1 line of code about a week now.
Thanks for your explanation tho.

// Here I declared an array. it is storing 3 names.
let names = ["john", "jenny", "mike"];

// values in arrays are stored in indices. so the first value is at index 0, second value is at index 1, third value at index 2 and so on…
// So, if I want to get the second item from the names array i.e, “jenny”,
then I need to do something like this…

console.log(names[1]);
// If I want to get the Third name in the array I will do
console.log(names[2]);

// So in your code
for(var i = 0; i < names.length; i++) { var currentNames = names[i]; console.log(currentNames); }
value of i increases as it loops,
it starts at 0, then increments to 1 then 2 and so on as long as it is smaller than the names.length
So, on the first round , i is 0, which means
var currentNames = names[i];
is similar to
var currentNames = names[0];

as the value of i increases,
names[i] becomes names[1] then names[2] and so on…

1 Like

so instead of the index array it shows the letters or the names in the arrays?

It returns the names in the array.
I’ll suggest read more about Arrays.
Like what is it, why to use it, how it works.
Maybe watch some videos about it on YouTube

1 Like

I know what an array is and right now learning the DOM but this particular problem was hard to grasp. I was gonna quit actually.
The only thing I did not get is
names[i] using a variable inside and array as indexing. I have never seen such a confusing peace of code. But thanks for your help.

1 Like