# Function with a for loop inside

I am trying to write a function `totalGoals` that will take in an array of goals (numbers) and return the total. I am really confused on how to make this work. Any help would be greatly appreciated.

What have you tried so far?

@nhcarrigan, it’s great that you know how to do this, but we try to guide people to be able to write code on their own rather than just giving them answers here. That helps people do this sort of thing on their own in the future.

function totalGoals(array) {
console.log(array);
for (let i = 0; i < array.length; i++) {
let array = [0, 1, 2]
}
}

Either way, I can’t get any of it to print the result I need. The goals are [0, 1, 2] and the total should be 3, but I can’t seem to figure out how to get that.

``````function totalGoals(array) {
console.log(array);
for (let i = 0; i < array.length; i++) {
let array = [0, 1, 2]
}
}
``````

You’ve got some good pieces here, but their order is a bit jumbled. You need to be able to take in any array, so let’s put the array on the outside:

``````// Function to sum array
function totalGoals(array) {
console.log(array);
for (let i = 0; i < array.length; i++) {

}
}

// Declare array
let array = [0, 1, 2];

// Use function
console.log(totalGoals(array));
``````

With this, you’re actually not too far off.

``````// Function to sum array
function totalGoals(array) {
console.log(array);

for (let i = 0; i < array.length; i++) {
// What code should go here to add up the elements into a total?
}
}

// Declare array
let array = [0, 1, 2];

// Use function
console.log(totalGoals(array));
``````

Maybe you can use the `for...of` loop to iterate through an array

This may be helpful

Sure, an `for... of` might work, but your current `for` loop will work fine if you add a way to sum up your array entries.

That’s the part that has me confused

Have you covered accessing array entries?

``````const myArray = [1, 4, 6];
console.log(myArray);
``````

You’ll want to use the loop to access each entry of the array and add it to a running total.

No I haven’t covered that yet

Try running

``````const myArray = [1, 4, 6];

console.log(myArray);
console.log(myArray);
console.log(myArray);
``````

If `i` goes from `0` to the end of the array, how could you get each element of the array?

I just tried that but it didn’t work

Just tried what? How?

I tried running the const myArray…

That code won’t add anything, there are no + signs. It should just print the three values in the array.

It did print the three values, I just don’t understand the code to add them together. I have been stuck on this for a few days.

Ok, so how can I change

``````const myArray = [1, 4, 6];

console.log(myArray);
console.log(myArray);
console.log(myArray);
``````

into a loop that prints the three values?

``````const myArray = [1, 4, 6];

for (let i = 0; i < array.length; i++) {
// What goes here?
}
``````

I honestly don’t know…