EN
JavaScript - what do square brackets around expression mean?
2
answers
0
points
What do square brackets around expression mean?
For example:
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
// ONLINE-RUNNER:browser;
const array1 = new Array('a', 'b');
const array2 = ['a', 'b']; // equal to the syntax above
console.log(array1); // [ 'a', 'b' ]
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.
// ONLINE-RUNNER:browser;
const letters = ['a', 'b', 'c'];
const [first] = letters;
console.log(first); // 'a'
going further:
// ONLINE-RUNNER:browser;
const letters = ['a', 'b', 'c'];
const [first, second] = letters;
console.log(first); // 'a'
console.log(second); // 'b'
References
0 comments
Add 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.
// ONLINE-RUNNER:browser;
const x = 5;
const text = 'value: ' + [x];
console.log(text); // 'value: 5'
0 comments
Add comment