1

I have a function that takes an input of a string and a single char that will count how many times that char appears in that string.

function count(str, letter) {
  var num = 0;
  for (var i = 0; i < str.length; i++)
    if (str.charAt(i) == letter)
      num += 1;
  return num;

}

console.log(count("BBC", "B"));
//output 2

It works fine like this, but this took me some time to figure out. Its second hand nature for me to always put brackets on a for loop but when i do that, the function doesn't work as i anticipated it would, like so:

function count(str, letter) {
  var num = 0;
  for (var i = 0; i < str.length; i++) {
    if (str.charAt(i) == letter)
      num += 1;
    return num;
  }
}

console.log(count("BBC", "B"));
//outputs 1

Why are the brackets causing it to act this way?

4 Answers 4

1

Why are the brackets causing it to act this way?

Because you have the return statement inside of the for loop block. At the end of the block, the function returns.

function count(str, letter) {
    var num = 0;
    for (var i = 0; i < str.length; i++) {  // block start
        if (str.charAt(i) == letter)
            num += 1;
        return num;                                        // exit function in first loop
    }                                       // block end
}
Sign up to request clarification or add additional context in comments.

Comments

0

It's not the braces (brackets are []), it's the placement of the return statement. The return statement is in the first iteration of the loop (i = 0). If you add an extra set of braces (as seen below), it becomes more obvious.

function count(str, letter) {
    var num = 0;
    for (var i = 0; i < str.length; i++) {
        if (str.charAt(i) == letter) {
            num += 1;
        }
        return num; // <-- This return exits the function
    }
}

console.log(count("BBC", "B"));
//outputs 1

Comments

0

In the First one return statement was outside for loop, but in the second one return statement is inside the for loop. That made the difference. Try the below code.

    function count(str, letter) {
      var num = 0;
      for (var i = 0; i < str.length; i++) {
        if (str.charAt(i) == letter)
          num += 1;
        }
        return num;
    }

console.log(count("BBC", "B"));

Comments

0

your loop gets terminated after first iteration. So if you try to get the occurrence of "B" in "XBBBB...B" it will return 0. Try to debug your code and place brackets at right position. Learn to debug your js code using browser.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.