Hello friends, in this article we will learn how to call constant from another file in javascript.

Scenario

You have a large javascript code and need to maintain all constants in a separate javascript file. You have to use the constants written in one file to be used in another file.

Quick answer

//constantFile.js
var CONSTANT = function() {
    var months = {
        'shortMonthNames': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
        ],
        'longMonthNames': ['January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'
        ]
    };

    var weatherServiceParameters = {
        'WeatherWebServiceURL': 'www.google.com',
        'WeatherWebServiceAppId': '123234345',
        'WeatherWebServiceConsumerKey': 'asdf-a4dr-fgh5t-ert6',
        'WeatherWebServiceConsumerSecret': '123sdf345dfg'
    }

    return {
        months: function(name) {
            return months[name];
        },
        weatherServiceParameters: function(name) {
            return weatherServiceParameters[name];
        }
    };
}();

//anotherFile.js
console.log(CONSTANT.months('shortMonthNames'));
console.log(CONSTANT.months('longMonthNames'));
console.log(CONSTANT.weatherServiceParameters('WeatherWebServiceConsumerKey'));

Output