0

I saw this in a codepen "http://codepen.io/jalabkhan/pen/bgNavG". I am confused about how the foreach loop works. Also what is the value of spark, i and array. I am new to programming so please try to make the answer as simple as possible. Thanks Everyone!!

  function draw() {
    ctx.fillStyle = 'rgba(0,0,0, 0.1)';
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);

    sparks.forEach(function (spark, i, array) {

      if (spark.opacity <= 0) {
        array.splice(i, 1);
      } else {
        drawSpark(spark);
      }
    });

    window.requestAnimationFrame(draw);
  }
4
  • spark is the current element on whip loop counter is, i is the index and array is the whole array sparks here Commented Jan 27, 2017 at 12:09
  • Please do basic research before asking. This isn't a tutorial site Commented Jan 27, 2017 at 12:18
  • So when the sparks obj is called in the foreach loop, the first value 'spark' is current element, from the multiple new elements in the obj, and 'i' is the index like "spark[0]", and the array is the whole Sparks obj. Did i miss something or am i still wrong. Commented Jan 27, 2017 at 12:29
  • And im sorry, i know this is not a tutorial site, but im really confused, and i would like an answer. Thanks for Taking your time to advise. Commented Jan 27, 2017 at 12:31

2 Answers 2

2

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

The forEach method of an array allows you to loop over its values via a callback function. In other words, each value in the array is passed to the callback function in turn, for processing.

forEach automatically forwards three arguments to the callback:

  • the value of the array item currently being processed
  • the numerical index of the array item currently being processed
  • the entire array being iterated over
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks alot mate!!
You're welcome. Please mark an answer correct if you deem it the answer to your question.
1

forEach iterates threw your array just like a for loop does, but it's more redable since you already have the value in your callback function

in your example:

function draw() {
    ctx.fillStyle = 'rgba(0,0,0, 0.1)';
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);

    sparks.forEach(function (spark, i, array) { 

/*spark is    your current value in the array (like sparks[i] in a for loop), i is 
you current index and array is sparks*/

      if (spark.opacity <= 0) {
        array.splice(i, 1);
      } else {
        drawSpark(spark);
      }
    });

    window.requestAnimationFrame(draw);
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.