Menu Close

Articles

JavaScript: functions

A function is a named block of code designed to perform a particular task. Functions have parameters and most function return a result. If a function do not return an explicit result it actually returns an “undefined” value and can’t be used in expressions.

Expression review

Before we talk about functions, let’s review what an expression is and how to execute an expression in JavaScript: An expression is an enumeration of literals, operators, variables and functions or methods. The result of expression has a data type, so an expression can be: numeric, logical, string expression depending on the result type.

An expression is usually anonymous and is executed immediately when the logical flow it reaches it. The expression is usually part of a statement. It may be a declaration statement, a modification statement a return statement or a decision statement.

Expressions may be enclosed in round parenthesis and may be combined into larger expressions. Sometimes smaller parts of a larger expression are not executed. For example in a ternary expression or a short-circuit expressions.

Example:

Next we define a function and an expression. A return statement execute first expression before returning the result to the function call. The second expression is used in assignment statement. A function call is an expression. 

Ternary expressions

A ternary expression is an intelligent expression that makes a decision and calculate one result or another depending on condition value. Remember a logical condition can use relation operators or logical operators to create a boolean response.

Example:

Syntax:

condition ? first_expression : second_expression;

  •  when condition is true, first_expression is calculated as result
  •  when condition is false, second_expression is calculated as result

Note: The conditional operator “?” is the only JavaScript operator that takes three operands. But wait  there is more. This kind of expressions can be chained, so you can use multiple conditions. Read about it next and wander if you could ever use this in your programming snippets.

Conditional chain

The ternary operator is right-associative, which means it can be “chained”:

Pattern:

Notes:

  • If condition1 is true the condition2 and condition3 are not executed,
  • If no condition is true, the last expression is executed,
  • Result can be captured using return or assignment.

Function Invocation

The JavaScript function can be call using operator: () after function name. Enclosed in these parenthesis you can use literals, variables or expressions, or not. Remember that a JavaScript function can be located in a <script> or in a file. There are 3 basic ways to call a JavaScript function.

  1. From another function or JavaScript code;
  2. When an event occurs. For example user click a button or a link;
  3. Automatic invocation (self invoked).

Function Result

A function can calculate a value and return value back to the caller. We use “return” keyword. In the example we use an expression to return value of multiplication between arguments. Results can be ignored in JavaScript. That means you can use a function like you normally use a procedure in a procedural language.

Function Parameters

A function can have several parameters. The parameters can have initial values. In next example p2 has default value 10. Parameters with default value are optional. Parameters with no default value are mandatory.

Multiple results

JavaScript functions can create multiple results using JSON notation. This is anonymous block enclosed in curly brackets and separated by comma. Actually is an anonymous object that contains your results.

Example:

Capture results using anonymous object:

Example:

Capture result using destructuring:

Output Parameters

Normally a function is using the parameter for input, but sometimes it is useful to use the parameters for output. That means instead of using the return statement to return a result, you assign the result to the parameter. Output parameters can be used to propagate multiple results back to the caller.

Example:

In previous example I have used many things you may not be yet familiar with. The output parameter has name: result and is parameter of an anonymous arrow function. The arrow function is declared with “=>” that looks like an arrow. This function is transmitted to get_back as callback function that has the name callback in this case, but could have other name.

Caution: Any output parameter must be an object, otherwise the parameter value will not propagate back. In our example the object is created using expression: {value:”yes”}. The variable “output” declared in first line becomes an object when callback is executed and is assigned to the result. 

Functional Programming

JavaScript can be used as a functional programming language. This is very good feature of JavaScript. It may be difficult to understand at the beginning. Pay attention and memorize the fundamental concepts of functional programming, then use the examples to understand more:

Concepts:

  1. A function is a reference to an object;
  2. You can assign a function to a variable;
  3. You can create a function that can have as a result another function;
  4. You can use a function as a parameter to call other function;
  5. You can execute a function by using a variable instead of function name;

Functions that manipulate other functions are called: “high order functions“.

Example:

In this example we use a higher order function to create a closure. The closure is a function that can create another function. The created function is enclosed in a closure and it has special properties that makes its behavior unique.

Note: This example create actually two functions: increment() and getCount() that are encapsulated into an anonymous object created by return statement. Read more concepts to understand better:

  • A high order function is a function that return other function;
  • A closure is a high order function that create another function;
  • The closure create a local context for enclosed functions;

Callback functions

A “callback function” is a parameter of a high order function. It is called “call back” since it can be invoked from the higher order function.  Callback functions can be anonymous functions or arrow functions that look like an expression. If you do not pay attention to this you may read others people code and do not even realize that a function need a callback parameter.

Example:

Note: Example above is using new concepts to create callback functions: “expression function” and “arrow function”. These two kind of functions can be named or unnamed. In our case the name of the callback function will be “foo” because is the name of the formal parameter of the high order function that is “bar”.

Expression functions

An expression function is a function that is created at runtime using an expression. Expression functions can be assigned to variables and executed later. The declaration of expression functions is very unusual. Read the example to understand how “foo” is in fact a function.

Example:

Arrow functions

An arrow function is using symbol “=>” to associate a list of parameters with an expression. In this case the keyword “function” is missing, but the expression is actually assigned to a variable that becomes function. The variable name can be executed later as a function with parameters and it can return a result.

Example:

Note: We have used the new keyword: “const” to declare expressions. This will help to avoid overriding by mistake an expression function that was already defined. You can also use “let” to create a handler for the expression functions. A common mistake is to use “var”. This enable you to recreate a function in a loop, over and over again. This works, but the performances could be miserable. It is a very bad mistake easy to avoid if you use “const”.

Homework:

Try the next example and observe that it does not produce the right result. Then fix the code and run it again. The solution of the problem is explained in the comments. So read the solution and try to understand the code. 

Demo: call with mistake

Fix: call with output

This example was created to demonstrate how to use output parameters. 

Next article: objects