More about functions - STRENGTHENING THE WARRIOR'S ARSENAL - JavaScript in Plain Language (2015)

JavaScript in Plain Language (2015)


3.2 More about functions

What are expressions and statements?

We have been using the terms expression and statement throughout the book in an informal way. It is time to stop and think about these terms because they have specific meanings.

· A statement is a complete command which instructs the computer to carry out a specific task. It’s usually written in one line (but not always) and terminated by a semicolon.

Examples of statements:

var z = 1 + 2 + 3;

console.log("Hello World");

if(z > 2) {
console.log("yes it is");

In the last example, the statement starts at if and ends at the semicolon. If you place the semicolon prematurely you will get an error. That is a common mistake when we first start programming.

We have also mentioned several times “the return statement”. Aside from a return being only allowed in functions, it is written as a statement:

return 3 + 4;

Many times statements are compounded into a group of multiple statements in which case we use the curly braces to wrap the compound statements:

if(z > 2) {
console.log("yes it is");
console.log("z is greater than 2");
console.log("z is also the last word of the alphabet");

Notice how the last curly brace does not terminate with a semicolon. The only time a semicolon is placed after a curly is when we assign a code block to a variable like for example when we create and object.

Then we have expressions.

An expression is anything that evaluates to a one unit. Like for example, when JavaScript sees 3 + 4 it actually see 7. JavaScript looks at the expression and simplifies the expression into 1 unit. Just like statements, expressions are everywhere and they can be one and the same.


var x = 4;

Above, var x = 4; is a statement and also an expression. Actually we have two expressions. JavaScript looks at the code and subdivides the expressions into:

1- x, which results in 4 when evaluated, and

2- 4, which results in itself. JavaScript looks a 4 and it expresses 4 as a result.

if( 10 < 11) { // do something; }

Above, if(10 < 11) is an expression because JavaScript does not see the literal 10<11, it only sees true or false, one or the other. JavaScript does not really care for 10<11 in itself, it looks at it and internally replaces it with a Boolean true.

· This is a very important concept in order to understand the language: We write expressions, and JavaScript stores the result of their evaluation.

Of course 10 and 11 are individual expressions in their own right, but they are not as important as the combination of 10<11. JavaScript interprets it and saves it as just plain true.

Now, look at the semicolon on the previous if() example. That’s where the statement ends, it starts on if and it ends at ..thing;

What about a function? Is it an expression in itself?

Take for example the following function:

function x (num1, num2){
return num1 + num2;

The above function by itself does not evaluate to anything. It could potentially evaluate to the sum of num1 + num2 but only when the function is called upon:


The function when called evaluates to 6.

How does it evaluate to 6 when we call function x with arguments 2 and 4?

num1 becomes an expression and it evaluates to 2.
num2 becomes an expression which evaluates to 4.
num1 + num2 become an expression which evaluate to 6

Expression evaluation is an important concept in order to truly understand JavaScript (or any other language for that matter).

In the next topic we will see how to assign a function to a variable, making the combination of function and variable, an expression.

Remember, to declare a variable we start with var. To declare a function we start with function:

var x = 33;

function y (){ }

Next we are going to see how to assign a function as a value to a variable and answer a few of common questions you may have.

Assigning functions to variables

Up to this point we have been declaring functions in the following literal manner:

function x () { return 5; }

However, we could also assign a function to a variable like this:

var x = function { return 5; };

Notice the semicolon at the end. This is because the whole variable declaration is in itself a statement. Statements are complete command sentences given to JavaScript and they usually terminate with a semicolon which separates them from the next statement.

Wait, I still don’t get it. I don’t see a semicolon on a function declaration like we have done before. Why does this one get a semicolon?

The semicolon has nothing to do with the function. A function in itself is not a complete command statement until it is called in. When we call a function, like for example x(); we add a semicolon. The earlier semicolon in question had to do with the variable assignment. When we assign a value to a variable we terminate the assignment with a semicolon because the assignment is a command sentence, or an expression.

The same goes for any other assignment such as an array:

var y = [1,2,3];

Or as for object assignments:

var z = {"color": "green"};

Or function assignments:

var z = function(){ return 5; };

What is an anonymous function?

In the previous example, the function is known to be an anonymous function because it has no proper name. z is just some variable that points to it.

However, without z the function ceases to exist because the browsers will clear it from memory since it has nothing point at it. Any loose objects in memory get discarded because they cannot be identified (remember functions are also objects).

Using variables as pointers

Speaking of pointers, the previous variable z points to the function assigned to it. We could use more than one pointer by assigning the “contents” of z to another variable.
Take for example the following function assignment:

var z = function(){ return 7; };

Now assign a to z and b to a to see what happens:

var a = z;

var b = a;

Remember, assignments are from right to left.

What is the content of variable z?

The content of variable z is function(){ return 7; }. That’s right, the function script (the string of words and symbols that make up the function) is the content of variable z, or what z evaluates to by itself. The only time we get the value 7 is when we call the function by post fixing a pair of parentheses to z: z();

Because the value of z is a function script, when we assign z to a, or z to b, we are assigning the script of the function. This is very powerful in JavaScript because it means that we can plug in an existing function anywhere in the program and as many times as we need to.

Now we are able to call the function with any of the three variables:

a(); // returns 7

b(); // returns 7

z(); // returns7

In summary

Remember, an expression is anything that evaluates to a one unit. This unit is what JavaScript actually sees from the code we write, not what the code looks like to the human eye. As programmers we need to think like a computer by knowing what the computer is going to see when it encounters an expression.

1- What is the value of expression z?
Ans: function(){ return 7; }

2- What is the value of z();
Ans: 7

3- What is the value of expression a?
Ans: function(){ return 7; }

4- What is the value of expression a( )?
Ans: 7

5- What is the value of expression b?
Ans: function(){ return 7; }

6- What is the value of expression b( )?
Ans: 7

And just to solidify the concept, here’s a question unrelated to our examples:

7- What is the value of expression if(10 > 5)?
Ans: true

true is what JavaScript sees when we write (10 > 5), which by the way, an expression in an if() statement is actually a question as far as JavaScript is concerned.

The balloon concept


If a function was a balloon tied by three strings, z, a, b, what would happen to the balloon if we cut off string z?


Nothing would happen to the balloon, it would stay the same because a and b still hold the balloon.

What would happen then if we cut both a and b from the balloon? The balloon would fly away.

If the balloon was our function it would also fly away, it would be put in garbage collection mode to be wiped out from memory by the browser.

In the next few exercises we will practice with function expressions (those assigned to variables) instead of function declarations (the syntax style we had first learnt). Bear in mind that one function or another will yield the same result, but it is important to become with both styles.

Function parameters and arguments

A function can have input parameters so that when we call the function we pass in data arguments. Many times programmers use the same term for both meanings, either parameter or arguments and it has been accepted as such, but this is the definition: we give arguments to parameters when we call the function. A parameter is a physical thing, an interface, an input mechanism, a temporary variable that gets deleted once the function ends its execution.

The sequence of our data arguments when we call the function will always coincide with the physical sequence of the input parameter in the function parentheses.

For example:

var x = function(num1, num2){
return num1 - num2;

The sequence of passing data into inputs num1 and num2 matters because the function’s internal program is wired to the layout sequence of the input parameters:

x(5, 3);

It will return the value 2 because 5 – 3 = 2

However, if we call the function and write the arguments in reverse order:


The function will return the value -2 because 3 -5 = -2

In short, when we call the function, the sequence of arguments needs to be observed.

· What happens if we call the function and pass in three arguments instead of two?


The result will be 2, as of 5 -3 = 2. The last argument (4) is ignored because there is no provision to do anything with it within the function.

· What happens if we call the function with just one argument even though the function is hardwired with two input parameters?


In our case it returns NaN, which is a JavaScript property that stands for Not-a-Number, or not a valid number. That’s because the output became the subtraction of 5 – num2 and num2 was not assigned to anything and remained "undefined" which is its original value.

For example, in

var x = function(input1, input2){
return input1 + input2;

If I call the function with two arguments:
x("Tony", "deAraujo");

I get an output of "TonydeAraujo".

If on the other hand I only use one argument, it assumes the first input parameter, and the other input parameters will be undefined:

It outputs "Tonyundefined".

· We can program as many as 256 input parameters in a function.

Do not memorize all these, juts take the time to understand it and move forward.

The object arguments

The input parameters are written into a function by the programmer because he/she wants to have some sort of sequence of data input and for the most part this works out greatly.

However, JavaScript functions have another way to accept arguments via an object that belongs to (and only to) functions: the object arguments (use the plural name).

The object arguments acts like an array in the sense that it can be addressed numerically, but it is not a full featured array because it only inherits some functionality from the array family, not all of its library.

Let’s see how this object works.

var x = function(){
return arguments[0] + arguments[1].toUpperCase();

The above function has no input parameters specified. However, it outputs the first argument we give to it when we call the function, as well as the second argument in upper case which goes on position 1 (remember, locations are zero based just like in arrays):

x("tony", "dearaujo");

It returns: "tonyDEARAUJO"

So we can still program our functions as we wish and with no specified input parameters. Just use the arguments object to numerically address each data element.

I go into much more detail about the arguments object on my other book which, although written earlier, it could be considered a second volume for this one.