What is the order of precedence for modulus in Javascript?

后端 未结 3 531
栀梦
栀梦 2021-01-29 10:55

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

相关标签:
3条回答
  • 2021-01-29 11:28

    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
    
    0 讨论(0)
  • 2021-01-29 11:32

    Basically you going left to right but you're doing plus first, then multiply, then divide, and the remainder stuff is divide. So

     var num = 15 % 2 + 6 * 4;
    

    is basically 15 % 2 = 1

    0 讨论(0)
  • 2021-01-29 11:36

    Modulo should have the same precedence as division, multiplication, and exponents. See here

    0 讨论(0)
提交回复
热议问题