Languages

JavaScript - what do square brackets around expression mean?

0 points
Asked by:
ArcadeParade
666

What do square brackets around expression mean?

For example:

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:
Admin Dirask Community
4380

Square brackets can be used to:

  • create a new array,
  • destructure arrays.

    1. Creating new array

    2. Destructuring arrays (ES6)

    Square brackets ([]) on the left side of the expression are used to "unpack" values from arrays.

    going further:

     

    References

    1. Destructuring assignment - JavaScript | MDN
    2. Array() constructor - JavaScript | MDN
    0 commentsAdd comment
    0 points
    Answered by:
    Admin Dirask Community
    4380

    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.

    0 commentsAdd 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