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だけです。
letやconstでは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で定義したはずの変数をlet・constで上書きするという荒業が可能になります。
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されているはずのxを直接上書きできてしまいました。
もちろん、evalを通さず直接varした変数はこれまでどおり再定義できないままです。
ということでこの機能、実はChrome・Firefox・Safariいずれも既に実装されています。
従って、おそらく最初のES2026になると思われます。
今後はeval(var)した変数を直接上書きできるようになりますね。
感想
ニッチすぎて使いどころがわかんねえ。