My Journey to Learning Javascript: Notes- Functions


Functions are used to enclose a block of code that performs a certain task. Functions are created using (function) followed by the (function name) and data that is required to be passed- called a parameter enclosed in parenthesis. Open and closed curly braces are then added to enclose the code that is to perform the task.


function myBlog(*parameter*){
// code
}


A function parameter is an item of data that the function needs to be given in order to do its job, it will always be enclosed in parentheses. Even if no parameter is used, parentheses still need to be included following the function name.


Functions can later be called by using the function name followed by the parameter in braces, which will then execute the code inside the curly braces.


*Functions are called first class citizens meaning they may be treated as any other value.


Scope



Any code inside a function can only be used inside that same function, meaning that it does not exist out of it. You cannot access code that exist inside a function to be used by another. This is called functional scope, it is recommended because it cannot be access by outside code so it cannot be changed.


Functions and variable defined outside of functions however, may be used by all javascript code on the page, also called global scope. Global scope is not recommended because it can mistakenly be changed by other code which will then cause already written code to malfunction.