Member-only story
Incrementing — increasing values by one — is a ubiquitous operation in programming. Want to count things, generate IDs, or just add 1 more of something? Let’s tackle this basic JS concept by building our own custom increment function.
In a few simple steps, we’ll take a number as input, add 1 to it, and return the result. Ready for some quick, handy syntax? Let’s get started!
Defining Our Function
First, we initialize the function signature and input parameter:
function increment(num) {
}
By accepting num as input, we indicate that values can be passed here later when calling the function.
Adding One
Inside the body, we take that num value and add 1 to it:
function increment(num) {
var result = num + 1;
}
Using the += assignment operator is a common shortcut for incrementing values in place.
Returning the Result
Finally, we return the new result value out of the function:
function increment(num) {
var result = num + 1;
return…