DEV Community 👩‍💻👨‍💻

Grzegorz Kućmierz

Posted on

What can be max const name in JavaScript?

This post is about maximum length of variable name in JavaScript.

`2 ** 29 - 63`

Pretty long variable name, huh?

It is more than 500 megabytes!

I don't know why is that exactly, but I precisely checked this using bisection algorithm.

``````1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
262144
524288
1048576
2097152
4194304
8388608
16777216
33554432
67108864
134217728
268435456
536870912
402653184
469762048
503316480
520093696
528482304
532676608
534773760
535822336
536346624
536608768
536739840
536805376
536838144
536854528
536862720
536866816
536868864
536869888
536870400
536870656
536870784
536870848
536870880
536870864
536870856
536870852
536870850
536870849
'maxConstName', 536870849
``````

Here is code, that I wrote.

``````const naturalSearch = (cond, retFirstTrue = true) => {
let min = 1;
let max = 1;
while(1) {
const stop = cond(max);
if (stop) break;
min = max;
max *= 2;
}
let mid;
while (1) {
mid = Math.floor((min + max) / 2);
const stop = cond(mid);
if (stop) {
max = mid;
} else {
min = mid;
}
const diff = max - min;
if (max - min <= 1) {
return retFirstTrue ? max : min;
}
}
};

const checkConstName = n => {
console.log(n);
try {
const name = 'a'.repeat(n);
new Function(`const \${name} = 5;`)();
return false;
} catch (e) {
return true;
}
return false;
};

const maxConstName = naturalSearch(checkConstName, false);

console.log('maxConstName', maxConstName);
``````

Junxiao Shi

I checked the ECMA-262 Standard edition 5.1. There isn't a limit on `Identifier` length. What you found is specific to the engine implementation you are using.

Grzegorz Kućmierz

Thank you for explanation

Dream Big

Use any Linode offering to create something unique or silly in the DEV x Linode Hackathon 2022 and win the Wacky Wildcard category.

Join the Hackathon <-