Using functions
Function declaration
A function can be declared with the keyword function:
function doIt(param) {
log('Do something with param :', param)
}
Functions can be declared on any scope level. More inner scope levels overrule outer scope levels.
Functions can also be "self calling" - this is best practice for the main function of a package. This is used to avoid operational code on global level - everything should be in a function.
(function () {
log('This function is called by its own declaration')
}())
Arrow functions are also allowed. They can be used in any kind of callback method like in array member funtions.
let list = [
{ id: 1, value: 'First' },
{ id: 2, value: 'Second' },
{ id: 3, value: 'Third' }
]
let res = list.find(el => el.id == 2)
log('Result :', res)
Of course it is possible to use standard functions with names instead of the arrow function:
(function () {
let list = [
{ id: 1, value: 'First' },
{ id: 2, value: 'Second' },
{ id: 3, value: 'Third' }
]
let res = list.find(check_value)
log('Result :', res);
}())
function check_value(element) {
return element.id == 2
}
This is mostly useful for more complex scenarios.
Functions in variables
As shown in the example above the function name can be used as a parameter like a variable identifier. This means that any variable can also contain a function.
let is_add = false
function add(a, b) {
return a + b
}
function sub(a, b) {
return a - b
}
let algorithm = is_add ? add : sub
let res = algorithm(5, 2)
log('Result :', res)
In the example add and sub are functions with two parameters. Depending on the value of "is_add" the algorithm variable is set to the value of add or sub. In this case the result of the function call is (5-2) = 3.
With Arrow functions this can be written even shorter:
let is_add = false
let add = (a, b) => a + b
let sub = (a, b) => a - b
let algorithm = is_add ? add : sub
let res = algorithm(5, 2)
log('Result :', res)
Now add and sub are variables containing the functions.
Object literals and functions
Since any variable can contain a function, object literals can do also:
let obj = {
f: function (p) {
return p * 2
}
}
let res = obj.f(5)
log('Result :', res) // 10
The object obj contains a member property f that is a function doing a multiplication with its parameter value.
To call the function the object is written in front of it.
The result of the calculation in the example is 5*2 = 10.
Object member functions and this
Object literals contain data and functions. Inside a Object Literal Member Function the other properties of the same object can be accessed with this.
let obj = {
a: 3,
f: function (p) {
return p * this.a
}
}
let res = obj.f(5)
log('Result :', res) // 15
The object obj contains a member property "a" with the value 3, and a function.
Using the function in the code multiplies the parameter with the member property a.
The result of the calculation in the example is 5*3 = 15.
Object property values can be changed as shown in the next example:
let obj = {
a: 3,
f: function (p) {
return p * this.a
}
}
let res_1 = obj.f(5)
log('Result 1 :', res_1) // 15
obj.a = 4
let res_2 = obj.f(5)
log('Result 2 :', res_2) // 20
Important: functions using "this" must not be arrow functions. Arrow functions do not have "this" per definition.
Array member functions
Lists / arrays define a set of useful functions to locate or manipulate their elements. Use them to make the code more concise, more readable and easier to maintain.
Below are some examples of array member functions:
- find - find the first element that matches a specific condition
- findIndex - find the index of the first element that matches a specific condition
- every - true if every element matches a specific condition
- some - true if some elements matches a specific condition
- forEach - execute the function for each element
- sort - return a sorted list of the same elements
- filter - return a filtered list of the same elements
- map - return a list of new elements computed by each of the original elements
More functions can be found in the Built-in object types section of the Function reference.
Example find:
let list = []
list.push({ id: 3, subject: 'Running out of coffee' })
list.push({ id: 6, subject: 'Toner is empty' })
list.push({ id: 8, subject: 'Paper needs to be replaced' })
let search_result = list.find(el => el.id === 6)
log('Result :', search_result.subject) // 'Toner is empty'
Example findIndex:
let list = []
list.push({ id: 3, subject: 'Running out of coffee' })
list.push({ id: 6, subject: 'Toner is empty' })
list.push({ id: 8, subject: 'Paper needs to be replaced' })
let search_ix = list.findIndex(el => el.id === 6)
log('Result index:', search_ix) // 1
log('Result value:', list[search_ix].subject) // 'Toner is empty'
Example every:
let list = []
list.push({ id: 3, subject: 'Running out of coffee' })
list.push({ id: 6, subject: 'Toner is empty' })
list.push({ id: 8, subject: 'Paper needs to be replaced' })
let all_elements_same_id = list.every(el => el.id === 6)
if (all_elements_same_id) {
log('All Elements have the same id of 6')
} else {
log('Not all Elements have the same id of 6')
}
Example some:
let list = []
list.push({ id: 3, subject: 'Running out of coffee' })
list.push({ id: 6, subject: 'Toner is empty' })
list.push({ id: 8, subject: 'Paper needs to be replaced' })
let all_elements_same_id = list.some(el => el.id === 6)
if (all_elements_same_id) {
log('Some Elements have the same id of 6')
} else {
log('Not one Element has the id of 6')
}
Example forEach:
let list = []
list.push({ id: 3, subject: 'Running out of coffee' })
list.push({ id: 6, subject: 'Toner is empty' })
list.push({ id: 8, subject: 'Paper needs to be replaced' })
log('List:')
list.forEach(el => log(`Element : ${el.id} - ${el.subject}`))
Example forEach with index:
let list = []
list.push({ id: 3, subject: 'Running out of coffee' })
list.push({ id: 6, subject: 'Toner is empty' })
list.push({ id: 8, subject: 'Paper needs to be replaced' })
log('List:')
list.forEach((el, ix) => log(`Element Nr.: ${ix} with Id: ${el.id} - ${el.subject}`))
Example sort:
let list = []
list.push({ id: 3, subject: 'Running out of coffee' })
list.push({ id: 6, subject: 'Toner is empty' })
list.push({ id: 8, subject: 'Paper needs to be replaced' })
let result = list.sort((el_a, el_b) => el_a.subject < el_b.subject ? 1 : -1)
log('Alphabetical List:')
result.forEach((el, ix) => log(`Element Nr.: ${ix} with Id: ${el.id} - ${el.subject}`))
Example filter:
let list = []
list.push({ id: 3, subject: 'Running out of coffee' })
list.push({ id: 6, subject: 'Toner is empty' })
list.push({ id: 8, subject: 'Paper needs to be replaced' })
let result = list.filter(el => el.id < 7)
log('Result List:')
result.forEach((el, ix) => log(`Element Nr.: ${ix} with Id: ${el.id} - ${el.subject}`))
Example map:
let list = []
list.push({ id: 3, subject: 'Running out of coffee' })
list.push({ id: 6, subject: 'Toner is empty' })
list.push({ id: 8, subject: 'Paper needs to be replaced' })
let result = list.map(el => `${el.id} - ${el.subject}`)
log('Result List:')
result.forEach(el => log(el))
Example find: additional parameter index
The second parameter of find, findIndex, every, some, forEach, filter and map is the index of the first parameter in the origin list.
let list = []
list.push({ id: 3, subject: 'Running out of coffee' })
list.push({ id: 6, subject: 'Toner is empty' })
list.push({ id: 8, subject: 'Paper needs to be replaced' })
let search_result = list.find((el, ix) => ix === 1)
log('Result :', search_result.subject) // 'Toner is empty'