D
D
drinkcsis2012-09-05 10:04:07
JavaScript
drinkcsis, 2012-09-05 10:04:07

What is this JavaScript somevar:'sometext' construct?

In one comment to my article there was a link from MrSLonoed to a video where the guy told and showed examples of type casting. Among other examples was

{}+[] //0

User HDg suggested that {} in this case is not an object, but a block of code.
Just on the same day, my colleague had a question related to the same situation as in the example above. The question was: “Why is SyntaxError: Unexpected token: thrown when writing the following construction in the browser console {a:'a',b:'b'}? It's an object! ". I said that this is because, in the absence of other operators, curly brackets are perceived as a code block, and not an object declaration, that is, it's the same as just writing a:'a',b:'b' in the console.
Accordingly, now I have a question:
If you write simply {a: 'a'} - this is also not an object declaration, but the command a: 'a' will work and return the string "a". What is a:'a' ??
Dear Khabrovtsy, explain what this construction gives? Thank you all in advance!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
H
HDg, 2012-09-05
@HDg

This is the label for goto

H
HDg, 2012-09-05
@HDg

If you want to declare an object at the beginning of a line, then you just need to enclose it in parentheses: ({a:'a'})

D
drinkcsis, 2012-09-05
@drinkcsis

Wow... there was never a need for labels in JS)) I didn't even think about it, since goto doesn't seem to exist in JS!? But I see they can be cleverly manipulated, up to such a moment

top: 
{
  a=5
  break top
  a=10
}
alert(a) // 5

that is, they can not only be put into cycles, but also directly into code blocks ... Interesting. Thank you!

K
Kir ---, 2012-09-06
@SowingSadness

>>> {'a'}+[]
0
>>> {return 0}+[]
0
>>> ('a')+[]
"a"
>>> {return 'a'}+[]
"a"
>>> ({'a':'a'})+[]
"[object Object]"
>>> {return ;}+[]
undefined

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question