For example this:
var a = 123;
var b = a++;
now a
contains 124
and b
contains 123
I understand that b is taking the value of a and then a is being incremented. However, I don't understand why this is so. The principal reason for why the creators of JavaScript would want this. What is the advantage to this other than confusing newbies?
1 : the amount or degree by which something changes especially : the amount of positive or negative change in the value of one or more of a set of variables. 2a : one of a series of regular consecutive additions. b : a minute increase in quantity. c : something gained or added.
1. The process of increasing or decreasing a numeric value by another value. For example, incrementing 2 to 10 by the number 2 would be 2, 4, 6, 8, 10. 2.
An increment usually represents a portion of what the employee earns per year. Employers use increments to increase or decrease base salaries or to award bonuses. Employees use them as a benchmark to either negotiate a pay increase or a starting salary with a new employer.
To increment a variable means to increase it by the same amount at each change. For example, your coder may increment a scoring variable by +2 each time a basketball goal is made. Decreasing a variable in this way is known as decrementing the variable value.
That's why it's called the "post-incrementing operator". Essentially, everything is an expression which results in a value. a + 1
is an expression which results in the value 124. If you assign this to b
with b = a + 1
, b
has the value of 124. If you do not assign the result to anything, a + 1
will still result in the value 124, it will just be thrown away immediately since you're not "catching" it anywhere.
BTW, even b = a + 1
is an expression which returns 124. The resulting value of an assignment expression is the assigned value. That's why c = b = a + 1
works as you'd expect.
Anyway, the special thing about an expression with ++
and --
is that in addition to returning a value, the ++
operator modifies the variable directly. So what happens when you do b = a++
is, the expression a++
returns the value 123 and increments a
. The post incrementor first returns the value, then increments, while the pre incrementor ++a
first increments, then returns the value. If you just wrote a++
by itself without assignment, you won't notice the difference. That's how a++
is usually used, as short-hand for a = a + 1
.
This is pretty standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With