views:

73

answers:

3

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!

A: 

const (MDC)

And: const (the page you linked...)

jtbandes
+3  A: 

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.

CMS
+2  A: 

There is a const keyword in Javascript, but it isn't recognised by Internet Explorer so you can't really use it.

That's why Google's Javascript style guide recommends either using upper-case letters for a constant, or placing @const into a documentation block.

Both these techniques are advisory only and place no actual restrictions on the code.

Note that when you "compile" some code using Google's Closure Compiler that "compiler" will look at such things in the comment blocks and even generate warnings and errors. But this is separate to running the code unmodified in an actual Javascript interpreter.

thomasrutter