Skip to content

Instantly share code, notes, and snippets.

@tkihira

tkihira/null.js Secret

Last active October 24, 2022 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkihira/808ca736e6ff289844c65bbfd3ce5fe5 to your computer and use it in GitHub Desktop.
Save tkihira/808ca736e6ff289844c65bbfd3ce5fe5 to your computer and use it in GitHub Desktop.
How to make `null` value without using `null` literal
// pattern 1: eval or parse
console.log(eval("null"));
console.log(JSON.parse("null"));
console.log(JSON.parse(JSON.stringify([undefined]))[0]);
// pattern 2: Date.prototype.toJSON
console.log(new Date(NaN).toJSON());
// pattern 3: RegExp related
console.log(/a/.exec(""));
console.log("".match(/a/));
// pattern 4: retrieve prototype of Object.prototype (by azu san)
console.log(Object.prototype.__proto__);
console.log(Object.getPrototypeOf(Object.prototype));
console.log(Reflect.getPrototypeOf(Object.prototype)); // by Yosuke HASEGAWA san
console.log(Object.__proto__.__proto__.__proto__); // by Yosuke HASEGAWA san
(function foo(){ console.log(foo.caller)})(); // by Yosuke HASEGAWA san
@tuchida
Copy link

tuchida commented Oct 24, 2022

document.allをECMA262に含めてよいのであれば、これでもnull値を作れるようです。

document.all[Symbol.replace] = document.all;
"".replaceAll(document.all);

ref. https://github.com/tc39/test262/blob/b5d3192914e9b107ce4f5df4f77e625865d337c7/test/annexB/built-ins/String/prototype/replaceAll/custom-replacer-emulates-undefined.js#L19-L29


(追記)このTest262のテストケースはIf replacer is not undefined, thenを確認するためのもので、document.all()がnullを返すことはECMA262の仕様の範囲外なので、本問題の回答としては不適切かもしれません。
お騒がせして申し訳ありませんでした。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment