hogashi.*

日記から何から

JavaScriptでは変数名に三点リーダが使えない/識別子におすすめUnicode文字セット

TL;DR

本編

 JavaScript では、変数名に日本語を使ったりできる (使える言語は他にもあると思う) が、三点リーダは使えない (syntax error になる*1 )。

const いろは = 123;
const い… = 123;  // Uncaught SyntaxError: Missing initializer in const declaration
let ろ… = 123;  // Uncaught SyntaxError: Invalid or unexpected token
const= 123;  // Uncaught SyntaxError: Invalid or unexpected token

 MDN を見ると、ブログ記事に詳しいとのこと。

åü などの ISO 8859-1 や Unicode 文字 (詳しくはこのブログ記事を参照) も識別子に使用することができます。

文法とデータ型 - JavaScript | MDN

 ブログ記事を見ると、 ES2015*2での識別子はこう:

  • $_UnicodeID_Start の文字から始める
  • その後は $_ かゼロ幅非接合子*3かゼロ幅接合子*4UnicodeID_Continue の文字
Acceptable Unicode symbols

In ES2015, identifiers must start with $, _, or any symbol with the Unicode derived core property ID_Start.

The rest of the identifier can contain $, _, U+200C zero width non-joiner, U+200D zero width joiner, or any symbol with the Unicode derived core property ID_Continue.

Valid JavaScript variable names in ES2015 · Mathias Bynens

 Unicode を見ると、 ID_StartID_Continue というのは Unicode が用意している識別子用の文字セット詰め合わせみたいなもので、プログラミング言語の変数名などはこれを使うのがおすすめというようなことが書かれている。

These guidelines follow the typical pattern of identifier syntax rules in common programming languages, by defining an ID_Start class and an ID_Continue class and using a simple BNF rule for identifiers based on those classes; however, the composition of those classes is more complex and contains additional types of characters, due to the universal scope of the Unicode Standard.

UAX #31: Unicode Identifier and Pattern Syntax

 三点リーダUnicode でどうなっているか見ると、確かに ID_StartID_Continue には入っていない。というわけで、 JavaScript では変数名に三点リーダは使えないのであった。

 普段の暮らしで妙な変数名にすることはまずないので困らないけど、もし困ったら https://codepoints.net/ で見るとよい、ということがわかった (エラーで気付きそうではある)。
 あと Unicode が識別子用におすすめ文字セットを用意してくれてるのは便利、 Unicode のドキュメントにも書いてあるけどハッシュタグみたいなことをするときにどういう範囲の文字を使うかさっと決められそう。

*1:const の例では書式がおかしいので? 初期化してないよというエラーになっている

*2:https://262.ecma-international.org/6.0/

*3:ゼロ幅非接合子 - Wikipedia

*4:ゼロ幅接合子 - Wikipedia