Understanding the basics of Functions

There’s a saying that I follow, “If you can’t explain it easily, you didn’t understand”. So with that in mind, out of all the concepts that I struggle with I thought I would do my best attempt to explain the basics of functions.

Well what is a function? A function is a subprogram, designed to perform a particular task. Due to the nature of functions, they are executed when they are called for, which is commonly referred to as invoking(executing) a function. Values can be passed into functions and used within the function. The name of the value is called a parameter. The actual value itself is called an argument. Functions always return a value. In JavaScript, if no return value is specified, the function will return undefined.

How to define a function?

There are a few ways to define a function, however before most I would like to add to my earlier statement, that function are also objects. However that’s for another blog post to discuss. Back to the topic, well how does Function Declaration/ aka Function statements differ from Function expressions. When using a function declaration, the function definition is hoisted, which allows the function to be used before it is defined. Whereas Function expression, defines a name or Anonymous function, and are expressions that are not hoisted. Therefore cannot be used before they are defined.

So here’s an example of a Function declaration. As per the example below, the keyword function has been created along with the name used to refer to the function. The name is paired by parentheses that contain a parameter. Following the parentheses are curly braces that contains the body of the function, the purpose of the body is to create some sort of logic or statement for our function to return.

function gymRat(name){return ('you are always at the gym' + name)}gymRat(' Eric')//'you are always at the gym Eric'

Function expression on the other hand defines a name or anonymous function, because the Function expressions are not hoisted, they cannot be used before they are defined, because the function would return a reference error.

let gymRat = function(name){return 'you are at the gym' + name}gymRat(' Eric')
//'you are at the gym Eric'

Because functions declarations and expressions are simply a lot of information to digest, the key components to remember are, Function declarations are hoisted — expressions are not. Functions are executed when they are called. This is known as invoking a function and finally a function always returns a value, if not the function will return undefined by default.