Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does importing only a single function also runs other functions in that file?

I have this code in the file bmiCalculator.ts


import { isNotNumber } from "./utils";

export default function calculateBmi(height: number, weight: number) {

const bmi = weight / Math.pow(height / 100, 2);

if (bmi < 18.5) {

return "Underweight";

} else if (bmi >= 18.5 && bmi < 25) {

return "Normal (healthy weight)";

} else {

return "Overweight";

}

}

const parseArguments = (args: string[]) => {

if (args.length < 4) throw new Error("Not Enough Arguments");

if (args.length > 4) throw new Error("Too many arguments");



if (!isNotNumber(args[2]) && !isNotNumber(args[3])) {

return {

height: Number(args[2]),

weight: Number(args[3]),

};

} else {

throw new Error("Arguments are not of the correct type");

}

};

const { height, weight } = parseArguments(process.argv);

console.log(calculateBmi(height, weight));

And also this code in the file index.ts


import express from "express";

import calculateBmi from "./bmiCalculator";

const app = express();

app.get("/hello", (_req, res) => {

res.send("Hello Full Stack!");

});

app.get("/bmi", (req, res) => {

const height = Number(req.query.height);

const weight = Number(req.query.weight);

const bmi = calculateBmi(height, weight);

res.send({ weight, height, bmi });

});

const PORT = 3002;

app.listen(PORT, () => console.log(`server running on port ${PORT}`));

I am having this error while running the express server.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error: Not Enough Arguments

But why?? I am not running the parseArgument function. I am only importing the calculateBmi function. So why this error?

Right now, I can only run the code by commenting out the non-exported code in bmiCalculator.ts

>Solution :

Yes, as soon as you import a module (here the module is just a file), it is executed.

If the module contains only exported objects, then there is no side effect.

If the module contains some root level expressions (like const { height, weight } = parseArguments(process.argv); in your case), they are executed. In particular, you should see your next console.log printing.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading