Home

How to Write Functions in JavaScript

|
|  Updated:  
2016-03-26 7:38:44
JavaScript Essentials For Dummies
Explore Book
Buy On Amazon

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.

About This Article

This article is from the book: 

About the book author:

Chris Minnick is an accomplished author, teacher, and programmer. Minnick authored or co-authored over 20 books, including titles in the For Dummies series. He has developed video courses for top online training platforms and he teaches programming and machine learning to professional developers at some of the largest global companies.

Eva Holland is an experienced web developer, tech trainer, and coauthor of Coding with JavaScript For Dummies. She is a co-founder of WatzThis?, a company focused on training and course development.