Arguments in function (Javascript - ES5)


I have the following code:

function leerTexto (nombre, callback) {
 process.nextTick(function () {
  var contenido = fs.readFileSync(nombre)

Leaving aside what the code does, I would like to know why the callback argument can be put as '' a type of function '' or something like that inside the readText function. I do not need to know what it does or why it makes things work, the only thing I would like to know is how, or what form the '' callback (content.toString ()) '' is made in that way, since It's strange because I've never seen an argument like that before. In advance, thank you very much.

asked by Ricardo A 05.03.2017 в 22:03

3 answers


The only thing that I would like to know is how, because or in what way the callback(content.toString()); is made

In JavaScript almost everything is an object since everything inherits from Object.prototype The functions are not the exception and that is why you can pass them as parameters, save them in an array, a set, map, etc.

When you pass a callback what you're going through is the definition of that function, that is, as such, an object, as if you passed a literal object ( { clave: valor } ), the instance of a class or a type of primitive data. Once inside the primary function, you can handle it like any other type of data or execute it.

It should be noted that a callback is also a closure ; that is, define one function within another. This allows you to recognize the environment in which it was created.

answered by 05.03.2017 в 22:29

Adding to what Guz explained that this feature of Javascript that marks is due to the programming paradigm functional.

Javascript is a multi-paradigm language, this means that you can program with different approaches, thanks to the versatility of the language: Procedural, Object Oriented (prototyping) or functional.

All functional programming languages comply with a feature that are Higher Order Functions . This means that a function can take another function as an argument and, in addition, all functions can return a new function as a result. It is a very powerful feature of Javascript that allows us to enter the world of functional programming.

answered by 05.03.2017 в 22:41

Function declaration leerTexto expects (and demands) a function as the second parameter.

When invoked, that second parameter can be an existing function:

var loguear=function(texto) {

leerTexto('archivo.txt', loguear);

How can it be a closure (mentioned in the other answers) that you define at that moment:

leerTexto('archivo.txt', function(texto) {

In the case of the example that you propose, if a function is not given as a second parameter, leerTexto will throw an error.

answered by 06.03.2017 в 13:25