Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding how many time a specific letter is appearing in the sentence using for loop, break, and continue - JavaScript
We are required to write a JavaScript function that finds how many times a specific letter is appearing in the sentence using for loop, break, and continue statements.
Using continue Statement
The continue statement skips the current iteration and moves to the next one. Here's how we can use it to count character occurrences:
const string = 'This is just an example string for the program';
const countAppearances = (str, char) => {
let count = 0;
for(let i = 0; i < str.length; i++){
if(str[i] !== char){
// using continue to move to next iteration
continue;
};
// if we reached here it means that str[i] and char are same
// so we increase the count
count++;
};
return count;
};
console.log(countAppearances(string, 'a'));
console.log(countAppearances(string, 'e'));
console.log(countAppearances(string, 's'));
3 3 4
Using break Statement for Early Exit
We can also use break to exit the loop early once we find a certain number of occurrences:
const findFirstNOccurrences = (str, char, maxCount) => {
let count = 0;
for(let i = 0; i < str.length; i++){
if(str[i] === char){
count++;
console.log(`Found '${char}' at position ${i}`);
if(count >= maxCount){
// using break to exit loop early
break;
}
}
}
return count;
};
const testString = 'programming example';
console.log(`Total found: ${findFirstNOccurrences(testString, 'r', 2)}`);
Found 'r' at position 1 Found 'r' at position 4 Total found: 2
Alternative Approach Without continue
For comparison, here's a simpler approach without using continue:
const countLetterSimple = (str, char) => {
let count = 0;
for(let i = 0; i < str.length; i++){
if(str[i] === char){
count++;
}
}
return count;
};
const text = 'JavaScript programming';
console.log(`Letter 'a': ${countLetterSimple(text, 'a')}`);
console.log(`Letter 'r': ${countLetterSimple(text, 'r')}`);
Letter 'a': 3 Letter 'r': 4
Comparison
| Approach | Use Case | Performance |
|---|---|---|
With continue
|
When you need to skip complex conditions | Same as simple approach |
With break
|
When you want to stop after finding N occurrences | Faster for early termination |
| Simple approach | Basic counting without conditions | Most readable and efficient |
Conclusion
While continue and break provide flow control options, the simple approach is often more readable. Use continue for complex skip conditions and break for early termination scenarios.
Advertisements
