user9542422
user9542422

Reputation:

Why does a function with return gives me undefined when I use it inside module export? node.js

I am practicing some module export exercises using a function with a return statement passed inside a module export then to be imported in a new file, it tells me total is not defined? why is this happening?

Code:

file 1:

// Using Async & Await with MODULE EXPORT.

const googleDat = require('../store/google-sheets-api.js');

//passing a let var from a function to another file
let total = googleDat.addVat(100);
console.log(total);

File 2:

function addVat(price) {
  let total = price*1.2
  return total
};

module.exports = {
  total
};

result:

enter image description here

Upvotes: 0

Views: 501

Answers (2)

Jom
Jom

Reputation: 158

On file 2, you should be exporting the addVat() function itself and not just its return. Try this one:

exports.addVat = (price) => {
  let total = price*1.2
  return total
};

Upvotes: 0

Jordan Breton
Jordan Breton

Reputation: 1327

That's because you export a variable that havn't ben initialized AND you didn't exported your function :


function addVat(price) {
  //defining variable with let work only in this scope
  let total = price*1.2
  return total
};

//In this scope, total doesn't exists, but addVat does.

module.exports = {
  total //So this is undefined and will throw an error.
};

What you want to do is to export your function, not the result inside.


function addVat(price) {
  return  price * 1.2;
};

module.exports = {
  addVat
};

Upvotes: 1

Related Questions