Reputation: 1327
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
}
Upvotes: 0
Views: 1971
Reputation: 138257
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:
If it is however not defined, cities.newyork
will be undefined
which is falsy (will enter the else
branch)
Upvotes: 1
Reputation: 22885
typeof cities.cityName === 'function'
if city's name is assigned to some variable
typeof cities[cityName] === 'function'
Upvotes: 0