Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 356
Florian Margaine Avatar asked Apr 04 '12 07:04

Florian Margaine


1 Answers

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

like image 186
Ray Toal Avatar answered Sep 30 '22 05:09

Ray Toal