Normally when we develop our JavaScript scripts we use functions for everything and in this way modularize our programs as much as possible; although the JavaScript API has another component very similar to the typical functions we know in JavaScript called declarative functions, this other component is known as expression functions in JavaScript.
Expression functions in JavaScript
Surely you have noticed in other Blogs or help forums when looking for any tutorial or help on how to use a JavaScript component the following way to declare a function:
var sumar = function (a,b) {return a+b;}
And this other one which is the most known and used (in part it must be because it is the basic syntax used in any programming language) called declarative functions:
function sumar (a,b) {return a+b;}
Both declarations of functions that are obviously not syntactically the same cause the JavaScript compiler to treat it differently; let's do some more tests on the results:
console.log(suma(2,3));
var sumar = function (a,b) {return a+b;}
Results:
TypeError: undefined is not a function
And this one better known:
console.log(suma(2,3));
function sumar(a,b) {return a+b;}
Results:
5
What is the difference between the two previous code sections?
Both forms that we saw previously are valid statements of a function in JavaScript but with a different format and therefore with a different behavior:
Then we can reference a function by means of a variable or using the name of the function directly; The interesting thing is not its syntax that differs from one to another if not how the JavaScript compiler interprets it which I will try to explain through the next code section:
console.log(suma(2,3));
function sumar(a,b) {return a+b;}
The last expression of the function called "adds" the JavaScript compiler makes it:
function sumar(a,b) {return a+b;}
console.log(suma(2,3));
That is to say; The compiler places the definitions of the functions and places the function at the beginning of the code; In other words, the JavaScript compiler converts the statement seen previously in a global scope to the entire program that only corresponds to a defined section of the program.
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter