JavaScript functions

Functions are famously called first-class citizens of the JavaScript world. Functions can smoothly be treated as a variable, 

For example, if we execute this in a browser:

function myFunction(a, b) {
  return a * b;
}
var x = myFunction;
console.log(x(3,4));

It will log 12. The declaration of myFunction makes it a 'value', which is assigned to a variable 'x'. Notice that there are no parenthesis in that assignment.
Next, we have a log that invokes myFunction by applying the parenthesis () operator on the variable. The log statement logs the return value of myFunction, which is the product of 3 and 4.

Let's say we forget the parenthesis:
console.log(x);
This will log the function itself! Try it out in your browser by enabling the console display via the 'developer tools' option.

Of course, this will just call the function normally:
var x = myFunction(3,4);
It's just the application of the () operator to call a function.


Comments

Popular posts from this blog

Relationships in a Relational Database

Data Schema and Blobs

JavaScript data-types