-2

Given the following code:

var x = 0;

function decrement(num) {
  return num--;
}

var y = decrement(x);
console.log(y);    // 0

Versus the following:

var x = 0;

function decrement(num) {
  return num -= 1;    // this is the only difference between the functions
}

var y = decrement(x);
console.log(y);    // 0

Why does y-- return 0 from the function while y -= 1 returns -1?

dtburgess
  • 551
  • 4
  • 16
  • 1
    I'm curious as to why you didn't also run `--y`; but you'll probably find the answer in this question: http://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript – David says reinstate Monica Feb 13 '17 at 00:59
  • @DavidThomas thanks. did not realize that you could not easily search for single characters on SO. Would explain why I could not find an answer to this question at first. – dtburgess Feb 13 '17 at 01:08
  • 2
    Rather than using Stackoverflow as a reference, trying using an actual reference as a reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators – Jan Feb 13 '17 at 01:11

2 Answers2

1

UPDATE: This is a duplicate question, answered here: What does this symbol mean in JavaScript?

I couldn't find an answer to this question on SO, and managed to answer my question while researching it and composing the question.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement_(--)

The code example is using the postfix incrementing operator. A postfix operator will first return the current value and then increment it.

var x = 1;
x++;   // returns 1, x === 2    

This is in contrast to the prefix incrementing operator, which will first increment the value and then return the incremented value.

var y = 1;
--y    // returns 0, y === 0

Regarding the += and -= assignment operators: these operators also increment the value and then return the incremented value.

Community
  • 1
  • 1
dtburgess
  • 551
  • 4
  • 16
0

Remember prefix and postfix. When I do return num-- I return the value of num only, detuction comes after I return the value.

In short , operator precendence

Kaynn
  • 3,335
  • 2
  • 17
  • 23