Back

Technologies:

javascriptjavascript
avatar
Tolerim
24 days ago

What is the purpose of curly braces when used in JavaScript loops?

When working with loops, I usually utilize curly braces when I have more than one statement. However, in this particular situation, I found that curly braces resulted in unexpected behavior.

const game = { odds: [1.33, 3.25, 6.5] };
const array = Object.values(game.odds);
let avg = 0;
for (const value of array) {
  avg += value;
  avg /= array.length;
  console.log(avg);
  // 0.44333333333333336
  // 1.231111111111111
  // 2.577037037037037
}

The above code logs each result in a separate line. Surprisingly, when I removed the curly braces, it worked as expected:

const game = { odds: [1.33, 3.25, 6.5] };
const array = Object.values(game.odds);
let avg = 0;
for (const value of array) avg += value;
avg /= array.length;
console.log(avg);
// 3.6933333333333334
/* I expected this 3.6933333333333334 */

Therefore, I am curious to know the role of curly braces in loops and the difference they make in this context.

Answers(2)
avatar
Vogi
23 days ago
Verified Answer
Curly braces are used to group a set of statements. Often we use them along with loops and conditional statements in order to avoid confusion and to define a clear scope. In your case, when you removed the curly braces, the loop only executed the last statement which is avg /= array.length; and then printed the result. However, when you used curly braces, the loop executed both statements avg += value; and avg /= array.length; before printing the result. Therefore, the result was different.

Sources

What is the role of curly braces in C program? – ITExpertly.comRole of curly braces in loop in JavaScript - Stack OverflowC# if-else statement: Curly braces or not? An in-depth analysisarrays - In which situations curly braces are used in loops in Java ...
avatar
Tolerim
24 days ago
When using curly braces in a loop, it indicates that the statements in the loop should be executed as a block of code. In the code provided, the curly braces were not used and as a result, only the first statement of the loop (avg += value;) was being executed as part of the loop. This resulted in the incorrect results being displayed. When the curly braces are removed, the loop is executed as a block and all the statements are executed with each iteration. This results in the correct calculation of the average value of the game.odds array. So the difference between using curly braces and not using them in loops is that the former ensures that all the statements within the loop are executed as a block for each iteration, while the latter only executes the statement immediately following the for keyword as part of the loop.
;