| Closures in JavaScript | Arrays & Objects in JavaScript | |
JavaScript: Mini Project: Word Counter |
This project demonstrates how to use a closure to keep track of word count in a blog post.
function createWordCounter() {
let totalWords = 0; // private variable
return function(blogText) {
// split words by spaces and filter out empty strings
const words = blogText.trim().split(/\s+/).filter(word => word.length > 0);
totalWords += words.length;
return totalWords;
};
}
const counter = createWordCounter();
console.log(counter("This is my first blog post."));
// Output: 6
console.log(counter("I love writing in JavaScript."));
// Output: 11 (6 + 5 more words)
console.log(counter("Closures are powerful!"));
// Output: 14 (previous total + 3 words)
totalWords is a private variable preserved by closure.Open the browser console and paste the code to test different blog posts.
Type your blog post below. The tool will show word count, character count, and estimated reading time in real-time.
Words: 0
Characters (with spaces): 0
Characters (without spaces): 0
Estimated Reading Time: 0 min
| Closures in JavaScript | Arrays & Objects in JavaScript | |