benbotto
benbotto

Reputation: 2440

Why do square brackets around HTML-bound event handlers work?

Consider the following code snippet.

function func1() {
  console.log('func1 fired');
}

function func2() {
  console.log('func2 fired');
}
<button onclick="[[[func1(), func2()]]]">Click Me</button>

Note that the onclick event attribute's value is surrounded by multiple pairs of square brackets (I used three arbitrarily, but the number of brackets doesn't appear to matter). The code works in Firefox and Chrome, but why does it work? Is this standard and documented somewhere, or is it just the browser trying to be helpful.

Upvotes: 1

Views: 282

Answers (2)

Pointy
Pointy

Reputation: 413720

The browser will construct a function from the attribute value, using the text of the attribute as the code of the function. In your case, that'll be a function that looks like

function madeByBrowser(event) {
  [[[ func1(), func2() ]]];
}

That is legal JavaScript. The function contains a single expression, an array initializer. A side effect of evaluating that array initializer is to call the two functions.

(The actual constructed function won't be exactly like that, and there are some odd and often problematic details about the implicit scope of the code in the function. It's close enough for the purposes of this question.)

Upvotes: 3

Barmar
Barmar

Reputation: 780909

It works because expressions can be used as statements in JavaScript. So it's creating nested arrays of the results of the function calls, but not doing anything with those arrays.

For the same reason you could write:

function func3() {
    [[[func1(), func2()]]];
}
func3();

Upvotes: 3

Related Questions