I am confused about when to use else in my code. For example in the below code that I found, there is no else used before the final return true statement. But sometimes I see that else is used in if statements. Sometimes I use else but it comes up with an error saying I shouldn’t use it. How do I know when to use it or not?
function isPangram(string){
let alphabet = "abcdefghijklmnopqrstuvwxyz";
let regex = /\s/g;
let sentence = string.toLowerCase().replace(regex, "");
for(let i = 0; i < alphabet.length; i++){
if(lowercase.indexOf(alphabet[i]) === -1){
return "false";
}
}
return "true";
}
I would like to clarify why return true comes after the second curly brace and not after the first one? I kind of get it but it’s not totally clear in my mind why…
You don’t have to have an else block in JS of you don’t need it. If you only need to do something if some condition is true, then you can just have if (condition) doThing.
Because it isn’t necessary to explicitly write else every time, if you have something like if (condition) returnThing otherwise returnDefaultThing, often these two are equivalent:
if (condition) {
return thing;
}
return defaultThing;
It’s completely context-sensitive. You seem to have something turned on that checks, that should help. But [and I’m sorry to put it this way] it’s very simple logic – look at the code and see if it’s appropriate, don’t guess.
So this code you posted is a good example. There are some issues with it (I can’t see how the current approach can work??), but logic wise, what you want:
You have a string.
You want to check if it is a pangram. You do this by looping through the characters
As soon as the loop encounters a bad character, stop looping and return false
If the loop finishes, it cannot have encountered a bad character, so must be able to return true
a return statement makes the function stop - if you have both return statements inside the loop only the first iteration of the loop does something - it’s like not having the loop and just checking for i = 0 and never increasing i
as a return statement stops the function, if you have two alternative return statements having
if (...) {
return ___
}
return ___
or
if (...) {
return ...
} else {
return ...
}
it doesn’t matter
it is important to know which one you want to use if you don’t have a return statement inside the if
this is more probable a syntax error - what kind of error you get and what’s your code when it happens?
Thank you. I don’t have an error message right now but it is something I feel like I have come across a few times. If it comes up again I will be sure to paste it here.