1. Home
  2. Computing & Technology
  3. JavaScript

JavaScript Functions
1. Introduction

By , About.com Guide

The first thing to consider about functions is how to name them. This will be easy for you to remember because JavaScript follows exactly the same rules for naming functions as it does for naming variables. A function is just another type of variable. The only difference from the other types we have looked at so far is that a function contains code rather than numbers or text strings.

We can assign a value to a function the same way that we do with other variable types. Here are two variations on how to assign a value to a function this way.

var x = Function('a = 2; b = 3; c = 4;');
var x = function() {a = 2; b = 3; c = 4;};

There is a third way of coding functions that doesn't require us to assign the function code to a variable before we use it. This method is the most commonly used way to define functions.


function x() {
  a = 2;
  b = 3;
  c = 4;
}

There are disadvantages to the first two methods shown. The main one is that the entire functions are effectively treated as one statement. The method used in the last example is exactly the same function written in a way that makes it easier to split the code over multiple lines. This makes this third alternative the easiest one to use most of the time. There will be times when using one of the other two methods makes the code much easier to write so it is worth remembering that there are three ways of defining functions.

Warning: As functions are really just another type of variable, you need to be careful that you don't give them the same name as another variable. This would have the effect of overwriting the value currently stored in that variable with the value of the function.

This tutorial first appeared on www.felgall.com and is reproduced here with the permission of the author.

Explore JavaScript
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript
  4. Javascript Tutorials
  5. Learn Modern JavaScript
  6. 3. Functions
  7. JavaScript Functions>

©2010 About.com, a part of The New York Times Company.

All rights reserved.