JavaScript : Increment & Decrement Variable Values

Using Javascript, you might want to define a variable when a page is loaded and change the value of that specific variable throughout the period of the interaction of the user with the page. You can define a variable in the HEAD section of the page like this :

var number = 1;

Then, you might want to increment or decrement the value when a button or a link is clicked or another event is fired. I’ll show you an example, using a button to fire a custom function I’ll be showing you shortly. Here is a button in our page :

As you’ll notice, I put an onclick attribute inside the button tags and inserted a value which tells the page to fire a javascript function called change_number when the button is clicked. This function can either be defined in your HEAD section or in an externally referenced file. The first parameter passed to the function is simply a value I’m using so that I can utilize the same function for both incrementing and decrementing our variable. “inc” will represent incrementing the value of the variable and “dec” will indicate that the variable needs to be decremented. Below is our custom javascript function :

function change_number(way) {
    //check if we should increment or decrement
    if (way == "inc") {
        //two plus signs will increment our variable by one
    } else if (way == "dec") {
        //two minus signs will decrement our variable by one

So thats a simple function showing you how our global Javascript variable named number is being incremented or decremented when a button is clicked.