Functions are named portions of code that can optionally accept arguments and return values.
Defining functions
Functions are defined using the 'function' keyword, followed by the name of the function, and the list of arguments that the function accepts enclosed in parentheses. The function's statements are inclosed within curly braces following the function definition. Inside the function, the 'return' keywork can be used to indicate that a value should be returned to the calling program.
Variable scope
Variables declared inside a code block are only accessible inside that block. These variables are called local variables, and are referred to as having a local scope. Global variables, on the other hand, are not declared inside a code block, and are accessible throughout the entire script.
Returning values
Functions can return values by using the 'return' keyword, followed by the value to be returned.
Where to put functions
Generally, functions are placed within the <head> tag to ensure that they are fully loaded before being called.
Code layout
Whitespaces (tabs, spaces, returns, and so on) do not affect the execution of JavaScript statements, so they can be used to make code readable. The most important consideration is picking a style and remaining consistent. However, a good starting point is to indent code blocks (such as those under conditionals or looping statements) by one tab space.