Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do square brackets around an expression mean, e.g. `var x = a + [b]`?

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?

like image 445
Richard Ev Avatar asked Oct 27 '09 09:10

Richard Ev


People also ask

What do square brackets mean in an equation?

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.

What does it mean when square brackets are used?

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.

What do brackets around a variable mean?

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).

What does square brackets mean in node JS?

Square brackets means new Array.


1 Answers

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'.

like image 87
Jim Smart Avatar answered Sep 28 '22 22:09

Jim Smart