1

I am trying to write a very simple script but do not understand why one syntax isn't working over the other.

The function is to simply increment any number by one.

This one does not work

function plusOne(x) {
  return x++;
}

but this one does.

function plusOne(x) {
  return x + 1;
}

What am I not understanding??

Cuong Vo
  • 249
  • 1
  • 6
  • 16
  • 2
    you need to use `return ++x;` – Pranav C Balan Mar 19 '19 at 18:40
  • 1
    https://hackernoon.com/javascript-back-to-basics-prefix-vs-postfix-8da5256223d2 – chevybow Mar 19 '19 at 18:41
  • 1
    https://stackoverflow.com/questions/1094872/is-there-a-difference-between-x-and-x-in-java – Pranav C Balan Mar 19 '19 at 18:41
  • Its called `unary +` operator – Fr0zenFyr Mar 19 '19 at 18:44
  • wow I had no clue there was a post and pre increment operation. Thanks all – Cuong Vo Mar 19 '19 at 18:44
  • 1
    @CuongVo: As a rule, you want to default to pre-increment, only using post-increment when you *want* the "return old value, increment variable" behavior. Aside from being somewhat more intuitive to increment and return the incremented value, in some language (e.g. C++) with some types (e.g. non-primitive types), there is a significant performance penalty for using post-increment (it has to copy the underlying object and return it after incrementing, rather than just modifying the underlying object in place and returning a reference to it). – ShadowRanger Mar 19 '19 at 18:52

1 Answers1

2

Increment (++)

If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing

You should use

function plusOne(x) {
  return ++x;
}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73