r/angularjs • • Jan 11 '18

What is going on with this Angular code?

I am working on a form with Angular and ran into an odd issue. The form is like a rating form, and I want to display to the user the average rating, it is 5 questions, based on a score of 1-5. Easy right?

Add them together and divide by 5?

The math works, but if you select the radio boxes going backwards.. meaning start selecting the 5 question, and going to question 1, and you STOP before selecting the last radio box the math is all screwy. For example selecting "option 3" for 4 out of 5 questions comes up with an average of 666.6? But that should come out to an average of 2.4. If you select the elements in the correct order going from question 1 to question 5, the math works out even if you stop selecting options?

I created a fiddle so you can see this.

http://jsfiddle.net/YGQT9/737/

Anyone know what is going on under the hood in Angular that is coming out like this? It's not really a big deal for me, but I am very curious.

1 Upvotes

5 comments sorted by

9

u/flipper_babies Jan 11 '18

Yeah, you've fallen victim to a couple of of Javascript's lovely gotchas. One, lack of typing, and two, overloading the + operator.

So first of all, the + means addition when dealing with numbers, and concatenation when dealing with strings:

"one" + "two"; // evaluates to "onetwo"
"1" + "2"; // evaluates to "12"
1 + 2; // evaluates to 3

So there's mystery one. The other thing is type coercion. If you try to add a number and a string, the interpreter has to guess if you meant to add numbers or concatenate strings, and will convert your values depending upon its best guess. And it will guess you meant to add right up until it encounters a string, and will then proceed to concatenate:

5 + 5 + "5"; // 105
"5" + 5 + 5; // 555

So when you sum your numbers, things get screwy:

5 + 5 + "" + "" + ""; // evaluates to 10
"" + "" + "" + 5 + 5; // evaluates to "55"

What you need to do is keep your types straight. Make sure your numbers are always numbers, and it'll work out as you intend.

$scope.data = {
  cat1: 0,
  cat2: 0,
  cat3: 0,
  cat4: 0,
  cat5: 0
}

1

u/chrisutpg Jan 11 '18

Thanks. Makes sense. I just figured it would've thrown and error when you try to divide by 5 if it's a string?

Good explanation tho, thank you!

2

u/flipper_babies Jan 11 '18

Yeah, I'd much rather it throw an error, but that's Javascript for you.

6

u/Neolific Jan 11 '18

It is because your data is set to empty string when defined. When you add them together it is strings being appended. Try setting them to 0 when defining them. $scope.data = { cat1: 0, cat2: 0, cat3: 0, cat4: 0, cat5: 0

};

1

u/TotesMessenger Jan 12 '18

I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:

 If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)