Chichi Ukomadu Chichi Ukomadu - 1 year ago 139
Javascript Question

Why is my Javascript increment operator (++) not working properly in my addOne function

Please can someone explain to me why my addOne function doesn't work with the increment operator (++). Please see my code below.

// addOne Function

function addOne(num){
return num + 1

log(addOne(6)) => 7

// same function with ++ operator

function addOne(num){
return num++

log(addOne(6)) => 6

// Question - why am I getting 6 instead of 7 when I use ++ operator?

Answer Source

There are two increment operators: prefix and postfix.

The postfix operator increments the variable after it is evaluated. For example, the following code produces 11, because it adds 5 and 6:

var a = 5;
(a++) + (a++)

The prefix operator increments the variable before it is evaluated. Sounds like that is what you want. The following code produces 13, because it adds 6 and 7:

var a = 5;
(++a) + (++a)

So your code should be:

function addOne(num) {
  return ++num;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download