Functions By Chloe
Declaring Functions
To declare a function, you use the following syntax:
function functionName(parameter){
//code to be executed
}
The functionName should give the developer a clue as to what the function does, so that other developers can easily read the code.
function hello(){
console.log(Hi, how are you?);
}
function number(a){
return a;
}
function add(a, b){
return a+b;
}
Function Expressions
This is when a function is assigned to a variable. When using the function expression you can remove the function name - making it an anonymous function - this makes the code more concise.
var sum = function add(a, b){
return a+b;
}
Without the function name:
var sum = function(a, b){
return a+b;
}
To call upon the function expression you would do:
sum(2, 5) => 7
Arrow Functions
Arrow functions are a newer method in javascript they are always anonymous functions and a type of function expression. They are a way to make the code even more concise.
var sum = (a, b) => {
return a+b;
}
var num = x => {
return x;
}
If there is no parameter included, you must include the empty ():
var hello = () => {
console.log("Hi there!");
}
As the above example are only a one line return, they can be reduced down even further by removing the return keyword and curly brackets:
var sum = (a, b) => a+b;
How you write arrow functions is personal preference as all of them will give the same result.