Functions

Now things get a little more interesting. Functions allow you to create discrete bits of reusable code, which you can call at any given time. These will make up the bulk of what you write in JavaScript.

Creating a function is easy. Here’s the pseudocode for making one:

function functionName(arguments ){
       statements;
    }

The function keyword designates the block as a function, and the arguments can be either a single variable or a comma-separated list of variables. Let’s make a basic one and then put it to use:

    function addThese( a, b ){
      var combination = a + b;
      return combination;
    }
    var my_var = addThese( 2, 10 );          // 12
    var my_str = addThese( 'A', ' string' ); // 'A string'

The function we created adds/concatenates the two supplied arguments and then returns that new value using the return keyword.

Tip

Functions do not need to return a value.

Functions can also be unnamed. These functions , called anonymous functions, are usually either assigned to a variable for use as objects or are used in event handling, both of which we will discuss shortly.

Before we move on, it is important to touch on the concept of variable scope. In JavaScript there are two kinds of variables: global and local . Global variables are initialized outside of any functions and are available for any function to use. Local variables are those variables that are declared within a function. No other functions will have access to those variables. The var keyword plays an important role in determining variable scope. ...

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.