Last active
July 7, 2023 10:44
-
-
Save jonurry/ef3d28f16ba1e6ec6693a0777af52ad9 to your computer and use it in GitHub Desktop.
3.3 Bean Counting (Eloquent JavaScript Solutions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function countBs(s) { | |
var count = 0; | |
for (var i = 0; i < s.length; i += 1) { | |
if (s.charAt(i) === "B") | |
count += 1; | |
} | |
return count; | |
} | |
function countChar(s, c) { | |
var count = 0; | |
for (var i = 0; i < s.length; i += 1) { | |
if (s.charAt(i) === c) | |
count += 1; | |
} | |
return count; | |
} | |
console.log(countBs("BBC")); | |
// → 2 | |
console.log(countChar("kakkerlak", "k")); | |
// → 4 |
Thank you so much for that clarification. I understand it now and I really appreciate it! I'm new to JS and programming in general, and I don't really know people I can ask for help when I'm stuck so it's really nice to see people out there who are willing to help! Thank you and have a great day!
function countChar(s, c) {
var count = 0;
for (var i = 0; i < s.length; i += 1) {
if (s.charAt(i) === c)
count += 1;
}
return count;
}
function countBs(s){
return countChar(s,"B");
}
console.log(countBs("BBC"));
// → 2
console.log(countChar("kakkerlak", "k"));
// → 4
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @umpavi
If you declare the count variable within the for loop then it will reset to zero with every iteration of the loop.
By declaring count outside the for loop and setting the initial value to zero it can be incremented within the loop.
It's all about
scope
.Variables declared within a code block (e.g. the for loop) have a different scope to those declared outside the block.