I created a for loop that wanted to check for a “.” or a “!” and increment the value of sentenceCount every time it finds one:
function sentCount() {
for (let i = 0; i < storyChar.length; i++) { if (storyChar[i] === '.' || storyChar[i] === '!' ){
sentenceCount ++
}
}
}
When I first wrote this function I had the function return sentenceCount++
and when I called the function and then used console.log(sentenceCount);
I got a total of 0.
function sentCount() {
for (let i = 0; i < storyChar.length; i++) { if (storyChar[i] === '.' || storyChar[i] === '!' ){
return sentenceCount ++
}
}
}
In an effort to fix my code I deleted return
, because I realised I wasn’t sure if it needed return
or not, and voila the function suddenly started to work!
This has drawn my attention to the fact that I don’t really understand when return
is needed and when it is not. And I’m not sure why return
broke my function.
Can anyone shed some light on this?
Before posting this I did some testing myself… I just re wrote the function to include a return statement:
function sentCount() {
for (let i = 0; i < storyChar.length; i++) { if (storyChar[i] === '.' || storyChar[i] === '!' ){
sentenceCount ++
}
}
return sentenceCount
}
and then instead of console logging the variable “sentenceCount”, I wrote console.log(sentCount());
and got the correct answer.
So maybe I just answered my own question… If I use return
that means that the function will return its own value i.e. that function now = a value. In this case sentCount()
= 12.
So the function itself now is almost like its own variable… with the return statement included the function = 12, and without the return statement the function doesn’t have a value of its own. And so including the return statement means that I don’t have to call the statement and then console log the variable separately.
It also means that I can declare my variable(in this case sentenceCount
) within the function itself so that it doesn’t have to have global scope and therefore I have cleaner code.
So maybe I just answered my own question in the process of writing this post, but I could be missing something and perhaps someone else might find this useful so I’ll post anyway…
Here’s the final variation of the function I created
function sentCount() {
let sentenceCount = 0
for (let i = 0; i < storyChar.length; i++) { if (storyChar[i] === '.' || storyChar[i] === '!' ){
sentenceCount ++
}
}
return sentenceCount
}