yes this is really complicated I would recommend watching some youtube videos nested loops.

But I’ll try my best with words. remember when you count arrays they start/ index at 0.

Here is the question. You have 3 barrels of apples. Each barrel has several bags of apples inside the barrels. How many apples do we have in total?

Let’s write this as an array

## howManyApples([[1, 5,], [1, 8], [1, 4, 10]]) ; <------the[ ] are barrels and the numbers are bags of apples.

**function** howManyApples(*countApples*){

**var** apples = 0; <----- If multiplying set apples to 1 because 0 *0 is 0

**for** (var barrels=0; barrels < countApples.length; barrels++) {

**for** (var bags=0; bags < countApples[barrels].length; bags++) {

apples = apples + countApples[barrels][bags]; <—JS first look in barrels then look in bags.

}}

**return** apples;

}

howManyApples([[1, 2,], [1, 8], [1, 4, 10]]) ;

So let’s go through the loops as they count from [0], [1], [2] for the barrels, remember JS can only do 1 thing at a time.

remember apple is = 0 and every time this loops the value of apple will be updated to a new number.

apples = apples + countApples[barrels][bags]; <------ on the 1st loop we get the first barrel[0]

then bags[0] looks in the barrel and sees 1 bag. <-----apples = 0 +1 = 1

apples = apples + countApples[barrels][bags]; <------ on the 2nd loop we still get the first barrel[0] then bags[1] looks in the barrel and sees 2 bags. <----apples = 1 + 2 = 3

**the length of the bags counter is = countApples[barrels].length…so this is the end of barrel[0].**

apples = apples + countApples[barrels][bags]; <------ on the 3rd loop we get barrel[1] then bags[0] looks in the barrel and sees 1 bag. <----apples = 3 +1 = 4

apples = apples + countApples[barrels][bags]; <------ on the 4rth loop we still get barrel[1] then bags[1] looks in the barrel and sees 8 bags. <----apples = 4 + 8 = 12

**end of loop barrel[1]**

apples = apples + countApples[barrels][bags]; <------ on the 5th loop we get barrel[2] then bags[0] looks in the barrel and sees 1 bag. <----apples = 12 + 1 = 13

apples = apples + countApples[barrels][bags]; <------ on the 6th loop we still get barrel[2] then bags[1] looks in the barrel and sees 4 bags of apples. <----apples = 13 +4 = 16

apples = apples + countApples[barrels][bags]; <------ on the 7thth loop we still get barrel[2] then bags[2] looks in the barrel and sees 10 bags of apples. <----apples = 16 + 10 = 26

**end of loop barrel[3]**

**returns** apples.

and then if you wanted

alert(“you have” + apples + “apples!”);