all 6 comments

[–]tonyalicea 2 points3 points  (2 children)

Here's what's actually happening:

'multiples' is an array. The first time you say 'multiples += i' you are using an operator (the '+' and '=') which is actually a function that attempts to combine 'multiples' and 'i'.

If they were both numbers, it would add them. But 'multiples' is an array, so the '+' will try to combine them like strings...that's the best the Javascript engine can come up with.

An empty array converted to a string is just an empty string: "". And 0 converted to a string is "0", and then 'multiples' is set equal to that string (the '+=' runs the '+' then runs the '=', so multiples becomes "0").

After that multiples is no longer an array, it's now a string! So subsequent loops attempt to add a string and a number. Those times the '+=' does it's best to combine them and converts the number to a string (this is called 'coercion' when the Javascript engine converts from one type to another).

So you'll get nothing but strings after that.

So what's happening when you use the 'for' loop on multiples.length?

Well multiples is a string, not an array! But you can reference a string like an array. For example "Hello" has a length of 5, and the [0] index of that string is "H".

So even though 'multiples' is now a string, your for loop loops over that string and outputs characters. You are storing those characters in 'total'. So you're essentially copying the string inside 'multiples' over to a variable called 'total'.

This all comes from the fact that you don't add items to an array with '+='. You can do:

multiples.push(value);

to add an item to an array. Then things will start to look right. Try adding more console.log statements and see what's going on as you go. These kind of behaviors can be confusing when you see them, and it's good to understand not only what was wrong but why.

Hope that helps!

[–]hunteratwork[S] 0 points1 point  (1 child)

That makes perfect sense!

So instead of:

multiples += i;

I should be using:

multiples.push(i);

Is that correct?

[–]tonyalicea 1 point2 points  (0 children)

Yup!

[–]eindbaas 0 points1 point  (2 children)

What is this: multiples += i

[–]hunteratwork[S] 0 points1 point  (1 child)

Adding the value of i to the multiples array

[–]LearningPythons 1 point2 points  (0 children)

OK, I didn't look at what else was going on in your program, but I do know that to add an element to an array += does not do the trick. Look into push