EN
JavaScript - what do square brackets around expression mean?
2 answers
0 points
What do square brackets around expression mean?
For example:
xxxxxxxxxx
1
const text = 'value: ' + [x];
This works, but the square brackets seem redundant.
Is this syntax correct? What is the purpose of using it?
2 answers
0 points
Square brackets can be used to:
- create a new array,
- destructure arrays.
1. Creating new array
xxxxxxxxxx
1
const array1 = new Array('a', 'b');
2
3
const array2 = ['a', 'b']; // equal to the syntax above
4
5
console.log(array1); // [ 'a', 'b' ]
6
console.log(array2); // [ 'a', 'b' ]
2. Destructuring arrays (ES6)
Square brackets ([]
) on the left side of the expression are used to "unpack" values from arrays.
xxxxxxxxxx
1
const letters = ['a', 'b', 'c'];
2
3
const [first] = letters;
4
5
console.log(first); // 'a'
going further:
xxxxxxxxxx
1
const letters = ['a', 'b', 'c'];
2
3
const [first, second] = letters;
4
5
console.log(first); // 'a'
6
console.log(second); // 'b'
References
0 commentsShow commentsAdd comment
0 points
In your case, there's no difference if you use square brackets or not because if it's an array it will be converted to a string.
However, when you remove the brackets it will take less time because it doesn't have to build a new array and convert it.
xxxxxxxxxx
1
const x = 5;
2
3
const text = 'value: ' + [x];
4
5
console.log(text); // 'value: 5'
0 commentsAdd comment