What is the difference with/without curly brackets?

Viewed 123

I saw a source code and noticed there was an "additional" curly brackets around a.name as below, although the common case I usually see is without curly bracket. I'm wondering this works differently in some specific cases, which I tried and came out the same though, or some sort of convention. Does anybody know the difference?

With curly bracket

array.forEach((item, index) => {
  let a = {
    id: index;
  };

  {
    a.name = 'test';
  }
}

Without curly bracket

array.forEach((item, index) => {
  let a = {
    id: index;
  };
  
  a.name = 'test';
}
1 Answers

Both examples are the same in this case, however, it has two uses in other cases.

One use is to force the scope of a variable declared with let. let variables are "block scoped", and if you declare them inside a "block" like this, then they will be scoped to that block. For example:

let cookies = "Cookies are nice";

console.log(cookies);// "Cookies are nice"

but

{
    let cookies = "Cookies are nice";
}

console.log(cookies);// Reference error

The other use for them is simply to force auto-indenting to have an extra indent in your IDE... For example, most IDEs do not auto-indent PHP code, and some programmers will chose to use these blocks to fake out the IDE into auto-indenting.

For example:

<?php

//the code in here won't be auto-indented

?>

but

<?php
{
    //if I do this, then it will be auto-indented.
}
?>

Hope this answers your question. :)

Edit: Actually, I believe there's another use for these brackets when referring to objects. I've seen them used like { nameOfObject } in place of nameOfObject, but I don't know exactly what they do in those cases, and can't speak on the matter. I bet someone else here could answer that though! (If you know, please feel free to leave a comment sharing why!)

Related