This site runs best with JavaScript enabled.

Write and Execute a JavaScript Function

Robin Kim

August 01, 2014


You will learn:

  1. A function definition is a function implementation.
  2. A function expression is not the same as a function declaration.
  3. A function call is a function invocation.
  4. An actual argument and a formal parameter are similar, but not exactly the same thing.

Definition (or Implementation)

A function definition (or function implementation) is a group of statements that create a function. The definition (or implementation) tells us about the function's:

  1. name (if any),
  2. parameters (if any), and
  3. contents (if any)

and can be achieved through a:

  1. function expression, or
  2. function declaration.

Here is an example of a function expression. The variable useless is assigned to an anonymous function that has no parameters and no content:

var useless;
useless = function() { };

Tidbit #1: Placing a set of parentheses () after the final curly bracket } will execute the function immediately and assign the variable to the return value of the function!

A function declaration defines a free standing function, as shown below:

function isZero(num) {
return num === 0;
}

Here, the function is named isZero, has a parameter num, will execute return num === 0; when called upon.

Tidbit #2: Function expressions and function declarations will come into play again when we talk about variable and function hoisting.

Call (or Invocation)

A function call (or function invocation), is the expression that starts the execution of a function. Listed are two function calls (or invocations):

useless(); // nothing happens
isZero(0); // evaluates to true

At this point, any inputs are passed along to the function, which executes based on its definition.

Argument vs. Parameter

An actual argument is an input passed into a function. It's written in the function call. A formal parameter is an input received by a function during its execution. It's given in the function definition.

This example helps explain the difference between an argument and a parameter:

// function declaration
function add(first, second) {
return first + second;
}
// function call
add(2, 3);
  1. The function add is declared with 2 parameters: first and second.
  2. The function is called by add(2, 3) with the arguments 2 and 3.
  3. The function add is excuted with parameters first and second being assigned the values 2 and 3, respectively. It returns 5.

The ability to use a built-in arguments object in a function definition probably doesn't help distinguish the difference between an argument and parameter. You'll often see the words used interchangeably!

Tidbit #3: The number of arguments passed into a function doesn't have to equal the number of parameters listed in the function's definition. The arguments array-like object allows us to have access to all of a function's inputs!

Share article