Book of Coding


JavaScript functions - create reusable code blocks

The more extensive and complex the software you develop, the more source code you have to manage. As certain tasks are repeated, it makes sense to group the source code into reusable code modules. This has the advantage of not losing the overview of the program and these functions can be reused instead of constantly writing individual instructions one after the other. A function can be called at different points within a program.


1. Define functions

In JavaScript, a function is defined using the keyword function. Since ECMAScript 6 (ES6) there is also the option where the keyword is not required. More on the other shorthand notations later in the text.


Define functions using a function declaration

After the keyword function, the name of the function is specified, followed by a few round brackets () and the instructions that are to be executed. This process is called function declaration. The names of functions are subject to the same restrictions as variable names (Valid variable names).

Complete Code - Examples/Part_66/main.js...

 function showMessage() {
   console.log('Welcome');
 }
                            

The function with the name showMessage(), calls the sentence Welcome on the console. This is a simple example of a function declaration, usually functions consist of several statements that perform more complex tasks.


Define functions using a function expression

Functions can also be created using function expressions. Such function expressions can be used wherever normal expressions can also be used. As a rule, a function name is not specified, which makes the function a so-called anonymous function. A function with a name is a named function.

Complete Code - Examples/Part_67/main.js...

 const showMessage = function() {
   console.log('Welcome');
 }
 showMessage();
                            

Here, the function is assigned to the variable showMessage and then the function can be called via the variable showMessage(). The name showMessage is not the name of the function here, but the name of the variable. The function in this example has no name!


Function declarations vs. function expressions

Function declarations and function expressions differ as follows:

  • For function declarations, the function must be given a name. For function expressions, the name is optional.
  • With function declarations, functions are called via the function name, with function expressions via the variable to which the function was assigned.

 const showMessage = function showMessageFunctionName() {
   console.log('Welcome');
 }
 showMessage();
 // showMessageFunctionName();   // Call not possible

 // For function expressions, the function cannot be called by its name
                            

  • Function expressions are only processed by the interpreter when it encounters the corresponding instruction. This means that such functions can only be used in the subsequent statement. With function declarations, on the other hand, the interpreter ensures that the corresponding functions are also available before the declaration and can therefore also be called in statements before it.

 showMessage();     // Call not possible, this instruction produces an error
 const showMessage = function() {
   console.log('Welcome');
 }

 // Functions that are created using a function expression cannot be used before this expression
                            


 showMessage();     // Call possible
 function showMessage() {
   console.log('Welcome');
 }

 // Functions that are created via function declaration can already be used before this declaration
                            

Create functions via constructor function

It is also possible to define functions via the constructor function Function, but this is rarely done as a rule:

Complete Code - Examples/Part_68/main.js...

 const sum = new Function('x', 'y', 'return x + y');
 console.log(sum(6, 7));
 // output: 13
                                

2. Call functions

The showMessage() function declared above can now be called at various points within a program. All you have to do is specify the function name followed by the round brackets:


 showMessage();   // output: "Welcome"
                        

If the message is to be changed, only Welcome needs to be changed:


 function showMessage() {
   console.log('Hello world');
 }

 showMessage();   // output: "Hello world"
                        

3. Pass and evaluate function parameters

It is often the case that a function requires certain information in order to be executed. For example, if the function showmessage() is to be adapted so that any message can be displayed on the console. This requires a way to pass this message to the function:


Define functions with a parameter

With the help of so-called function parameters, information can be passed to a function, which is then available within the function. To define that a function expects parameters, the name of the parameter must be entered in the round brackets after the function name (the same rules apply when choosing names for parameters as for variable names):


 function showMessage(message) {
   console.log(message);
 }
                            

Here, the showMessage() function has been extended by the message parameter. Within the function, the parameters are then available via their names.


Call functions with a parameter

To call a function with a specific argument, this must be specified in the round brackets when the function is called:

Complete Code - Examples/Part_69/main.js...

 function showMessage(message) {
   console.log(message);
 }
 showMessage('Morty: Hello Rick');
 showMessage('Rick: Hello Morty');

 // output:
 // Morty: Hello Rick
 // Rick: Hello Morty  
                            

Define functions with multiple parameters

Functions can also contain several parameters. In this case, the individual parameters are listed in the function declaration, separated by a comma:

Complete Code - Examples/Part_70/main.js...

 function printPersonalInformation(firstName, lastName, age) {
   console.log(`Firstname: ${firstName}`);
   console.log(`Lastname: ${lastName}`);
   console.log(`Age: ${age}`);
 }
                            

The function printPersonalInformation() is defined here, which accepts the three parameters firstName, lastName and age. All three parameters are available within the function via their respective names.


Call functions with multiple parameters

To call a function that expects several parameters, the corresponding arguments in the round brackets must be separated one after the other with a comma:

Complete Code - Examples/Part_71/main.js...

 printPersonalInformation('Rick', 'Sample', 62);
 printPersonalInformation('Morty', 'Sample', 14);

 // output:
 // Firstname: Rick
 // Lastname: Sample
 // Age: 62
 // Firstname: Morty
 // Lastname: Sample
 // Age: 14
                            

Parameters vs. arguments

Parameters are what is listed within the signature of a function or method. In JavaScript, the signature of a function or method is made up of the name and the number of parameters:

Complete Code - Examples/Part_72/main.js...

 function createNewUser(username, email, password) {
   // ...
 } 
                                

Here createNewUser() is the signature of the method and username, email and password are the parameters of the function.

The term argument is generally understood to mean what is actually passed to the respective function or method when it is called:


 const max = createNewUser('Rick', 'rick@example.com', 'secret');
                                

Here the values Rick, rick@example.com and secret are the arguments of the function.


Call functions with less arguments than specified parameters

A function can also be called with fewer arguments than the parameters defined in the function declaration. The parameters for which no arguments are passed when the function is called behave within the function like variables that are not initialized, i.e. are undefined:

Complete Code - Examples/Part_73/main.js...

 function printPersonalInformation(firstName, lastName, age) {
   console.log(`Firstname: ${firstName}`);
   console.log(`Lastname: ${lastName}`);
   console.log(`Age: ${age}`);
 }
 printPersonalInformation('Rick', 'Sample');

 // output:
 // Firstname: Rick
 // Lastname: Sample
 // Age: undefined
                            

Within the function, you can check whether an argument has been passed to the respective parameters by testing whether it contains the value undefined:

Complete Code - Examples/Part_74/main.js...

 function printPersonalInformation(firstName, lastName, age) {
   if(firstName !== undefined) {
     console.log(`Firstname: ${firstName}`);
   }
   if(lastName !== undefined) {
     console.log(`Lastname: ${lastName}`);
   }
   if(age !== undefined) {
    console.log(`Age: ${age}`);
   }
 }

 printPersonalInformation('Rick', 'Sample');

 // output:
 // Firstname: Rick
 // Lastname: Sample 
                            

The printPersonalInformation() function has been adapted here to check whether a corresponding argument has been passed for each parameter. The argument is only output if this is the case.


Call functions with more arguments than specified parameters

It is also possible to call a function with more arguments than the specified parameters:

Complete Code - Examples/Part_75/main.js...

 function printPersonalInformation(firstName, lastName, age) {
   if(firstName !== undefined) {
     console.log(`Firstname: ${firstName}`);
   }
   if(lastName !== undefined) {
     console.log(`Lastname: ${lastName}`);
   }
   if(age !== undefined) {
     console.log(`Age: ${age}`);
   }
 }
 printPersonalInformation('Rick', 'Sample', 62, 1.76);

 // output:
 // Firstname: Rick
 // Lastname: Sample
 // Age: 62
                            

Here, the fourth argument 1.76 within the function printPersonalInformation() was not assigned to a parameter, as only the three parameters firstName, lastName and age were explicitly specified in the function declaration.

However, there is a way to access all arguments passed within the function. This can be done with the variable arguments, which is implicitly available within a function. This is an object that contains all passed arguments and makes them available via indices (as with arrays): The first argument is accessed via arguments[0], the second is provided via arguments[1] and so on. The length property can be used to determine how many arguments have been passed in total.

Complete Code - Examples/Part_76/main.js...

 function printPersonalInformation(firstName, lastName, age) {
   console.log(`Firstname: ${firstName}`);
   console.log(`Lastname: ${lastName}`);
   console.log(`Age: ${age}`);
   if(arguments.length > 3) {
     console.log(`Size: ${arguments[3]}`);
   }
   if(arguments.length > 4) {
     console.log(`Weight: ${arguments[4]}`);
   }
 }
 printPersonalInformation('Rick', 'Sample', 62, 1.76, 70);

 /* output:
 Firstname: Rick
 Lastname: Sample
 Age: 62
 Size: 1.76
 Weight: 70
 */
                            

The arguments object is not an array, but a so-called array-like object. Because it is not a real array, it is therefore not possible to use an array method on this object.


Call functions with more arguments than specified parameters (rest parameters)

Since ES2015, there is an alternative (or replacement) for the arguments object, the so-called rest parameters. Rest parameters combine all the arguments in a function call for which no parameter is provided in the function declaration:

Complete Code - Examples/Part_77/main.js...

 function printPersonalInformation(firstName, lastName, age, ...restArgs) {
   console.log(`Firstname: ${firstName}`);
   console.log(`Lastname: ${lastName}`);
   console.log(`Age: ${age}`);
   if(restArgs.length > 0) {
     console.log(`Size: ${restArgs[0]}`);
   }
   if(restArgs.length > 1) {
     console.log(`Weight: ${restArgs[1]}`);
   }
 }
 printPersonalInformation('Rick', 'Sample', 62, 1.76, 70);

 /* output:
 Firstname: Rick
 Lastname: Sample
 Age: 62
 Size: 1.76
 Weight: 70
 */
                            

Rest parameters are defined via three consecutive dots and an arbitrary parameter name immediately following. Rest parameters are also accessed via an index and length again specifies the number of arguments. However, the rest parameters are a real array (in contrast to the arguments object) and this array does not contain all the arguments of the function call, but only the arguments for which there is no matching parameter, in this case the values 1.76 and 70.


Functions with a variable number of arguments

Rest parameters are most useful for functions that allow a variable number of arguments, the so-called variadic functions. There are several ways to implement such functions.

  • By specifying an array parameter in the function declaration and accessing this array. Strictly speaking, this is no longer a variadic function, as the function must always be called with a single argument, the array:
Complete Code - Examples/Part_78/main.js...

 function sum(numbers) {
   let result = 0;
   for (let i = 0; i < numbers.length; i++) {
     result += numbers[i];
   }
   console.log(result);
 }
 sum([2,4,6,8]);                 // output: 20
 sum([2,3,4,5,6,7,8,9]);         // output: 44
 sum([1,2,3,4,5,6,7,8,9,10]);    // output: 55
                            

Here the array numbers, in the function declaration, stands for the number array that can be passed. The sum of the numbers is then calculated in a counting loop. An array must always be passed when the function is called.

  • By specifying a remainder parameter in the function declaration and accessing the array implicitly provided by this. The function can also be called with any number of arguments. The implementation of the function using rest parameters differs only slightly from the implementation with arrays. The difference lies in the function declaration:
Complete Code - Examples/Part_79/main.js...

 function sum(...numbers) {
  let result = 0;
  for (let i = 0; i < numbers.length; i++) {
     result += numbers[i];
   }
   console.log(result);
 }
 sum(2,4,6,8);                   // output: 20
 sum(2,3,4,5,6,7,8,9);           // output: 44
 sum(1,2,3,4,5,6,7,8,9,10);      // output: 55
                            

The instructions within the function remain the same, but the function call is different, i.e. individual arguments are passed rather than an array.


Define functions within functions

In JavaScript, it is possible to define functions within other functions. Such functions are then only valid within the function in which they were defined.

Complete Code - Examples/Part_80/main.js...

 function sum(x, y) {
   const result =
     normalize(x) +
     normalize(y);
   function normalize(i) {
     if(i < 0) {
       return 0;
     }
     return i;
   }
   return result;
 }
 console.log(sum(-4, 4));    // output: 4
 console.log(normalize(-4)); // ReferenceError: normalize is not defined
                            

First, the function sum() is defined, which adds two numbers together. Within the function, normalize() is defined, which simply returns the value 0 for negative arguments. However, the function can only be called within the sum() function. Outside of this function, normalize() is not valid; calling it outside of this function results in an error. Functions within other functions have the disadvantage that the inner functions are created anew each time the outer functions are called.


4. Define return values

It is possible to pass certain information to a function via arguments or parameters. It is also possible to return information from a function to the calling code. This information that a function returns is called a return value. A return value is defined within the function using the keyword return, followed by the value that is to be returned.


 function sum(x, y) {
     const result = x + y;   // Addition of the two transferred parameters
     return result;          // Return of the result
 }
                        

Alternatively, the intermediate variable can also be omitted:


 function sum(x, y) {
   return x + y;            // Addition and return
 }
                        

The same thing happens in both variants. In the corresponding function that adds the two parameters x and y, the result is stored in the intermediate variable result and returned.

The result of a function call can then be saved in a variable, for example, and used in the calling code:

Complete Code - Examples/Part_81/main.js...

 function sum(x, y) {
   return x + y;             // Addition and return
 }
 const resultA = sum(4, 4);
 const resultB = sum(6, 6);
 console.log(resultA);     // 8
 console.log(resultB);     // 12
                        

Here, the result of the function call sum(4, 4) is saved in the variable resultA, the result of the function call sum(6, 6) in the variable resultB.

In principle, functions can return any return values: Numerical values, character strings, Boolean values, objects, arrays and functions themselves.

Complete Code - Examples/Part_82/main.js...

 function createUser(username, email, password) {
   const user = {
     username: username,
     email: email,
     password: password
   }
   return user;
 }
 const rick = createUser('Rick Sample', 'rick.sample@example.com', 'secret');
 console.log(rick.username);         // Rick Sample
 console.log(rick.email);            // rick.sample@example.com
 console.log(rick.password);         // secret
                        

In this example, the function returns an object.

The keyword return can only ever be followed by a single value or a single variable, i.e. a function can only have a single return value. It is not possible for a function to return multiple values. However, in order to return several results from a function, a few tricks are used to combine these results in an array or an object and return this array or object. A function can also have several different exit points and therefore different return values, for example by using if branches.


5. Define default values for parameters

The fact that functions in JavaScript can be called with a variable number of arguments leads to the question of how to handle cases within the function where fewer arguments are passed as parameters. This is not so easy to answer across the board, but must be decided individually for each function. In the case of an addition function that expects two parameters but only one argument is passed, a corresponding warning or error would be issued. However, it is often possible to continue working within the function if you use default values for the omitted arguments. Since ES2015, there is a simple notation for this with the so-called default parameters.

Complete Code - Examples/Part_83/main.js...

 function createUser(username, email, password = 'Defaultpassword') {
   const user = {
     username: username,
     email: email,
     password: password
   }
   return user;
 }
 const rick = createUser('Rick Sample', 'rick.sample@example.com', 'secret');
 console.log(rick.username);    // Rick Sample
 console.log(rick.email);       // rick.sample@example.com
 console.log(rick.password);    // secret
 const morty = createUser('Morty Sample', 'morty.sample@example.com');
 console.log(morty.username); // Morty Sample
 console.log(morty.email);    // morty.sample@example.com
 console.log(morty.password); // Defaultpassword
                        

Using the password parameter, you can see here that the default value of a parameter is simply written after the parameter, separated by an equals sign. As soon as the createUser() function is called without passing an argument for the password parameter, the default value Defaultpassword is used.

The next example shows how default values have been implemented so far:

Complete Code - Examples/Part_84/main.js...

 function createUser(username, email, password) {
   password = password !== undefined ? password : 'Defaultpassword';
   const user = {
     username: username,
     email: email,
     password: password
   }
   return user;
 }
 const rick = createUser('Rick Sample', 'rick.sample@example.com', 'secret');
 console.log(rick.username);     // Rick Sample
 console.log(rick.email);        // rick.sample@example.com
 console.log(rick.password);     // secret
 const morty = createUser('Morty Sample', 'morty.sample@example.com');
 console.log(morty.username);    // Morty Sample
 console.log(morty.email);       // morty.sample@example.com
 console.log(morty.password);    // Defaultpassword
                        

The corresponding parameter within the function is overwritten depending on the value of the corresponding argument. If the parameter is set password !== undefined, the corresponding argument is also processed further password. If the parameter is not set, it is reinitialized with the default value defaultpassword. The selection operator (more about selection operator) is used here as it enables a relatively space-saving notation.


6. Use elements from an array as parameters

If you want to use values that exist in an array as individual arguments of a function, there are three options:

  • Accessing the individual values of the array by index and passing the respective value as an argument.
Complete Code - Examples/Part_85/main.js...

 function createUser(username, email, password) {
   const user = {
     username: username,
     email: email,
     password: password
   }
   return user;
 }
 const userData1 = ['Rick Sample', 'rick.sample@example.com', 'secret'];
 const userData2 = ['Morty Sample', 'morty.sample@example.com', 'password'];
 const rick = createUser(
   userData1[0],
   userData1[1],
   userData1[2]
 );
 const morty = createUser(
   userData2[0],
   userData2[1],
   userData2[2]
 );
 console.log(rick);
 console.log(morty);
                        

Here, the user data is available in the arrays userData1 and userData2. In order to create corresponding objects from these two arrays, you must access the individual elements in the arrays via userData[0], userData[1] and userData[2] and then use these as arguments.

Complete Code - Examples/Part_86/main.js...

 function createUser(username, email, password) {
   const user = {
     username: username,
     email: email,
     password: password
   }
   return user;
 }
 const userData1 = ['Rick Sample', 'rick.sample@example.com', 'secret'];
 const userData2 = ['Morty Sample', 'morty.sample@example.com', 'password'];

 const rick = createUser(
   ...userData1
 );
 const morty = createUser(
   ...userData2
 );
 console.log(rick);
 console.log(morty);
                        

The third option is the apply() method, which can be called on functions themselves. It is not necessary to understand this method at this point. The example can be found here:

Complete Code - Examples/Part_87/main.js...

7. Define functions using shorthand notation

Since ES2015, there has been a shorthand way of defining functions. This alternative notation for function expressions is also called Arrow Functions due to the syntax used. The character string => separates the function parameters (on the left-hand side) from the function body (on the right-hand side):


 (parameter) => {function body}
                        

The syntax for the parameters and for the function body differs for Arrow Functions depending on how many parameters the function expects and what you want to express with them. As a rule, parameters are written in round brackets as with "normal" functions, while the function body is written in curly brackets:


 const sum = (x, y) => {return x + y;}

 // ... is the same as ...

 const sum = function(x, y) {
   return x + y;
 }
                        

Since only one statement is used here, the curly brackets can also be omitted and the specification of return can also be omitted, since the result of the expression x + y is automatically returned:


 const sum = (x, y) => x + y;
                        

For functions with one parameter, the round brackets around the parameters can also be omitted:


 const showMessage = message => console.log(message);  
                        

For functions without parameters, however, an empty pair of brackets is used:


 const printHelloWorld = () => console.log('Hello world');
                        

If you want to dispense with the curly brackets in an Arrow Function but return an object, the object must be written in round brackets to prevent the object's curly brackets from being incorrectly interpreted as a function body:

Complete Code - Examples/Part_88/main.js...

 const createUser = (username, email, password) =>
 (
   {
     username: username,
     email: email,
     password: password
   }
 );

 // ... is the same as ...

 function createUser(username, email, password) {
   const user = {
     username: username,
     email: email,
     password: password
   }
   return user;
 }
                        

The different notations for Arrow Functions
NotationMeaning
() => {<function body>} function without parameters
x => {<function body>} function with one parameter
(x, y) => {<function body>} function with several parameters
<function parameter> => {return x*x} function body as block
<function parameter> => x*x function body as a single statement

8. Changing strings via functions

So-called Tagged Templates offer a special way of influencing the result of the string evaluation. The template string (more about template strings) is preceded by the name of a function.


 const name = 'Rick Sample'
 const age = '62'

 function tagFunction(strings, ...replacements) {
  ...
 }

 const message = tagFunction`My name is ${name}, I am ${age} years old`;
 console.log(message);
                        

Internally, the JavaScript interpreter then ensures that the corresponding function tagFunction is called with two parameters: The first parameter represents the fixed parts, the second parameter represents the variable parts, i.e. the values for the placeholders of the corresponding template string.

Within the tag function, it is then possible to access these values and use them, for example, to influence the result value of the function and thus the result of the template string:

Complete Code - Examples/Part_89/main.js...

 function tagFunction(strings, ...replacements) {
   const name = replacements[0]; // "Rick Sample"
   const age = replacements[1];  // 62 or 89
   if (age > 80) {
     return `${strings[0]}${replacements[0]}.`;
     // --> "My name is Rick Sample."
   }
   return `${strings[0]}${name}${strings[1]}${age}${strings[2]}.`;
   // --> "My name is Rick Sample, I am 62 years old."
 }

 const name = 'Rick Sample';
 let age = 62;

 let message = tagFunction`My name is ${name}, I am ${age} years old`;
 console.log(message);
 // My name is Rick Sample, I am 62 years old.

 age = 89;
 message = tagFunction`My name is ${name}, I am ${age} years old`;
 console.log(message);
 // My name is Rick Sample
                        

Here, the tagFunction ensures that a different string is generated depending on the transferred age. The parameter replacements contains the dynamic values of the underlying string, i.e. Rick Sample and 62 or 89. The parameter strings contains the strings My name is ',', I am ' and ' years old. divided by dynamic values.


9. Functions in detail

A good JavaScript developer should also know what happens behind the scenes when a function is called.


The function call stack

Within a JavaScript application, all instructions are executed by the interpreter in sequence. If the interpreter encounters a function call during execution, it "jumps" into this function and executes all the instructions it contains. At the end of the respective function, the interpreter "jumps" out of the function again and continues with the execution of the instruction that is in the program after the function call. If the called function returns a return value, you can continue working with this in the calling code.

A so-called function call stack is managed internally for this purpose. This is a "stack" of functions that can be used to trace which function has called which other function.


 function doSomething() {
   doSomething2();
 }
 function doSomething2() {
   doSomething3();
 }
 function doSomething3() {
   doSomething4();
 }
 function doSomething4() {
 }
 doSomething();
                            

Here you can see four functions that call each other in sequence: The function doSomething() calls the function doSomething2(), this in turn calls the function doSomething3() and this calls the function doSomething4(). Each time the interpreter jumps into a called function, the information about this function is placed on the call stack. If the interpreter jumps out of the function again, the corresponding information is removed from the call stack.

  • Execution context of the global code: Code that is not located within a function is also referred to as global code, i.e. accessible from anywhere. The context in which this code is executed is therefore also called the global execution context. There can only be one global execution context within a program.
  • Execution context of a function call: Code within a function is also called function code. This code is only accessible within the respective function. The execution context of functions determines which variables, which other functions (within the function), which parameters and which specific arguments are available. This creates a separate, new execution context for each function call.
  • Execution context of a call to the eval() function: The eval() method is used to interpret and execute source text that is passed in the form of a character string. If the function is called, a separate form of execution context is created for the passed code. However, the eval() method is rather bad practice.

An execution context defines the following three things:

  • Scope: Which variables, functions and parameters and which arguments are directly available in the respective execution context.
  • Chain of scopes: Defines where to search for variables and functions, for example, if identifiers are used in the code for which no corresponding variable or function with the same name was found in the respective scope.
  • Context object: Within an execution context, the special property this is available, which references the so-called context object.

Scope of validity

The area of validity or visibility is the area in a program in which a variable or function is valid or visible and can therefore be used. The execution context contains information about this scope. In principle, the scope can be defined in two different ways, but they are mutually exclusive:

  • Static (Lexical) means that the scope is derived from the surrounding source code.
  • Dynamic means that the scope is dynamically determined at runtime depending on the execution of the program.

Global variables and global functions are visible everywhere in a program. Variables and functions that have been defined within a function are only visible in this function and in all other functions that have been defined within this function.


Chain of scopes of validity

If an identifier (e.g. the name of a variable, a function or a parameter) is used within the code, but there is no variable, no function, no parameter for this identifier in the respective execution context, the so-called scope chain is used to search in the preceding or higher-level execution contexts.


Context object

The keyword this is used within an object method (or constructor) to address the respective object instance, the current object, "this" object. You can think of this a bit like a property of a function, which is assigned the value of the object on which it is called when it is called. Like arguments, this is an implicit parameter that is available for every function call within the function. Depending on whether a function is called as a global function or as a method of an object, this has a different value.

Complete Code - Examples/Part_90/main.js...

 const person = {
   name: 'Rick',                  // object property
   getName: function() {
     return this.name;
   }
 }
 console.log(person.getName());  // output: Rick
                            

In this object method, a property of the object is read out using this. The output of the program is Rick, because this refers to the object person.

In the next example, a global function getNameGlobal() is also defined. If this function is called, it refers to the global context. The variable name is not defined there, so undefined is returned:


 function getNameGlobal() {
   return this.name;
 }
 console.log(getNameGlobal());   // undefined
                            

The fact that this refers to the global object in a global function can be easily tested by creating a global variable name and calling the function getNameGlobal() again:

Complete Code - Examples/Part_91/main.js...

 var name = "global name";
 function getNameGlobal() {
   return this.name;
 }
 console.log(getNameGlobal());   // output: global name
                            

In the next example, there are two objects that each define the name property and reuse the global function getNameGlobal() as a method:

Complete Code - Examples/Part_92/main.js...

 function getNameGlobal() {
   return this.name;
 }
 const person = {
   name : 'Morty',
   getName : getNameGlobal
 }
 const artist = {
   name : 'Metallica',
   getName : getNameGlobal
 }
 console.log(person.getName());  // output: Morty
 console.log(artist.getName());  // output: Metallica
                            

Here you can see that this is set dynamically when the function is called: getNameGlobal() as an object method in the context of person returns the value Morty, in the context of artist the value Metallica.

The variable this has a different value depending on the context in which the function is called. The following rules apply:

  • When a global function is called, this refers to the global object or is not defined in strict mode.
  • If a function is called as an object method, this refers to the object.
  • If a function is called as a constructor function, this refers to the object that is created by the function call.

10. Call functions through user interaction

Here is another example of how you can call a function within a web page by pressing a button. To react to the pressing of a button and call an eFunction, add an event listener for the click event of the corresponding button:

Complete Code - Examples/Part_93/index.html...

 <body>
 <div class="container">
   <div class="row">
     <label for="field1">X</label> <input id="field1" type="text" value="4">
   </div>
   <div class="row">
     <label for="field2">Y</label> <input id="field2" type="text" value="6">
   </div>
   <div class="row">
     <label for="result">Result: </label> <input id="result" type="text">
     <button id="button-calculate-sum">Calculate sum</button>
   </div>
 </div>
 <script src="script.js"></script>
 </body>
                        

The HTML code is a simple web page on which the sum of two numbers can be calculated using a form. The form contains three input fields and a button to trigger the calculation.

Complete Code - Examples/Part_93/main.js...

 document.addEventListener('DOMContentLoaded', function() {
   const button = document.getElementById('button-calculate-sum');
   button.addEventListener('click', calculateSum);
 });
 function calculateSum() {
   const x = parseInt(document.getElementById('field1').value);
   const y = parseInt(document.getElementById('field2').value);
   const result = x + y;
   showResult(result);
 }
 function showResult(result) {
   const resultField = document.getElementById('result');
   resultField.value = result;
 }
                        

In the JavaScript code, an event listener is first registered for the event DOMContentLoaded using the addEventListener() method. The anonymous function, which is passed as an event listener, is only executed once all elements on the website have been loaded. This ensures that the input fields and the button are available when they are accessed. Another event listener is registered within the event listener, which is executed when the click event is triggered: the calculateSum() function. This in turn accesses the two input fields, reads their values, adds them together and displays the result in the third input field using the showResult() function.

Preview

Related links: