Functions in ES5
There are two ways to write functions in ES5, and both variations produce essentially the same outcome.
In a Function Declaration (sometimes referred to as a “named” function), we use the function keyword to declare our function, give it a name (sum in the example below), and use the return keyword to return the result of our statement in the code block.
Function Expressions (aka “Anonymous” functions) have many of the same characteristics as function declarations (basic structure, function and return keywords, etc.). However, we store function expressions in a variables, and terminate them with a semicolon (as we do with all variables in JavaScript).
What’s the Difference Between a Function Declaration and a Function Expression?
The key difference between function declarations and function expressions has to do with hoisting. Function declarations are hoisted by the browser when your script initially runs. In other words, any named functions you have in your script will be hoisted to the top of your code and interpreted before any other code is executed.
This means that you can actually call a named function before you’ve declared that function it in your code. Check out the example below:
Functions in ES6
We can still use both of the ES5 function types outlined above, but ES6 also introduced Arrow Functions to the JavaScript landscape. Arrow functions provide a simplified structure, allowing for a more concise way to write function expressions.
The syntax of an arrow function does away with the function keyword and instead uses a => symbol, which is placed to the right of the parentheses containing your parameters.
Arrow functions also come with some nifty shorthand options we can use to make things even more concise, depending on the required structure of our functions.
If you’d like to dive deeper into ES6 Arrow Functions and learn more about when and how you can use them, check out some of these resources and tutorials:
JavaScript: Arrow Functions for Beginners - codeburst.io
A Tutorial to JavaScript Arrow Functions - Flavio Copes
Arrow functions - MDN web docs
When (and why) you should use ES6 arrow functions — and why you shouldn’t - freeCodeCamp
Thanks for reading! If you’re interested in learning more about the fundamentals of HTML, CSS, and JavaScript, follow my Medium publication, Web Dev Basics. Ready to write some code? Sweet! Sign up for course and learn the basics of web development.
Top comments (1)