How many keywords can you place in a row in javascript?
Inspired by this fun post about C#
I wanted to try the same in javascript. Here’s what I came up with: 15 unique keywords in a row, with no punctuation separating them:
Can you do better? The above code will be successfully parsed by any modern JavaScript engine.
How does it work?
- First we create an async generator function. That opens up the possible keywords we can use to include
return
,await
, andyield
:
async function* foo() {}
2. Next we’ll return an anonymous class, which is possible in ES6:
async function* foo() { return (class {})}
3. Now we’ll extend that class
from an anonymous function. This works because in javascript functions can be used as class constructors. And you can also inherit from them!
async function* foo() { return (class extends (function() {}) {})}
4. Now let’s get the typeof
the whole thing, since that will work on any javascript object or value:
async function* foo() { return typeof (
class extends (function() {}) {}
);}
5. Next, let’s get see if this
is an instanceof
whatever we have so far. this
will always be set to some value in javascript in non-strict mode, whether or not we’re in a class.
async function* foo() { return this instanceof (
typeof (
class extends (function() {}) {}
)
);}
6. Next we’ll check if null
is in
the monstrosity we’ve created so far. in
conveniently works with any javascript object:
async function* foo() { return null in (
this instanceof (
typeof (
class extends (function() {}) {}
)
)
);}
7. We’ll await
the whole mess. We can await
any value whether or not it is a promise:
async function* foo() { return await (
null in (
this instanceof (
typeof (
class extends (function() {}) {}
)
)
)
);}
8. delete void
what we have so far (I actually have no idea why delete void
works — anyone care to explain this one?)
async function* foo() { return delete void (
await (
null in (
this instanceof (
typeof (
class extends (function() {}) {}
)
)
)
)
);}
9. yield
the whole thing, since we can do that with any javascript value!
async function* foo() { return yield (
delete void (
await (
null in (
this instanceof (
typeof (
class extends (function() {}) {}
)
)
)
)
)
);}
10. Let’s make that inner function async
for good measure! Even async
functions can be inherited from (or at least the javascript parser doesn’t mind).
async function* foo() { return yield (
delete void (
await (
null in (
this instanceof (
typeof (
class extends (async function() {}) {}
)
)
)
)
)
);}
11. And finally, let’s new
up that inner class:
async function* foo() { return yield (
delete void (
await (
null in (
this instanceof (
typeof (
new class extends (
async function() {}
) {}
)
)
)
)
)
);}
Now just remove the parenthesis and you’re set!
Now for the real fun: what happens when we throw the above code through Babel? Take a look:
Woooaah boy: