0

var x = 5;
var y = -1;
z = x++ + ++y / 2;
console.log(z);

Why the result is 5 and not 3.5? I start learning like one week ago so I'am a begginer

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 1
    Because of order of operations. And `0 / 5 = 0` – VLAZ Apr 28 '20 at 21:56
  • 2
    The code you show should not have any result at all, since it's just a comment. Please take some time to read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please learn how to create a [mcve]. – Some programmer dude Apr 28 '20 at 21:57
  • I think this post could be helpful to read https://stackoverflow.com/questions/7911776/what-is-x-after-x-x. – darclander Apr 28 '20 at 21:59
  • 2
    As for your problem, please do some research about *operator precedence*. Or at the very least, think back to the basic arithmetic you learned in school. What happens first: Addition or division? – Some programmer dude Apr 28 '20 at 21:59
  • maybe [learning math](https://www.mathsisfun.com/operation-order-pemdas.html) before jump to code? not necessary, but helps a whol'lot learn about PEMDAS, all math is ruled by it ✌ – balexandre Apr 28 '20 at 22:00

3 Answers3

2

initial x=5 y=-1

z = (x++) + (++y/2)

z = 5 + (0/2)

z = 5

Jackson
  • 1,213
  • 1
  • 4
  • 14
1

Division operator runs after addition operator, so your operation evaluates to:

z = (x++) + ((++y) / 2);

Hence, 5 + (0 / 2) = 5 + 0 = 5.

Robo Robok
  • 21,132
  • 17
  • 68
  • 126
1

I don't know where you would get 3.5, but as for the reason for the answer being 5 :

The post-increment operator (n++) returns the value and then increments. So, in your expression x++ is 5 but after your expression runs the value of x is 6.

The pre-increment operator (++n) increments the value then returns it. So, in your expression ++y = 0.

From there it is just basic arithmetic.

Crowcoder
  • 11,250
  • 3
  • 36
  • 45