Empty Function
function SimpleFunction() {
}
SimpleFunction();
Basic example with an input and a output
function MyFunction(input) {
console.log(input);
const output = 'Output';
return output;
}
MyFunction('Input');
console.log(MyFunction('Input'));
Assign a function to a variable
const square = function (x) {
return x * x;
}
console.log(square(3));
Example of how scope works with functions
const convertToFahenheitToVelsuis = function(fahenheit) {
let celsius = (fahenheit - 32) * 5 / 9;
if (celsius <= 0) {
const isFreezing = true;
}
try {
// This will throw an exception
// Scope within functions work the same as in conditional statements
console.log(isFreezing);
} catch(e) {}
return celsius;
};
try {
// Functions create local scope
// Variables created within that scope are bound inside it and are not globally accessable
// This will thrown an exception
console.log(celsius);
} catch(e) {}
const result = convertToFahenheitToVelsuis(32);
console.log(`result=${result}`);
Passing multiple parameters into a function
const multi = function(a, b) {
return a + b;
}
console.log(multi(1, 2));
Null Arguments Passed in
const noValues = function(a, b) {
return a + b;
}
if (isNaN(noValues()) ) {
console.log('NaN returned when no parameters provided');
}
Default arguments - prevents errors occuring from wrong parameters being passed into a function
const defaultParams = function(a = 0, b = 0) {
return a + b;
}
console.log(defaultParams());
(todo)