Iterating over arrays - For

We can iterate over arrays using the for loop. The syntax is:

Loading Code . . .

As the loop runs, the variable i will take on the values 0, 1, 2, etc., up to but not including array.length. Inside the loop body, we can refer to the current array element using array[i].

In other words, the above loop will execute the code between the curly braces once for each element in the array, with array[i] set to the current element in each iteration.

Example

Loading Code . . .

This will print:

Loading Code . . .

Challenge Time!

Write a function called sumArray that takes an array of numbers as an argument and returns the sum of all the numbers in the array.

Example:

If we call sumArray([1, 2, 3]), the function should return 6, because 1 + 2 + 3 = 6.

Loading...

© 2024 - ®Mewters