Search code examples
javascriptgoogle-closure-compiler

@const in javascript?


I was reading http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml when I noticed in the Constant section with the annotated comments:

/**
 * The number of seconds in each of the given units.
 * @type {Object.<number>}
 * @const
 */

and then the guide goes on with "This allows the compiler to enforce constant-ness."

Is this a v8 thing? where is this documented?

My mind is giddy with the possibility that maybe, just maybe, i can provide v8 (or whatever) with type information!


Solution

  • The Google's Closure Compiler can accept JSDoc comments, and it will generate warnings or errors.

    For example, if you try to compile the following code with the Advanced Optimization:

    /** @const */ var MY_BEER = 'stout';
    
    MY_BEER = 'bar';
    

    It will generate an error:

    Number of errors: 1

    JSC_CONSTANT_REASSIGNED_VALUE_ERROR: constant MY_BEER assigned a value more than once at line 5 character 8

    They discourage the const keyword because it is not part of the ECMAScript Standard.