I don't understand why my second else if statement never runs. Can someone explain it to me?
Name = window.prompt("Tell your First Name");
if (Name.endsWith('X') == true || Name.endsWith('x') == true) {
meh = Name.slice(0, -1)
console.log(meh)
} else if (Name.startsWith('X') == true || Name.startsWith('x') == true) {
hello = Name.slice(1)
console.log(hello)
} else if (Name.startsWith('X') == true || Name.startsWith('x') == true && Name.endsWith('X') == true || Name.endsWith('x') == true) {
var result = Name.slice(1) && Name.slice(0, -1);
console.log(result)
} else {
console.log(Name)
}
Your code needs to start with most specific and go to the least. The code will not check all cases and figures out what is the best match, it starts from the top and first thing it matches it exits.
const firstName = window.prompt("Tell your First Name");
const endsWith = firstName.toUpperCase().endsWith('X');
const startsWith = firstName.toUpperCase().startsWith('X');
if (startsWith && endsWith) { console.log('starts and ends'); }
else if (startsWith) {console.log('starts'); }
else if (endsWith) {console.log('ends'); }
else {console.log('nope'); }
There are quite a few issues with your logic. For example:
You have a compound conition to check of a character in string but, you should change the string case and then determine if the character you are looking for "startsWith" or "endWith" which appears to be the only to senarios your concerned with.
secondly the "startsWith" and "endWith" functions natrually return a boolean value so equating the return with true or false would be redundant and uneccessary.
If else execution of one or other
If else if execute one or other - just enables the ability to take other senarios into consideration.
const Name = window.prompt("Tell your First Name");
if (Name.toUpperCase().endsWith('X')) {
hello = Name.slice(1)
console.log(hello)
} else if (Name.toUpperCase().startsWith('X')) {
var result = Name.slice(1) && Name.slice(0, -1);
console.log(result)
} else {
console.log(Name)
}
const Name = window.prompt("Tell your First Name");
if (Name.toUpperCase().endsWith('X')) {
hello = Name.slice(1)
console.log(hello)
}
if (Name.toUpperCase().startsWith('X')) {
var result = Name.slice(1) && Name.slice(0, -1);
console.log(result)
} else {
console.log(Name)
}
startsWithX && endsWithX to be first condition, otherwise one of above will take it's placeX and xName = window.prompt("Tell your First Name").toLowerCase();
console.log('Answer: ', Name);
if (Name.startsWith('x') == true && Name.endsWith('x') == true) {
var result = Name.slice(1) && Name.slice(0, -1);
console.log('Starts and ends with X', result)
} else if (Name.endsWith('x') == true) {
meh = Name.slice(0, -1)
console.log('Ends with X', meh)
} else if (Name.startsWith('x') == true) {
hello = Name.slice(1)
console.log('Starts with X', hello)
} else {
console.log('Default', Name)
}