JavaScript constants: declaration and use

As of JavaScript 1.5, constants can be declared and used in your scripts. The Mozilla's JavaScript reference provides the following description of constants:

Creates a constant that can be global or local to the function in which it is declared. Constants follow the same scope rules as variables. The value of a constant cannot change through re-assignment, and a constant cannot be re-declared. Because of this, although it is possible to declare a constant without initializing it, it would be useless to do so. A constant cannot share its name with a function or a variable in the same scope. const is a Mozilla-specific extension, it is not supported by IE, but has been partially supported by Opera since version 9.0 and Safari.

Mozilla Developer Center

So here's an example:


function Class() {

    const baseURL = 'http://onwebdev.blogspot.com/';
    
    this.createRelativeAjaxURI = function() {
    
      var url = location.href;
      var ajaxURI = url.replace(baseURL, '');
      
      return ajaxURI;
    
    
    }

}

You can also declare constants at the top of your scripts, though this is considered a poor practice due to the likelihood of namespace collisions.

Leave a Reply

Note: Only a member of this blog may post a comment.