Search code examples
javascriptgoogle-chromegoogle-chrome-devtoolsobject-literal

weird behavior in Chrome console


Take a look at the screenshot...

screenshot

The reason why I'm experimenting with this is because I did a simple Google search for how to check if a parameter is a function, and I found this...

var getClass = {}.toString;
...
function isFunctionA(object) {
    return object && getClass.call(object) == '[object Function]';
}

source: http://jsperf.com/alternative-isfunction-implementations/4

So what is the difference between what I'm typing out and the example source code? Why is Chrome giving an error when entering just {}.toString, but works fine when it is inside the parenthesis?


Solution

  • {} at the beginning of a statement is ambiguous, is it an empty code block or an object? The definition resolves the ambiguity by defining it as a code block, to use {} at the start of a statement as an object make it an expression by enclosing it in parentheses : ({})

    See also answer to Why does accessing a property directly on an Object literal throw a SyntaxError?