We have received some JavaScript from an agency that looks wrong, but works.
For some reason they are adding square brackets ([
, ]
) around variables, like this:
var some_variable = 'to=' + [other_variable];
This works, but the square brackets seem completely superfluous.
Is there a purpose of using this syntax or is it technically incorrect, but ignored by the browser?
The notation may be a little confusing, but just remember that square brackets mean the end point is included, and round parentheses mean it's excluded. If both end points are included the interval is said to be closed, if they are both excluded it's said to be open.
Square Brackets are placed around extra information in a text; and are typically used for editorial comments, corrections, and clarifications. Square brackets can also be used to add something into a sentence that was taken out by the writer.
A square bracket at one end of an interval indicates that the interval is closed at that end (i.e., the number adjacent to the opening or closing square bracket is included in the interval).
Square brackets means new Array.
Just in case anyone else arrives here while trying to find out what some weird/new syntax involving [square brackets] (seen in someone else's Javascript) might possibly be, like I was...
Nowadays, with ES6, we also have [] used on the left-hand side for destructuring arrays, e.g.
const names = ['Luke', 'Eva', 'Phil']; const [first] = names; console.log(first); // 'Luke' const [first, second] = names; console.log(first, second); // 'Luke' 'Eva'
For further info see http://www.deadcoderising.com/2017-03-28-es6-destructuring-an-elegant-way-of-extracting-data-from-arrays-and-objects-in-javascript/ or google 'es6 destructuring'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With