3

Possible Duplicate:
Maximum length of variable name in JavaScript

While reading on a bit of JS, I thought to myself: how long can my names be?

    function myNormalFuncName () {//...}
    var myNormalVarName = 'how long?';

So my question is how long can it be? Is there any kind of mechanism that stops this from happening, or is there any kind of error thrown? Or maybe even a overflow or something like that? Or will it just work fine?

Maybe it depends more on the implementation? So how about modern browsers.

Would love to hear what skilled developers know about this.

Community
  • 1
  • 1
jeroen
  • 502
  • 8
  • 17
  • There's no reference to the spec in that question I've linked to, but here's [the relevant section](http://es5.github.com/#x7.6). No mention of a maximum length there. – James Allardice Nov 08 '12 at 20:25

2 Answers2

8

Fine for at least 999999 characters

var code = 'var ' + Array(1000000).join("a") + ' = 1;';
eval(code);
alert( window[Array(1000000).join("a")] ); //1
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • 1
    +1 for the creative way to make an insanely long variable name. Just curious what you tested that in. – Jeremy J Starcher Nov 09 '12 at 00:13
  • 1
    @JeremyJStarcher Google Chrome 23, Windows 7 – Esailija Nov 09 '12 at 00:14
  • I wonder if it is dependent on the type of character, some unicode characters need more space in memory compared to others right? Although I don't think this would really give a different limit. – jeroen Nov 13 '12 at 20:44
  • All BMP (The first ~65000 most used characters) characters take 2 bytes of memory per character, characters outside of BMP (very, very rarely used), take 4 bytes. – Esailija Nov 13 '12 at 21:16
0

It would be dependent on the implementations (browser JS engine). It could even be that some implementations of a dynamically typed language (like JS) don't have a limit at all, more then like the limit is imposed by reaching a maximum file size or similar as opposed to maximum characters in function name and/or variable name.

However generally you should avoid 'long' function names and/or variable names, in fact most good compression tools will shorten these for you when run on your JS file. The reason is of course to reduce the amount of bandwidth required to download resources (like JS files) to the browser when visiting your site.

ramsinb
  • 1,985
  • 12
  • 17