-1

I am new to javaScript and have been self learning by watching youtubers walk-through 'beginner friendly' projects but I'm having a problem wrapping my head around parameters and how they are defined in a function.

The project is a simple image corousel and theres a certain arrow function I can't quite follow:

const slideWidth = slides[0].getBoundingClientRect().width;


slides.forEach((slide, index) => { 
    slide.style.left = slideWidth * index + 'px';
});

So I understand the function is using the size of the slides to determine how far to move the images to the left but I don't understand how the function understands that 'index' means the array number because the function does not define this.

I've tested this code out and it works, I just really want to understand HOW it works. I know this is a simple concept but I am a true novice who is really trying to break into the world of JavaScript, any help is appreciated.

Liam
  • 27,717
  • 28
  • 128
  • 190
  • You're over thinking it, that's just how forEach works. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#syntax You don't need to know "how the function understands that 'index'". It's just how that function is defined. – Liam Oct 28 '22 at 17:04
  • Documentation, you need to read it for things you do not understand. – epascarello Oct 28 '22 at 17:25
  • Stackoverflow is not discussions. Please if the code works, there is not point using StackOverflow – surge10 Oct 28 '22 at 17:44
  • @surge10 No, Stack Overflow is not only for broken code. A question that asks for an explanation of working code is perfectly fine, if it wasn’t a duplicate. – Sebastian Simon Oct 28 '22 at 18:20

1 Answers1

0

I think the easiest way to explain how it works is with a simple dummy example.

The concept is called a callback:

function myForEach(callback) {
  const item = "something";
  const index = 3;
  const array = [10, 20, 30];

  // invoke the callback with three arguments passed through
  callback(item, index, array);
}

myForEach((slide, index) => {
  console.log(slide); // something (item)
  console.log(index); // 3 (index)
});

So the "real" forEach takes a callback function as an argument and iterates the array that the forEach is "attached" to, then invokes the callback for each iteration with three arguments passed through to the callback:

  1. the item from the current iteration of the array
  2. the index for the current iteration
  3. and the entire array

Hope it explains it just a little.

Bqardi
  • 682
  • 3
  • 10