Math consecutive in JavaScript

Math consecutive in JavaScript
0
#1

Hello,
could somebody explain such expression
var a = (1.5-1)*2 correct answer is 8
how does this expression calculate?
please.

0 Likes

#2

It evaluates to 1. You evaluate first those inside the parentheses. 1.5 - 1 equals 0.5, then you multiply it by 2, so you have 1.

0 Likes

#3

first this code evaluates the bracket in this case it is 1.5-1.0 = 0.5, then it is multiplied by 2 giving the answer 1 not 8.

0 Likes

#4

yes and I think so tha correct answer is 1 but I have met such quize on faceebook
and all answers was that correct is 8!

0 Likes

#5

do not trust the facebook’s quiz posts:smiley::smiley:

0 Likes

#6

Thanks, now I know that such quiz is rubbish :slight_smile:

0 Likes

#7

Is it possible, that you have a typo in your example?

var a = (1,5 - 1) * 2 will give you 8

EDIT.
Found a nice explanation: http://www.i-programmer.info/programming/javascript/6524-the-confusing-comma-in-javascript.html

General info on operator precedence: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

0 Likes

#8

Yes :slight_smile:
I have seen again the quiz
and question was var a = (1,5-1)*2;
not var a =(1.5-1)*2;
correct answer 8
:slight_smile:

0 Likes