Search code examples
javascriptoperator-precedencemodulus

What is the order of precedence for modulus in Javascript?


If I have the following code

var num = 15 % 2 + 6 * 4;

for example... I'd like to know what the output will be, specifically I would like to know the order of precedence for modulus (the operation executed by the % symbol). Will the modulus be performed before or after the addition and multiplication operations?

Edit: I have already looked at the article people are linking me to

MDN Operator Precedence

And had done so before asking the question, but unfortunately it didn't contain enough information to completely answer my question, hence my asking here. Just to save people the effort of linking again.

Update: Looking into associativity as indications from discussion in the comments beneath one proposed answer are that the question is associated with associativity (if you'll pardon the accidental pun).

Update: Syntax edit (^_^?)


Solution

  • Technically it's the remainder operator (more mathematical minds than mine say modulus would handle sign differences differently), and it has the same precedence and associativity as multiplication and division.

    So

    var num = 15 % 2 + 6 * 4;
    

    is

    var num = (15 % 2) + (6 * 4);
    

    MDN has a handy article on operator precedence and associativity.


    Re your comment on the question:

    ...I get the num variable value of 25 with the example code, yet var num = 3 * 15 % 2 + 6 * 4; also results in a num variable which a console.log shows as also bearing the value of 25...

    That's because both 15 % 2 + 6 * 4 and 3 * 15 % 2 + 6 * 4 are 25. Let's break it down:

    Your first example: 15 % 2 + 6 * 4

    15 % 2 + 6 * 4
    1      + 6 * 4
    1      + 24
    25
    

    Your second example: 3 * 15 % 2 + 6 * 4

    3 * 15 % 2 + 6 * 4
    45     % 2 + 6 * 4
    1          + 6 * 4
    1          + 24
    25