snippetjavascriptTip
What is the difference between prefix and postfix operators?
Viewed 0 times
postfixjavascriptwhatprefixoperatorsandbetweendifferencethe
Problem
The increment operator (
If used prefix, the value is incremented/decremented, and the value of the expression is the updated value.
If used postfix, the value is incremented/decremented, and the value of the expression is the original value.
++) adds 1 to its operand and returns a value. Similarly, the decrement operator (--) subtracts 1 from its operand and returns a value. Both of these operators can be used either prefix (++i, --i) or postfix (i++, i--).If used prefix, the value is incremented/decremented, and the value of the expression is the updated value.
If used postfix, the value is incremented/decremented, and the value of the expression is the original value.
Solution
let i = 0; // i = 0
let j = ++i; // i = 1, j = 1
let k = --i; // i = 0, k = 0If used postfix, the value is incremented/decremented, and the value of the expression is the original value.
Code Snippets
let i = 0; // i = 0
let j = ++i; // i = 1, j = 1
let k = --i; // i = 0, k = 0let i = 0; // i = 0
let j = i++; // i = 1, j = 0
let k = i--; // i = 0, k = 1Context
From 30-seconds-of-code: prefix-postfix-operators
Revisions (0)
No revisions yet.