6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】変数はdeleteもletもできないが`eval(var)`だとdeleteできるがletできないけどできるようになる

Posted at

delete演算子はオブジェクトのプロパティを削除する演算子です。

const Employee = {
  firstname: 'Maria',
  lastname: 'Sanchez',
};

console.table(Employee);
 // {firstname: 'Maria', lastname: 'Sanchez' }

delete Employee.firstname; // true

console.table(Employee);
 // {lastname: 'Sanchez' }

プロパティfirstnameが削除されました。

ところで変数はdeleteできません。

var hoge = 1;
console.log(hoge); // 1

delete hoge; // false
console.log(hoge); // 1

let hoge = 2; // SyntaxError: Identifier 'hoge' has already been declared

なに当たり前だろうって?

実は当たり前ではない遷移がひとつ存在するんですよ。

eval("var hoge=1;");
console.log(hoge); // 1

delete hoge; // true ←
console.log(hoge); // Uncaught ReferenceError: hoge is not defined

なんで?

evalで設定した変数については、delete削除することができます

なお、この謎の記法が使えるのはvarだけです。
letconstではevalを抜けたところで変数が消滅します。

eval("let   foo=1;");
console.log(foo); // Uncaught ReferenceError: foo is not defined

eval("const bar=1;");
console.log(bar); // Uncaught ReferenceError: bar is not defined

さて、これを使うとvarで定義したはずの変数をletconstで上書きするという荒業が可能になります。

eval("var x=1;");
const x = 2; // Uncaught SyntaxError: redeclaration of var x

delete x;
const x = 3; // x=3になる

deleteしてからletすることで実質上書きとなります。
ただし、deleteせずに直接上書きすることはできません。

とまあ今まではこういう動きだったのですが、どうせ削除して書き換えができるのなら最初から上書きできてもいいじゃん、というproposalが提出されました。

Make eval-introduced global vars redeclarable

eval("var x=1;");
const x = 2; // OK!

var y = 1;
const y = 2; // Uncaught SyntaxError: Identifier 'y' has already been declared

varされているはずのを直接上書きできてしまいました。
もちろん、evalを通さず直接varした変数はこれまでどおり再定義できないままです。

ということでこの機能、実はChrome・FirefoxSafariいずれも既に実装されています。
従って、おそらく最初のES2026になると思われます。

今後はeval(var)した変数を直接上書きできるようになりますね。

感想

ニッチすぎて使いどころがわかんねえ。

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?