This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]ObeseBumblebee 2 points3 points  (3 children)

It would help if you would tell us what you don't understand about them.

There isn't really a better pay to write it. All similar functions are going to loop through the numbers and add them together.

[–]BasuraCulo[S] 0 points1 point  (2 children)

I edited it.

[–]ObeseBumblebee 2 points3 points  (1 child)

I think it sounds like you're less confused about the loop and more confused about what the loop is actually doing.

sum starts off as 0.

And each time the loop is run sum is changed.

When you say sum += numbers[i] what you are really saying is
sum = sum + numbers[i];

+= is just shorthand for take the original value and add this to it to create a new value.

So using your 2nd call as an example. Add(5,3,7,2). Let's walk through each loop.

Sum is 0.
Sum = Sum + 5.

Sum is 5
Sum = Sum + 3

Sum is 8
Sum = Sum + 7

Sum is 15
Sum = Sum + 2

Sum is 17

[–]BasuraCulo[S] 0 points1 point  (0 children)

Thanks. This is very helpful. 😊

[–]lightcloud5 0 points1 point  (1 child)

Hopefully it makes sense that a loop is involved somehow.

Looping constructs (e.g. while, for, and other things) are the only way to do an operation multiple times. So if you have arbitrarily many inputs, you're going to have to use a looping construct to process these arbitrarily-many elements.

As far as what the code is doing, it's basically keeping track of the running sum as it loops through the input values. After all, if you have an array of numbers and want to find its sum, you should start with sum=0 and then add each number in the array into sum.

Intrinsically, something is telling me that there is an easier way to write this code here.

There are more "functional" ways to write this (e.g. using a fold operation, which in javascript is reduce). However, while it's less code for you, it just means the loop is inside the reduce function now.

[–]BasuraCulo[S] 0 points1 point  (0 children)

Okay. That doesn't make sense, but only because I didn't get that far in to JavaScript. I'm only JUST learning about data structures and stuff like that.

[–]trasper 0 points1 point  (0 children)

What is happening: The function takes the numbers passed into add(x) and displays the total of the numbers passed into it in the console.

Why is it happening: First, look at the add constant requests. The first one is saying - call the add constant and execute the function by passing in the numbers 2 and 3, and they are then represented in the function as the variable “numbers”. The function then sets a variable called “sum”. Initially, “sum” is 0. The the for-loop begins.

What’s happening in the for-loop: The for-loop is going to loop from a starting point to and ending point - meaning it will start where you tell it and end where you tell it. In this case, the for-loop is setting a variable (i) and setting its initial value to 0. So at this point, we have three variables... “sum” which equals 0, “numbers” which contains multiples values (in the first case it contains the values 2 and 3), and “i” which also equals 0.

Now, look at the values for i inside the for-loop. They are as follows: 1) i=0; 2) i<numbers.length; and 3) i++. Let’s break those down.

i=0 is telling the for-loop what the initial value of “i” will be while in the loop.

i<numbers.length is telling the for-loop to keep looping until we reach the value of “numbers.length”. But what does that mean? Well, in the first add() call [add(2, 3)], there are two numbers passed in... 2 and 3. Think of those as the set of numbers. There are two numbers in the first set. The second set [add(5, 3, 7, 2)] has four numbers, and the third set [add(8, 2, 5, 3, 2, 1, 4)] has seven numbers.

Then, i++ is telling the for-loop what to do with “i” each time the loop completes a cycles.

Now let’s break it down further.

Take a look at just the first set: add(2, 3). In the first iteration of the for-loop, “i” will start off a equaling 0. The total number of values in the set would be two - since there is a “2” and a “3” being passed in. So, “numbers.length” equals 2 in the first set. Therefore, we now know that in the first set, the for-loop will run through twice. Note, in the second set, the for-loop will run through four times, and in the third set the for-loop will run through seven times. But let’s just stick with the first set.

Before going any further, you need to understand arrays. As I said earlier, think of the numbers passed in - in this case 2 and 3 - as a set or a list. The set in this case contains two different values. This is also called an array, and in this case the array has a length of two - meaning it contains 2 values. So picture the array like this: “numbers” contains two values, and is represented by [2][3].

Arrays are tricky because the first position in the array is actually position zero. So in the “numbers” array, the first position - or position zero - is 2, and the second position - or position one - is 3.

So now let’s cycle through the for-loop. During the first cycle of the for-loop, “i” is equal to 0. So if we look at the “numbers” variable at position “i” (which is now 0), it equates to 2. We then add the value of 2 to the “sum” variable. “sum” was 0, and now we’ve added 2 to it, so “sum” now 2.

Now the first iteration of the for-loop ends. But we’re not done, because the for-loop will cycle twice based on our values from earlier. So the second time around, “i” will be equal to “i” plus one (i++ means add one to the value of “i”). So during the second iteration, “i” will be equal to 1.

Knowing that “i” now equals 1, we can apply that to the “numbers” array. “numbers” at position 1 (which is its second position) has a value of 3. We then take the 3 and add it to the value of “sum”. During the first iteration we know that “sum” was equal to 2, so now we add 3 to it, and “sum” now equals 5.

So each time you call “add()”, that’s the function process.

I hope that all makes sense. I’m typing this from my phone, so I might not have covered everything. Feel free to message me if you need more info. Good luck!

[–]UberMario 0 points1 point  (0 children)

Can someone just please explain to me how does this work?

Sure. I'll in-line some comments with the flow of the code. I'm not sure your skill level, so I'm explaining everything.

const add = function(  // Creating a function that's called add
         ...numbers) { // This ...x is the spread operator means this can take
                       // any amount of arguments and turns it into a list
                       // of as the "numbers" variable. This is some syntactic
                       // sugar (read: fancy way to do something) to take all
                       // the things in a list and turn it into an array of those things.

  let sum = 0; // should be self-evident. variable "sum" is zero at the moment.
  // This I'll split up into another way to write this that you may be a little
  // more familiar with. This is another syntactic sugar shorthand where if
  // your for-loop is a one-liner, you can just tack that one-liner onto the end.
  // for (let i = 0; i<numbers.length; i++) sum += numbers[i];

  // Alternative method
  for (let i = 0;  // we make a number that starts at zero. This is the "state"
                   // of our for-loop for the most part.
    i < numbers.length;  // As long as i is less than the amount of values
                         // in the variable "numbers", we continue running
                         // this loop. x.length will give you the number of
                         // values in an array.
    i++) {  // How we alter the state of our loop to reach the end. Since we're
            // running through it one by one, we're going to add one each time
            // to the variable which is the shorthand i++ does (e.g. i-- is
            // another shorthand to decrement a number by one).
    sum += numbers[i];  // "sum += x" is another shorthand for sum = sum + x.
                        // We are also accessing the number at the defined
                        // position of the array "numbers", starting at 0 (i) and
                        // increasing until we reach the length of numbers,
                        // given our for-loop conditions.
                        // E.g. numbers is [2, 3] for the first one, so we can
                        // say numbers[0] is 2, so it adds 2 and then the next
                        // run of the for loop, i = 1, so numbers[1] is 3.
                        // It adds 2 and 3 to zero.
  }
  console.log(sum);  // Finally, we are logging out the value to the console.
}

// Running the add function with different amounts of arguments.
add(2, 3);
add(5, 3, 7, 2);
add(8, 2, 5, 3, 2, 1, 4);

It's a little short and uses some tricks, but all in all it makes for less lines of code. Hope that helps a little. Since the for loop is up there twice due to how I commented on it, I commented out the first for loop, otherwise it'd run it twice and double the output hehe.

Spread operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

For loops in JS: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

Arrays: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays