Closed hsl0 closed 3 years ago
a={foo: 'bar'}['foo'] // a='bar'
a={}[] // Uncaught SyntaxError: Unexpected token ']'
{foo: 'bar'}[] // []
a={foo: 'bar'}[] // Uncaught SyntaxError: Unexpected token ']'
{foo: 'bar'}['foo']
means read the value of 'foo'
key from object {foo: 'bar'}
.
But if there is no item in the array, they will be one emty object {}
and one empty array []
for JS engine. Just like {};[];
.
> (()=>({}[]))()
(()=>({}[]))()
^
Uncaught SyntaxError: Unexpected token ']'
> (()=>({}['foo']))()
undefined
> (()=>({foo:'bar'}['foo']))()
'bar'
> (()=>({foo:'bar'}[]))()
(()=>({foo:'bar'}[]))()
^
Uncaught SyntaxError: Unexpected token ']'
I did some "return test" with functions. You can see:
It was not {}[]
returned []
; it was []
returned []
.
@libook hadn't mean "{}[]
returns array, but {foo: 'bar'}['foo']
returns 'bar' in node.js" is strange, but I meant "{}[]
returns array and {foo: 'bar'}['foo'] returns array in browser console" is strange as I wrote in README.
Anyway, thanks for letting me know how this happened! You didn't answer the intended question, but the answer could explain my curiosity.
I want to know one more thing, how {}{}
returns undefined in console, instead of returning object or throwing error? Is it strange behavior? (Chromium, node)
{}{}; // undefined
{}{}{}; // undefined
{}{}{}{}; // undefined
{foo: 'bar'}{}; // 'bar'
{}{foo: 'bar'}; // 'bar'
{}{foo: 'bar'}{}; // 'bar'
{a: 'b'}{c:' d'}{}; // 'd'
{a: 'b', c: 'd'}{}; // SyntaxError: Unexpected token ':'
({}{}); // SyntaxError: Unexpected token '{'
Yes, they are strange.
There are 2 meaning for {}
: object and block.
For example, the {}
in ()=>{}
means block. So we need to use ()=>({})
to return an object.
So there are 2 questions:
{}
, is it block or object?Also, REPL is different with directly executing files.
@libook Then, can it be recorded in WTFJS?
I found this simple strangeness of javascript!
I have tested it on Chromium Edge, Chrome, Firefox and IE. In node.js,
{}[]
returns array, but{foo: 'bar'}['foo']
returns'bar'