How to declare a function in the form of Arrow Function?

Asked

Viewed 76 times

-2

How to declare the function below as Arrow Function in javascript Ecma 6 and then call it? Currently I use it like this and do not know how it leaves working without the "Function" in front.

execSQLQuery('DELETE FROM Usuarios WHERE idUser=' + parseInt(req.params.id), res);


function execSQLQuery(sqlQry, res){
       const connection = mysql.createConnection({
        host     : 'localhost',
        port     : 3306,
        user     : 'joao',
        password : '123',
        database : 'dadosD'
    })   
    connection.query(sqlQry, (error, results, fields)=>{
        if(error) 
          res.json(error);
        else
          res.json(results);
        connection.end();
        console.log('executou!');
    })
  };

  • 1

    Why do you want to declare this function as Arrow Function?

1 answer

0


I don’t think there’s any need to do that, it won’t make any difference in the code. But...

Arrow functions are anonymous functions, that is, they have no name. To identify them, you need to assign it to some label, in case a variable.

That way:

const execSQLQuery = (sqlQry, res) => {
...
};

But if you do, you will have a ReferenceError, whereas statements let or const has not Hoisting. Therefore, you have to move the declaration to before invoking it. In case:

const execSQLQuery = (sqlQry, res) => {
...
};

execSQLQuery('DELETE FROM Usuarios WHERE idUser=' + parseInt(req.params.id), res);

(Note that you are now below)

  • 1

    Good Luis, I am studying deeply the Ecma6 and you answered very well, that’s exactly what I needed to know, ball show! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.