Why doesn't `{}.toString.apply(array)` work?

Go To StackoverFlow.com


Usually, when I want to check the type of an object (whether it's an array, a NodeList, or whatever), I use the following:

var arr = [] // I don't do this, but it's for the sake of the example
var obj = {}
obj.toString.apply(arr) // This works

The question is: why can I not do the following?

var arr = []
{}.toString.apply(arr) // Syntax error: Unexpected token .

I don't get where the syntax error is.

I can do something approaching with [] though, the following works:

var nodeList = document.getElementsByClassName('foo')
[].forEach.call(nodeList, function(bar) { console.log(bar) }) // Works

So... I'm confused.

2012-04-04 07:00
by Florian Margaine
you forgot () in toString() - kappa 2012-04-04 07:02
Nope, see @Ray Toal's answer. Adding the parenthesis would lead to a syntax error (Object has no method 'apply') - Florian Margaine 2012-04-04 07:13
Ahh.. i didn't thought that, it's correc - kappa 2012-04-04 07:19


When you begin a line with { JavaScript thinks it starts a block statement, not an object literal. Parenthesize it and you will be okay.

2012-04-04 07:01
by Ray Toal
Oh right, ({}).toString.apply(arr) works! Thanks a lot : - Florian Margaine 2012-04-04 07:02
@Ray Toal - +1 but: var arr = [] ({}).toString.apply(arr) // TypeError: object is not a function To work code must contains semicolons ; after each row var arr = []; ({}).toString.apply(arr); // works OKAndrew D. 2012-04-04 07:10
I didn't use semicolons because I trust the ASI :) But of course you'd have to specify it if you start your line with a parenthesis (it's one of the edge cases) - Florian Margaine 2012-04-04 07:11
+1 Correct. In fact I instinctively had that in my fiddle http://jsfiddle.net/58j53/ which I did not link to in the answer. I love those missing semicolon problems in JS. My favorite is when someone defines var f = function (...) {....} without the semicolon then follows that with a parenthesized expression (like an anonymous function activation) which is then picked up as an argument to that function - Ray Toal 2012-04-04 07:12
Yup, I usually code without semicolon, and once fell into this trap :-). Never again - Florian Margaine 2012-04-04 07:15