Creating JavaScript Functions

In JavaScript, there are multiple ways to create functions.

Method #1

We've already seen this way:

function DoMyTaxes(income) {
    return income * .15;
}

This way is fine, but it creates a global variable, one that every function can access. Global variables are great when we want to share them with everything else, but sometimes it's nice to not share them. Not sharing helps to avoid conflicts.

Method #2

We can use the var keyword to create a function:

var DoMyTaxes = function(income) {
    return income * .15;
};

If this bit of code is not in a function, a global variable is created (the same as in Method #1).

But, if we insert it into a function:

function DoMyTaxes(income) {
    var calculateTaxes = function(income) {
        return income * .15;
    };
    return calculateTaxes(income);
}

Then the calculateTaxes function is local (visible only inside the DoMyTaxes function).

Method #3

You can pass a function as an argument to another function:

function RunMyFunction(myfunction) {
    myfunction();
}

RunMyFunction(function() { alert('Bananas!'); })

The result:

a web page showing an alert dialog

Comments

Leave a comment

What color are brown eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.