Defining a function 38
Functions have an expression and a body and parameters The keyword function is used to define the value that the function binds the block below (that always must be wrapped in braces this way) to the value.
Functions can have no parameters or many parameters.
Some functions produce a value and some don't.
The functions that produce a value use return
to return the value from the function.
return statements without an expression or functions without a return statement will return undefined
.
The Parameters given behave like bindings, but are given by the caller of the function, not in the function itself. Unless you do something dumb like overwrite the parameters inside the function.
const square = function(x) {
return x * x;
};
console.log(square(12)); //144
Bindings and scopes 39
Each binding has a scope. If you define the binding outside of any function, block or module, you declare a global scope
.
If you define a binding within a function, you create a local scope
.
This means you can treat each function as it's own little environment that has little to no knowledge about the outside of the function.
Each scope can look out into the scope around it. notice that when we call this function, the value of n is different inside and outside the function.
const halve = function(n) {
return n / 2;
};
let n = 10;
console.log(halve(100));
// → 50
console.log(n);
// → 10
Nested scope 40
Functions within functions can create nested scopes. This is called lexical visibility
.
Functions as values 41
You can bind functions to values. Take this for example:
let launchMissiles = function() {
missileSystem.launch("now");
};
if (safeMode) {
launchMissiles = function() {/* do nothing */};
}
Declaration notation 42
Another way to declare a function is to use declaration notation
function square(x) {
return x * x;
}
Arrow functions 42
A third way define a function is with an arrow function. The logic is that "these parameters produces the result"
const roundTo = (n, step) => {
let remainder = n % step;
return n- remainder + (remainder < step / 2 ? 0 : step);
};
You can also call with one parameter and drop the parenthesis. If you have one line, you can drop the braces as well.
const square1 = (x) => { return x * x; };
//becomes
const square2 = x => x * x;