0

For example when I write this kind of code;

var power = function(base, exponent) {
            var result = 1;
            for(var count = 0; count<exponent; count++) 
            result *= base;
            return result;

            };
        console.log(power(2, 10));

I get 1024, but when I write this kind of code;

var power = function(base, exponent) {
            var result = 1;
            for(var count = 0; count<exponent; count++) {
            result *= base;
            return result;
            }   
            };
        console.log(power(2, 10));

I get 2, I am confused, what is the logic of curly braces in this kind of situation.

3 Answers3

1
for(var count = 0; count<exponent; count++) 
result *= base;

is equivalent to

for(var count = 0; count<exponent; count++) {
    result *= base;
}

The first block runs fully because by default the for loop only includes the line after it, so the "return" doesn't get hit until after the loop fully executes.

In the second block, your loop only executes once, because the function exits as soon as it hits "return".

anonymouse
  • 639
  • 1
  • 8
  • 18
0

You are allowed to omit the curly braces in a control block when there is only one statement inside the block. While allowable, it is inadvisable because it is a common coding pattern that leads to bugs down the line.

See these examples:

// Not using the braces leads to confusing code that can cause bugs:

if("scott" === "scott")
  console.log("scott === scott");
  console.log("Am I from the true section of the if/then or not?");
  
// Using them makes it much more simple to understand the code
if("scott" === "scott"){
  console.log("scott === scott");
}
console.log("I am clearly not from the true section of the if/then!");
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

Always use curly braces, not using them leads to unexpected behavior. The problem is, you need to return outside of your for loop:

var power = function(base, exponent) {
              var result = 1;
              for(var count = 0; count<exponent; count++) {
                result *= base;
              }  
              return result;
            };
        console.log(power(2, 10));