JavaScript — Back to Basics: Prefix vs. Postfix
Himashi Hettege Dona
Posted on April 15, 2018
Wish me luck, I’m diving into JavaScript!
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.
Increment/Decrement
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.
Syntax
Postfix 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.
Example
Prefix
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.
Example
Prefix
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 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, click the heart button. I would greatly appreciate it!
Posted on April 15, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.