How to Write Functions in JavaScript - dummies

How to Write Functions in JavaScript

By Chris Minnick, Eva Holland

Learning to write functions can make the life of a JavaScript programmer significantly easier. A function declaration must be written in a specific order. A function declaration consists of the following items, in this order:

  • Function keyword

  • Name of the function

  • Parentheses, which may contain one or more parameters

  • Pair of curly brackets containing statements

Sometimes, a function’s whole purpose will be to write a message to the screen in a web page. An example of a time when it’s useful to have a function like this is for displaying the current date. The following example function writes out the current date to the browser window:

function getTheDate(){
 var rightNow = newDate();
 document.write(rightNow.toDateString());
}

Follow these steps to try out this function:

  1. Open the JavaScript Console in Chrome.

  2. Type the function into the console.

    Use Shift + Return (or Shift + Enter) after typing each line, in order to create a line break in the console without executing the code.

  3. After you enter the final }, press Return (or Enter) to run the code.

    Notice that nothing happens, except that the word undefined appears in the console, letting you know that the function has been accepted, but that it didn’t return a value.

  4. Call the function by typing the name of the function (getTheDate) followed by parentheses, followed by a semicolon:

    getTheDate();

    The function prints out the current date and time to the browser window, and then the console displays undefined because the function doesn’t have a return value; its purpose is simply to print out the date to the browser window.

The default return value of functions is undefined, so technically, undefined is a return value.