Skip to content

8. The functions

Image

8.1. script [func-01]

The script examines how parameters are passed to a function:

  • pass-by-value for numbers, strings, and booleans;
  • pass-by-reference for arrays, literal objects, and functions;

'use strict';
// function parameter passing modes
// -----------------------number - passed by value
function doSomethingWithNumber(param) {
  param++;
  console.log("[param inside function]=", param, "[type]=", typeof(param), "[passed by reference]=", param === count);
}
// call code
let count = 10;
doSomethingWithNumber(count);
console.log("[count outside function]=", count);

// --------------------- string - passed by value
function doSomethingWithString(param) {
  param += " xyz"
  console.log("[param inside function]=", param, "[type]=", typeof (param), "[pass-by-reference]=", param === text);
}
// call code
let text = "abcd";
doSomethingWithString(text);
console.log("[text outside function]=", text);

// --------------------- boolean - passed by value
function doSomethingWithBoolean(param) {
  param = !param;
  console.log("[param inside function]=", param, "[type]=", typeof (param), "[pass-by-reference]=", param === bool);
}
// call code
let bool = true;
doSomethingWithBoolean(bool);
console.log("bool [outside function]=", bool);

// --------------------- array - passed by reference
function doSomethingWithArray(param) {
  param.push(1000);
  console.log("[param inside function]=", param, "[type]=", typeof (param), "[pass-by-reference]=", param === tab);
}
// calling code
const tab = [10, 20, 30];
doSomethingWithArray(tab);
console.log("[tab outside function]=", tab);

// --------------------- object - passed by reference
function doSomethingWithObject(param) {
  param.newProperty = "xyz";
  console.log("[param inside function]=", param, "[type]=", typeof (param), "[pass-by-reference]=", param === obj);
}
// calling code
const obj = [10, 20, 30];
doSomethingWithObject(obj);
console.log("[obj outside function]=", obj);

// --------------------- function - passed by reference
function doSomethingWithFunction(param) {
  // something rather odd, but it works
  param.newProperty = "xyz";
  console.log("[param inside function]=", param, "[type]=", typeof (param), "[pass-by-reference]=", param === f);
}
// calling code
const f = x => x + 4;
doSomethingWithFunction(f);
console.log("[f outside function]=", f, f.newProperty, typeof (f));

Execution


[Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe -r esm "c:\Data\st-2019\dev\es6\javascript\functions\func-01.js"
[param inside function]= 11 [type]= number [pass by reference]= false
[count outside function]= 10
[param inside function]= abcd xyz [type]= string [pass by reference]= false
[text outside function]= abcd
[param inside function]= false [type]= boolean [pass by reference]= false
bool [outside function]= true
[param inside function]= [ 10, 20, 30, 1000 ] [type]= object [pass by reference]= true
[tab outside function]= [ 10, 20, 30, 1000 ]
[param inside function]= [ 10, 20, 30, 'aNewProperty': 'xyz' ] [type]= object [pass by reference]= true
[obj outside function]= [ 10, 20, 30, 'aNewProperty': 'xyz' ]
[param inside function] = x => x + 4 [type] = function [pass by reference] = true
[f outside function] = x => x + 4 xyz function

8.2. script [func-02]

The following script shows that the [function] type is a data type like any other and that a variable can have this type. It also shows two ways to define a function:

  • one using the [function] keyword;
  • the other using the "arrow" notation =>;

'use strict';
// you can assign a function to a variable
const variable1 = function (a, b) {
  return a + b;
};
console.log("typeof(variable1)=", typeof (variable1));
// The variable can then be used as a function
console.log("variable1(10,12)=", variable1(10, 12));
// the function can be defined using the => syntax
const variable2 = (a, b, c) => {
  return a - b + c;
};
console.log("variable2(10,12,14)=", variable2(10, 12, 14));
// You can omit the curly braces if there is only one expression in the function body
// this expression is then the function's return value
const variable3 = (a, b, c) => a + b + c;
console.log("variable3(10,12,14)=", variable3(10, 12, 14));

Execution


[Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe -r esm "c:\Data\st-2019\dev\es6\javascript\fonctions\func-02.js"
typeof(variable1) = function
variable1(10,12) = 22
variable2(10,12,14) = 12
variable3(10,12,14) = 36

8.3. script [func-03]

This script demonstrates the ability to pass a function as a parameter to another function. This technique is widely used in JavaScript frameworks.


'use strict';
// a function's parameters can be of type [function]

// function f1
function f1(param1, param2) {
  return param1 + param2 + 10;
}
// function f2
function f2(param1, param2) {
  return param1 + param2 + 20;
}
// function g with function f as a parameter
function g(param1, param2, f) {
  return f(param1, param2) + 100;
}
// uses of g
console.log(g(0, 10, f1));
console.log(g(0, 10, f2));
// the actual function parameter can be passed directly - form 1
console.log(g(0, 10, (param1, param2) => {
  return param1 + param2 + 30;
}));
// the actual function-type parameter can be passed directly - form 2
console.log(g(0, 10, function (param1, param2) {
  return param1 + param2 + 40;
}));

Execution


[Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe -r esm "c:\Data\st-2019\dev\es6\javascript\functions\func-03.js"
120
130
140
150

8.4. script [func-04]

The following script demonstrates that a JavaScript function can behave like a class:


'use strict';
// A function can be used as an object

// an empty shell
function f() {

}
// to which properties are assigned from the outside
f.prop1 = "val1";
f.show = function () {
  console.log(this.prop1);
}
// using f
f.show();

// a function g acting as a class
function g() {
  this.prop2 = "val2";
  this.show = function () {
    console.log(this.prop2);
  }
}
// Instantiate the function with [new]
new g().show();

Comments

  • lines 5–7: the body of function f does not define any properties;
  • lines 9–12: properties are assigned to the function f from outside;
  • line 14: use of the function (object) f. Note that we do not write [f()] but simply [f]. This is the notation for an object;
  • lines 17–22: we define a function [g] as if it were a class with properties and methods;
  • line 24: the function [g] is instantiated by [new g()];

Execution results


[Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe -r esm "c:\Data\st-2019\dev\es6\javascript\classes\class-00.js"
val1
val2

ES6 introduced the concept of classes, which now allows us to avoid using functions to create classes.

8.5. script [func-05]

The script [func-05] demonstrates the use of an operator called the [rest operator]:


'use strict';
// rest operator
function f(arg1, ...otherArgs) {
  // 1st argument
  console.log("arg1=", arg1);
  // the other arguments
  let i = 0;
  otherArgs.forEach(element => {
    console.log("otherArguments[", i, "]=", element);
    i++;
  });
}

// call
f(1, "two", "three", { x: 2, y: 3 })
  • line 3: the [...otherArgs] notation means that with a call of the form f(param1, param2, param3), we will have line 3:
    • arg1=param1
    • otherArgs = [param2, param3]. [otherArgs] is therefore an array that collects all the actual parameters passed after [param1];

The results of the application are as follows:

1
2
3
4
arg1 = 1
otherArguments[ 0 ]= two
otherArguments[ 1 ]= three
otherArguments[ 2 ]= { x: 2, y: 3 }