Here, In the above code block, we're doing a++ means Post-Increment which states Set and then Increment. So, First b is set to 10 which is a 's original value and then a will be incremented by 1.
The opposite is Pre-Increment which states Increment and then Set.
I think the issue is that postfix increment is often taught and therefore used as a statement rather than an expression - therefore the fact that it returns a value and the question of which value it returns rarely comes up.
In fact in 1996 Scott Meyers in More Effective C++ noted:
Item 6: Distinguish between postfix and prefix forms of increment and decrement operators
...
If youβre the kind who worries about efficiency, you probably broke into a sweat when you first saw the postfix increment function. That function has to create a temporary object for its return value (see Item 19)
and in 2008 in JavaScript: The Good Parts Douglas Crockford observes:
In my own practice, I observed that when I used ++ and --, my code tended to be too tight, too tricky, too cryptic. So, as a matter of discipline, I donβt use them any more. I think that as a result, my coding style has become cleaner.
So it's kind of surprising that the canonical for loop is given as
In programming,
++
and--
are Increment and Decrement Operators.Say,
Here, In the above code block, we're doing
a++
means Post-Increment which states Set and then Increment. So, Firstb
is set to10
which isa
's original value and thena
will be incremented by1
.The opposite is Pre-Increment which states Increment and then Set.
Hope this code block makes sense.
When you use in if-block,
say,
"Hello" will not be printed since num is zero which is considered as false value.
If you want "Hello", you can use Pre-Increment.
"Hello" will be printed in the console.
Falsey values in js are,
0
,false
,""
,null
,undefined
,NaN
Hope it helps π
Hold up! Not in programming, but in Javascript and some other languages. Several languages use ++ to concatenate.
Thanks. π
Thanks a lot! That was really helpful!
I think the issue is that postfix increment is often taught and therefore used as a statement rather than an expression - therefore the fact that it returns a value and the question of which value it returns rarely comes up.
In fact in 1996 Scott Meyers in More Effective C++ noted:
and in 2008 in JavaScript: The Good Parts Douglas Crockford observes:
So it's kind of surprising that the canonical for loop is given as
Given that the old value returned isn't used it would make more sense to use the prefix increment:
though I hope that JavaScript engines optimize the unused return value out in any case.
Douglas Crockford's JSLint bans increment operators outright:
favouring instead:
... so there is an ESLint and TSLint rule for that.