Skip to content Skip to sidebar Skip to footer

How To Check If Module Function Exist In Node Js

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

Solution 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)

Solution 2:

typeof cities.cityName === 'function'

if city's name is assigned to some variable

typeof cities[cityName] === 'function'

Post a Comment for "How To Check If Module Function Exist In Node Js"