Declarative functions and functions of expressions in JavaScript

- Andrés Cruz

En español
Declarative functions and functions of expressions in JavaScript

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:

Funciones Declarativas vs Funciones de Expresiones en javaScript

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.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.