Basic Javascript Syntax

Functions

A function is a named group of JavaScript statements that you can declare once, near the top of your script, and call over and over again. Adding a reusable function to your script — instead of adding several slightly different versions of the same code — cuts down on the amount of typing that you need to do, as well as the number of potential bugs in your script.

Declaring a function

Here’s the syntax for a function declaration:

function name([parameter] [, parameter] [..., parameter]) {
    statements
    return value
}

And here’s an example:

function calculateTotal(numberOrdered, itemPrice) {
    var totalPrice = (numberOrdered * itemPrice) + salesTax
    return totalPrice
}

This code snippet declares a calculateTotal function that accepts two arguments: numberOrdered and itemPrice. The function uses these two arguments (plus an additional variable called salesTax) to calculate the totalPrice variable, which it then returns to the JavaScript code that originally called it.

Your function can take as many arguments as you want it to (including none at all), separated by commas. You generally refer to these argument values in the body of the function (otherwise, why bother to use them at all?), so be sure to name them something meaningful.

Calling a function

After you declare a function, which I describe in the preceding section, you can call that function. You call a function by specifying the name of the function, followed by an open parenthesis, comma-delimited parameters, and a closing parenthesis. For example:

alert(“Total purchases come to “ + calculateTotal(10, 19.95))

Notice that you can embed a function call within another expression. In this example, calculateTotal(10, 19.95) is actually part of the expression being sent to the alert() method.

Returning a value from a function

You use the return statement to return a value from a function. To understand why you might want to return a value from a function, imagine yourself asking a friend to look up some information for you. If your friend went ahead and did the research but neglected to pass it along to you, you’d be pretty disappointed. Well, in this case, you’re just like a bit of JavaScript code calling a function, and your friend is the function that you’re calling. Basically, no matter how many useful things a function does, if it doesn’t return some sort of result to the piece of code that needs it, it hasn’t finished its job.

The syntax for the return keyword is simple:

return expression

Here’s how it looks in action:

function calculateTotal(numberOrdered, itemPrice) {
    var totalPrice = (numberOrdered * itemPrice) + salesTax
    return totalPrice
} // Now the function is defined, so it can be called

alert(“Total purchases come to “ + calculateTotal(10, 19.95))

 

Post A Comment

Anti-Spam Quiz: