Search code examples
javascriptjquerymathparentheses

Jquery/Javascript Math: Why are these two 1 line math problems not giving the same answer?


Shouldn't these two math problems give the same answer? Brackets/parenthesis are done first, right? so it should add them all, then divide it by 2, then subtract 10. The second answer below is the one giving me the correct value that I need, the other one gives a value that's a long ways off.

    var pleft = $(this).offset().left + ($(this).width() /2) - ($("#question-wrapper").width() / 2) - 10;

    var pleft = (($(this).offset().left + $(this).width() + $("#question-wrapper").width()) / 2) - 10;

Solution

  • var x = $(this).offset().left;
    var y = $(this).width();
    var z = $("#question-wrapper");
    
    var pleft = x + (y/2) - (z/2) - 10
    
    var pleft = ((x + y + z) / 2) - 10
    

    Hopefully that helps clear up the difference.