Variables
One of the main purpose of functions is to avoid code duplication.
/**
* Local variables are visible only inside a function
* A function has full access to an outer variable
*
* Modern code has few or no global variables
*/
let out = 'World';
function hello() {
let msg = 'Hello ' + out;
out = 'Javascript';
}
hello();
console.log(typeof(msg) == "undefined"); // true
console.log(typeof(out) == "undefined"); // false
Return
It is posible to use return without value, in any place the function.
/**
* It is posible to use return without value ...
* which causes the function to exit (returns undefined)
*
* Functions used very often can have ultrashort names,
* but these are exceptions: $() jQuery, _() Lodash
*/
function check(age) {
if (!age) return; // Look Here
if (age > 18) return 'OK';
}
console.log(check()); // undefined
console.log(check(20)); // OK
Readability
A separate function is easier to debug and is also a great comment.
/**
* A separate function act as a great comment
* It good to create functions even if we don't reuse them
*/
function showPrimes(n) {
for (let i=2; i<n; i++) {
if (isPrime(i)) {
console.log(i);
}
}
}
function isPrime(n) {
for (let i=2; i<n; i++) {
if (n%i == 0) return false;
}
return true;
}
showPrimes(10); // 2 3 5 7
Expression
We can create functions, using function expression.
/**
* The common syntax to create a function ...
* is called function declaration
*
* In Javascript, a function is just another type of value
* So, we cand use function expression
*
* Function Expression are created when the exection reaches them
* Function Declaration it's created on initialization stage
*/
let sayHi = function() { // Look Here
console.log('Hello World');
};
console.log(typeof(sayHi)); // function
sayHi(); // Hello World
Arrow
There is another very concise syntax, arrow function.
/**
* Arrow function
*
* It is a shorter form for function expression
*
* Only one parameter, ...
* the parentheses can be omitted
*
* No parameter, ...
* the parentheses should be present
*/
let sum = (a, b) => a + b;
let double = x => x*2;
let pi = () => Math.PI.toFixed(2);
console.assert(sum(1,2) == 3); // pass
console.assert(double(3) == 6); // pass
console.assert(pi() == 3.14); // pass