-1

I have an index.js where I import a module:

const msg = require('../server/email/sendMail');

console.log(msg);

In my sendMail file I have:

// sendMail.js

function main() {
  return 'message'
}

module.exports = {main};

When I run the index.js file I get:

{ main: [Function: main] }

I expected the string message to be shown in the log.

Peter Boomsma
  • 8,851
  • 16
  • 93
  • 185
  • 2
    It's *you* who is not calling the function. Node doesn't randomly execute variables as functions without being told to. Either do `console.log(msg())` or export the result of calling the function. I don't know which one you want here. – VLAZ Apr 29 '22 at 14:23
  • *"I expected the string message to be shown in the log."* - Why? Where do you execute your `main()` function? The function is defined, and imported, but where specifically is it executed? – David Apr 29 '22 at 14:25
  • 1
    https://stackoverflow.com/q/7969088/438992 – Dave Newton Apr 29 '22 at 14:28
  • 1
    @PeterBoomsma It’s a pretty reasonable question—you’re calling other functions (`require` and `log`) but not the one you’re asking about—understanding why the expectation was there is often helpful when explaining. – Dave Newton Apr 29 '22 at 15:24

1 Answers1

1

To run a function you need to add () at the end of the function name:

msg()

So you need to do:

console.log(msg())

On the other hand, to pass the function around as a variable (not run it) instead of the result of the function you don't add the ():

let a = msg
let b = msg()

// a is now the function
// b is the string "message"

console.log(a()) // prints 'message'
slebetman
  • 109,858
  • 19
  • 140
  • 171