Counting Words in JS

I already found out how to count words in a given string, but I’m not sure why my previous code is wrong (albeit it’s much longer than it needs be). Here’s my code:

function countWords(str) {
	totalSpaces = 0
	for (var i = 0; i < str.length; i++) {
		if (str[i] === " ") { // if str[i] is a space, add 1 to totalSpaces
			totalSpaces += 1
		} else {
			return 'No spaces!'
		}
	}
	return totalSpaces
}

Your function returns the first time you hit a non-space character.

1 Like