Search code examples
node.jsvuejs3module-export

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


Solution

  • 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
    };