As much as I want to start using JavaScript right away, and create applications, I know that I won’t be able to fully grasp the language unless I understand the fundamentals. Consequently, I’ve been following the chapters from https://javascript.info which has been a great source so far.
For my own reference, I thought I would write about interesting tidbits I’m learning, or topics I’m struggling with along the way. I hope this will also be of some use to others who are leaning JavaScript as well.
This numerical operation increases or decreases a variable by 1. It’s important to remember that this can only be applied to variables, and applying this operation to numerical values will return an error.
Increment ++: Increases variable by 1
Decrement — — : Decreases variable by 1
The ++ or — — can be applied both before and after the variable. This is where it gets a bit tricky.
SyntaxPostfix Form: counter++
Prefix Form: ++counter
Although both forms increase the variable by 1, there is a difference. The Postfix Form returns the original value of the variable, before the increment/decrement The Prefix Form returns the value after the increment/decrement. This difference can be seen if we are using the returned value of the increment/decrement.
ExamplePrefix
let counter = 2;alert(++counter); // 3 incremented value has been returned
Postfix
let counter = 2;alert(counter++); // 2 Returns the original value prior to the increment
If we are using the value of the increment/decrement at a later point in time however, there is no difference between the forms.
ExamplePrefix
let counter = 2;++counter; // _3 The incremented value_alert(counter); // 3 Incremented value has been returned
Postfix
let counter = 2;counter++; // _2 The original value_alert(counter); // 3 Value has now been incremented and returns the new value
It took me a bit of time to wrap my head around this so I hope this was a clear enough explanation.
If you liked this article, give it a few claps. I would greatly appreciate it!