denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples
http://bit.ly/wtfjavascript
Do What The F*ck You Want To Public License
34.75k stars 2.55k forks source link

adding `{}[] ` returns array section #165

Closed hsl0 closed 3 years ago

hsl0 commented 3 years ago

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'

libook commented 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 [].

hsl0 commented 3 years ago

@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 '{'
libook commented 3 years ago

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:

  1. For each expression, it may not return one single value . Where did REPL read the final result?
  2. For each {}, is it block or object?

Also, REPL is different with directly executing files.

hsl0 commented 3 years ago

@libook Then, can it be recorded in WTFJS?