What is a function?
A function is a “subroutine” that can be invoked by code external or internal to it. When a function is invoked internally (e.g. called within itself), it is called recursion. A function has a “function body”, which is made up of one or more statements. Functions can have arguments (e.g. a passed in value) and also return a value.
So in short, functions are reusable bits of code that you can call (invoke) at some point in your program to execute a specific task.
Declaring (i.e. creating) a function.
To create a function we “declare” it. A function declaration is also called a function statement. This declaration also “defines” our function and is thus a function definition. Yup, three ways to say the same thing!
Invoking (i.e. calling) a function.
Boom, simple, easy peasy…from our example above let’s invoke!
Simply add “()” to the end of the function you declared and voila, invocation!
Functions are “first class” objects.
Functions create new scope.
Different ways to declare functions: declarations and expressions.
So in our first example above - under declaring a function - we kinda/sorta didn’t paint the entire picture. There are different ways you can declare functions: function expressions and function declarations. In short, starting with the keyword “function” deems a declaration, all other examples are function expressions.
ES6 function expression (e.g. arrow function):
Function expressions can be named or anonymous, function declarations are named by default.
Named function expression:
Function declarations are hoisted.
Because of this, you can use a function before you have declared it. However, do note that function expressions are not hoisted
Functions can take parameters.
The parameters of a function are called arguments (see below for further details).
Functions can access their ‘arguments’.
The ‘arguments’ property is an array-like object that contains all of the arguments passed into the function.
Log the first argument:
Log the number of arguments:
Functions can return values.
Return values can be primitives, references, or other functions.
We have learned the basics of functions, what they are, and how they operate at a high level. We have learned that they can take arguments and return values. Additionally, functions create new scope. We have learned the difference between a function declaration and a function expression, plus we have seen different examples in both ES5 and ES6. Next up, we dive even deeper. Feel free to try out some of your own examples and definitely check out the resources below.