Functions are blocks of code that are used for the following attributes
- To execute multiple lines of code together
- To avoid replication of code
- To enhance code re-usability.
- Functions take parameters and return value after performing some operation.
- Parameters use local copy of the values passed when function is called.
- function should me made wholly for single functionality (see : Single responsibility principle)
- If two functionalities are enclosing in a function divide them in two functions.
- Mostly aim at functions with no side effects.
Thus Functions are chunks of code which when given some input may produce output of some form and might also return value.
Naming conventions
- Functions must be named as verbs as they are actions.
- Verbal prefixes
Variables in relation to Functions
- local variables belong to functions’ body and global ones stay outside of them.
- local variables overshadows global variables
let variable1='forty';
function showMessage(){
variable1=40;
console.log(variable1+'This is inside the showMessage');
}
showMessage();
console.log(variable1 + 'This is outside showMessage');- Avoid usage of global variables as much as possible