Different Ways to Declare Functions
If you are like me, you learned ES5 where you just var
all the things, wrote everything out without shortcuts, and you are totally confused by arrow functions. Here are some of my notes from Wes Bos’ Javascript beginner course Module #2 on Different ways to declare functions.
Traditional function declaration:
This is a standard declared function, also known as a “First Class Citizen”, meaning it can be declared as a value that can be passed into other functions.
function doctorize(firstName) { return 'Dr. ${firstName}'; }
Anonymous (Anon) function declaration:
This is a function without a name, this isn’t valid but it can be used in a callback but this can be stored as a value known as a function expression (the next topic)
function (firstName) { return 'Dr. ${firstName}'; }
Function Expression
This is a valid way to use an anonymous function. This allows you to re-use the function and leverage “hoisting”.
const doctorize = function (firstName) { return 'Dr. ${firstName}'; }
Note: Hoisting is how Javascript moves functions to the top of the file so it can be run before it’s defined.
Arrow functions
These are anonymous functions but shorter. Here is an example of a traditional function declaration we can convert to an arrow function. Basically avoid extra words. Note this method creates issues when using this
method.
function inchToCm (inches) {
const cm = inches * 2.54;
return cm;
};
This is the same as the above but in Arrow function format:
const inchToCm = inches => inches * 2.54;
Note: If you only have one parameter (in this case inches) you don’t need to use the parenthesis for (inches) as shown above but would be necessary in a traditional function like below when converting to an arrow function:
Here is an example with two parameters :
//traditional format const ab = function add (a, b) { const total = a + b; return total; };
//arrow function format const ab = add (a, b) => a + b;
Note: If you try to run the function above without the parenthesis around the
(a, b)
parameters, you will get an error.
IIFE (Immediately Invoked Function Expression)
Woah, lots of words here right? Hopefully, this will clear things up! Note these parentheses:
(function () {
console.log{'This is an Anonymous Function'};
};)()
When you run this, the function is inside parenthesis meaning it’s going to run everything inside of the first, then because it’s followed by ()
it will call that function and initiate it.
Leave a Reply