Languages

JavaScript - what do square brackets around expression mean?

0 points
Asked by:
ArcadeParade
666

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
Answered by:
ArcadeParade
666

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

    1. Destructuring assignment - JavaScript | MDN
    2. Array() constructor - JavaScript | MDN
    0 comments Add comment
    0 points
    Answered by:
    ArcadeParade
    666

    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
    Donate to Dirask
    Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
    Join to our subscribers to be up to date with content, news and offers.
    Native Advertising
    🚀
    Get your tech brand or product in front of software developers.
    For more information Contact us
    Dirask - we help you to
    solve coding problems.
    Ask question.

    ❤️💻 🙂

    Join