0

I have created a module and defined functions in it. Sometimes I need to check if a certain function is actually already created.

For example

var newyork = function() { 
   console.log("newyork");
};

var washington = function() { 
   console.log("washington");
};

exports.newyork = newyork;
exports.washington = washington;

Now in the different file, I want to first check if the function exists, something like:

var cities = require('./city');

if(cities.newyork) {
  console.log("city function exist");
}
else {
  //false
}
5
  • 4
    "something like" actually works. Commented Jul 24, 2018 at 19:33
  • @JonasW. really omg? Commented Jul 24, 2018 at 19:33
  • Yes, Javascript is cool Commented Jul 24, 2018 at 19:35
  • @JonasW. 1) That 2) is 3) arguable. Commented Jul 24, 2018 at 19:39
  • @alexL do you really wanna argue or ... ? ;) Commented Jul 24, 2018 at 19:48

2 Answers 2

1

As I said in the comments what you wrote actually works because

if(cities.newyork){

Checks if cities.newyork is truthy. The following things are truthy:

  • functions (thats why it works here)
  • numbers except 0
  • strings except an empty one
  • objects / arrays

If it is however not defined, cities.newyork will be undefined which is falsy (will enter the else branch)

Sign up to request clarification or add additional context in comments.

Comments

0

typeof cities.cityName === 'function'

if city's name is assigned to some variable

typeof cities[cityName] === 'function'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.