Home United States USA — software Easy JavaScript Part 11: Function Expressions and Function Statements

Easy JavaScript Part 11: Function Expressions and Function Statements

268
0
SHARE

A tutorial on the differences between the three ways to create functions in the JavaScript language, and what these functions allow you to do in your code.
In JavaScript, a function can be created in three possible ways:
In this post, we will learn about function expressions and the function statement.
Consider the following code:
The name of the function expression can only be used inside a function body, which is helpful in recursion. A function expression can either be:
The third method of creating a function is by using the Arrow function, which was introduced in ECMAScript 6. You can learn more about Arrow functions here.
Some important points about naming functions are as follows:
A function statement is hoisted at the top of the execution context. Therefore, you can call a function that was created as a statement before it is declared. Consider the following code:
Since the foo function is created as a function statement, it is hoisted and therefore can be called before it is created.
Some important points to remember about hoisting:
A function expression can be immediately invoked (IIFE), which means a function expression can be executed as soon as it is defined. Consider the following code:
Above, we are creating a function expression and immediately invoking it, which is allowed. However, if you try to immediately invoke a function statement, you will get an error. See below:
By using IIFE, we achieve data privacy. Any variable created inside IIFE whether for a function expression or statement cannot be accessed outside.
To call a function inside its own body, you need to create a named function expression. Keep in mind that the name of the function expression is only available in the body of the function, and it is local to the body scope. You can write a function to find the factorial of a number using a named function expression as shown below:
A JavaScript function can be created in three possible ways: function statement, function expression, and arrow functions. In this post, we learned about the function statement and function expressions, but in the next post of this “Easy JavaScript” series, you will learn about another important concept of JavaScript, so stay tuned!

Continue reading...