var so = {name: 'stack'}['overflow'];
undefined
What is this expression exactly doing? Neither the console produces any errors nor so contains any data.
UPDATE
{name: 'stack'}['overflow'] in console it prints ["overflow"]{name: 'stack', location: 'somewhere'}['overflow'] gives error Uncaught SyntaxError: Unexpected token :(…){name: 'stack'} is called an Object literal, which has a property called name and its corresponding value is stack.
{name: 'stack'}['overflow'] is trying to get the value for the property overflow from the object literal.
Since the property is not there in the object, by default, undefined is returned and that is stored in the variable so.
In the Console,
{name: 'stack'} is being treated as a block and name: is considered as the label statement. Since there is nothing happening inside that block, it simply returns ['overflow'] as it is.
If you want that to be evaluated as a single expression, then you need to wrap that in parenthesis, like this
({name: 'stack'}['overflow'])
// undefined
In the second case, it sees a label in the block, name:, and then it sees 'stack', location: 'somewhere', which is not parsable by the JavaScript engine. That is why you are getting the error. Same way, wrap the expression in parenthesis to get the actual value, like this
({name: 'stack', location: 'somewhere'}['overflow'])
// undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With