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
}
Radix
  • 2,527
  • 1
  • 19
  • 43
user1hjgjhgjhggjhg
  • 1,237
  • 4
  • 15
  • 34

2 Answers2

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)

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

typeof cities.cityName === 'function'

if city's name is assigned to some variable

typeof cities[cityName] === 'function'

Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60