A function is a self-contained collection of statements that run as a single unit: essentially, you can think of it as a subprogram.

Anatomy of a Function

A function definition is just a regular variable definition where the value given to the variable happens to be a function. There are two ways to declare a function in JavaScript. Let’s take a look at both patterns:

Pattern A: Function Expression

var myFunction = function(){
    console.log("Hello world!");
    console.log("¡Hola mundo!");
    console.log("Hallo wereld!");
    console.log("Привет мир!");
    console.log("Përshëndetje bota!");
};

Pattern B: Function Declaration

function myFunction(){
    console.log("Hello world!");
    console.log("¡Hola mundo!");
    console.log("Hallo wereld!");
    console.log("Привет мир!");
    console.log("Përshëndetje bota!");
}

Both variants do exactly the same thing, they save the content of your function console.log("hello") to a variable called myFunction. You can choose the style you prefer.

The declaration begins with a function keyword followed by the function name. The function name is optional. If a function is not given a name, it is said to be anonymous. The third part is the set of parameters of the function, wrapped in parentheses. Within the parentheses is a set of zero or more parameter names separated by commas. These names will be defined as variables in the function, and instead of being initialized to undefined, they will be initialized to the arguments supplied when the function is invoked. The fourth part is a set of statements wrapped in curly braces. These statements are the body of the function. They are executed when the function is invoked.

Simply declaring a function does not execute the body: if you try this example, you will not see our multilingual “Hello, World” messages printed to the console. To call a function (also called running, executing, invoking, or dispatching), you use the name of the function followed by parentheses:

myFunction();

Return Value

Calling a function is an expression, and as we know, expressions resolve to a value. So what value does a function call resolve to? This is where return values come in. In the body of a function, the return keyword will immediately terminate the function and return the specified value, which is what the function call will resolve to.

Let’s check the following example:

var sayGreetings = function(){
    return "Hello there!"
};

Now when we call that function, it will resolve to the return value:
Hello there!

Calling VS Referencing a Function

In JavaScript, functions are objects, and as such, can be passed around and assigned just like any other object. It is important to understand the difference between calling a function and referencing a function. When you add the parentheses after the function identifier, JavaScript knows that you are calling the function: It executes the body of the function and the expression resolves to a value. When you don’t provide the parentheses, you ‘re refering to the function just as you refer to any other variable, and it is not invoked.

Being able to reference a function like any other value (without calling it) allows a lot of flexibility in the language. For example, you can assign a function to a variable, which allows you to call the function by another name:

var f = sayGreetings;
f(); // returns "Hello World"

You can also assign a function to an object property:

var o = {};
o.greetings = sayGreetings;

o.greetings(); // logs Hello World

Or even add a function to an array:

var array = [1, 2, 3];
array[1] = sayGreetings;

array[1](); // logs Hello World

Function Arguments

Now that we have seen how to get values out of functions, how to we put values in functions? The primary mechanism for passing data in a function call is function arguments (sometimes called parameters). Arguments are just like variables that do not exist until the function is called. Consider the following function that takes two numerical arguments and calculates their average:

var avg = function(a, b){
    return (a + b)/2;
};

In function declaration, a and b are called formal arguments. When the function is called, the formal arguments receive values and become actual arguments.

avg(5, 10) // returns 7.5

In this example, the formal arguments a and b receive the values 5 and 10, and become actual arguments (which are very much like variables, but specific to the
function body).

One common pitfall among beginners is that the arguments exist only in the function, even if they have the same name as variables outside of the function.

Take a look at the following example:

var x = 3;
console.log("x before function call: "+x);
var test = function(x){
    x = 5;
    console.log("x in function: " + x);
};

test();
console.log("x after function call: " + x);

When you run the example we will get the following output:

x before function call: 3
x in function: 5
x after function call: 3

The important takeaway here is that assigning a value to x inside the function doesn’t affect the variable x that’s outside the function; that’s because they’re two distinct entities that happen to have the same name.

Do Arguments Define the Function?

In many languages, a function’s signature includes its arguments. For example, in Java, f() (no arguments) is a different function than f(x) (one argument), which is a different function than f(x, y) (two arguments). JavaScript makes no such distinction,
and when you have a function named f, you can call it with 0 or 1 or 10 arguments, and you’re calling the same function.

The implication of this is that you can call any function with any number of arguments. If you fail to provide arguments, they will implicitly receive the value undefined:

var f = function(x){
    return x;
};

console.log(f()); // logs undefined
Advertisements