Member-only story
10 Fundamentals You Need To Know About Functions in JavaScript
Auto-execute after the definition, functions can be closures, and more
Functions are one of the most important concepts in JavaScript. In this article, we will look at the essential things you may need to know about them.
1. Functions Can Be Declared Using the Function Declaration
function compute(){}
When using the function declaration, the function
keyword is the first on the line. The function must have a name and can be used before definition.
Function declarations are moved, or “hoisted,” to the top of their scope. This means we can use a function before it is declared. The following example is a valid usage of a function created with the function declaration:
compute();function compute(){}
2. Functions Can Be Created Using Function Expressions
const compute = function() {};
When the function
keyword is not the first on the line we create function expressions. The name is optional in this case. There can be anonymous function expressions or named function expressions.
Function expressions need to be first defined and then they can be invoked. The following example is not a valid usage of a function expression. Function expressions are not hoisted.
compute();
//Uncaught ReferenceError: Cannot access 'compute' before initializationconst compute = function() {};
3. Functions Can Be Created Using the Arrow Syntax
const compute = () => {};
The arrow function is a sugar syntax for creating anonymous function expressions. As with other function expressions, we cannot use the function before is created. The following example is not a valid usage of a function expression created with the arrow syntax.
compute();
//Uncaught ReferenceError: Cannot access 'compute' before initializationconst compute = () => {};