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