*
Previous Closures in JavaScript Arrays & Objects in JavaScript Next

JavaScript: Mini Project: Word Counter

📌 Mini Project: Word Counter

This project demonstrates how to use a closure to keep track of word count in a blog post.

✅ Example Code

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)
    

🔎 Explanation

  • totalWords is a private variable preserved by closure.
  • Each time you pass a new blog post text, the word count is updated.
  • This simulates tracking the total word count across multiple posts.

🧠 Try It Yourself

Open the browser console and paste the code to test different blog posts.

Blog Editor Tool

📌 Mini Project: Blog Editor Tool

Type your blog post below. The tool will show word count, character count, and estimated reading time in real-time.

📊 Stats

Words: 0

Characters (with spaces): 0

Characters (without spaces): 0

Estimated Reading Time: 0 min

Back to Index
Previous Closures in JavaScript Arrays & Objects in JavaScript Next
*
*