Write and Execute a JavaScript Function
Robin Kim
—August 01, 2014
You will learn:
- A function definition is a function implementation.
- A function expression is not the same as a function declaration.
- A function call is a function invocation.
- 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:
- name (if any),
- parameters (if any), and
- contents (if any)
and can be achieved through a:
- function expression, or
- 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 happensisZero(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 declarationfunction add(first, second) {return first + second;}// function calladd(2, 3);
- The function
add
is declared with 2 parameters:first
andsecond
. - The function is called by
add(2, 3)
with the arguments2
and3
. - The function
add
is excuted with parametersfirst
andsecond
being assigned the values2
and3
, respectively. It returns5
.
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!