Question:
In a simple 'chat' project, which I've used and works 100%, you use
const express =require('express');//para http
const app = express();//instancia
const http = require ('http').createServer(app);
const io = require('socket.io')(http);
I already looked for a specific answer, but I still haven't found the meaning of applying that 'http' object in parentheses, in ('socket.io')(http).
What do these parentheses mean? Mean an anonymous function associated with require?
I don't understand how this works and thus when to use it.
Answer:
This is a high order function , basically it's a function that returns a function and executes the returned function.
As we can see in the following example:
function soma(a,b){
return a+b;
}
function subtracao(a,b){
return a-b;
}
function multiplicacao(a,b){
return a*b;
}
function retornaAlgumaOperacao(op){
switch(op){
case '+': return soma;
case '-': return subtracao;
default: return multiplicacao
}
}
console.log(retornaAlgumaOperacao('+')(1,1));
console.log(retornaAlgumaOperacao('-')(1,1));
console.log(retornaAlgumaOperacao('*')(1,1));
Note that the function retornaAlgumaOperacao
does not know which operation it will return, but it knows that it will be a function that will perform an operation with two parameters. When this function is returned, we know that we have to send two parameters to perform the operation.
This increases readability for code that would execute chained functions, for example.
In the specific case of socket.io, the second parameter is for it to return a Server , where the first parameter says where the socket will be tied.