Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do square brackets after a function reference mean?

I just spent about 15 minutes debugging a piece of JavaScript code, and discovered the problem was that I had written

matches.push[[-1]];

instead of

matches.push([[-1]]);

like I intended, where matches is an array. Can somebody explain to me why JavaScript didn’t throw a syntax error on the former, and what its meaning is?

like image 616
ekl Avatar asked Oct 23 '25 22:10

ekl


1 Answers

Why

matches.push is a Function Object, and you can access object properties and methods through dot notation or the bracket notation. Basically you're asking for something which isn't in the push Function Object, so it yields undefined.

enter image description here

Note

If you added something with the key [-1] as in matches[[-1]] = "something" it would also be valid, so the syntax is valid, simply not what you wanted to do.

like image 191
Juan Cortés Avatar answered Oct 26 '25 12:10

Juan Cortés



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!