Syntax error when trying to test for empty string [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
In Javascript, I am trying to do a simple task of testing and returning the longest of two words. If the words are empty then the return should say "empty string". I keep getting a syntax error when testing for an empty string with the or elseif statement. I am using (!word1) and (!word2) because my understanding is in Javascript it is a boolean statement and should be false. Please tell me where I am going wrong:
function longest(word1, word2) {
if (word1.length >= word2.length) {
return (word1);
} else {
return (word2);
} else if (!word1) || (!word2) {
return "an empty string";
}
}
console.log(longest('hi'));

if conditions should be surrounded by exactly 1 pair of parentheses.
Change else if (!word1) || (!word2) to else if (!word1 || !word2).

Your "else" clause should be the last clause in your if statement:
function longest(word1, word2) {
if (word1.length >= word2.length) {
return (word1);
} else if (!word1 || !word2) {
return "an empty string";
} else {
return (word2);
}
console.log(longest('hi'));

You got your else and else if around the wrong way. Heres the complete code for your problem.
function longest(word1, word2) {
if ((!word1) || (!word2)) {
alert ("an empty string");
} else if (word1.length >= word2.length) {
alert (word1);
}else{
alert (word2);
}
}
longest('hi');

Related

What Is The Difference Between else and !== In JavaScript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
Is there any difference between else and !== in JavaScript?
I am beginner in JavaScript and I can't find their difference, for example in this code I expected the text to appear when I enter other days.
const day= prompt(`Insert The Day`);
if(day===`monday`){
console.log(`Pray All Day Long🙏🏽`)
}
else if(day===`tuesday`){
console.log(`Code All Day Long`)
}
else if(day===`wednesday`){
console.log(`Meditate All Day Long`)
}
else if(day===`Thursday`){
console.log(`Design All Day Long`)
}
else if(day!==`monday`){
console.log(`Why Not Monday?`)
}
else{
console.log(`Invalid Day`)
}
These 2 are entirely different operators.
else is to be applied after an if block, and is run if the condition from the if block wasn't met.
== is a "loose" equals, which means that values of different types with the same value are considered to be equal. This means that 1 == "1" will return true, even if 1 is an int and "1" is a string.
=== checks for absolute equality, which means that only values with the same type and value are considered equal. This means that 1 === "1" is false, but 1 === 1 is true.
!== is the opposite of ===, which means that any value with a different type or value is considered not equal. This means that 1 !== 2 is true, and 1 !== "1" is as well.
Firstly, I think you should learn about if..else. You can read more here, and the !== is an operator
And in your case, I suggest using switch
switch(day) {
case 'monday': console.log('Pray All Day Long🙏🏽');
break;
case 'tuesday': console.log('Code All Day Long');
break;
...
default: console.log('Invalid Day');
break;
}
Finally, the better performance sulotions are Map and using [key, value] of Object
Hope useful for you.

Alerting on the last iteration of a Loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Hi So ive read threw a whole bunch of the questions in regards to this.. Most of them throw off my data or I just cant get them to actually proc on the last iteration
for(const[m, value] of datesLess) {
console.log("Logging M:" + m);
if(startD == m || endD == m){
console.log(m)
takendates.push(m);
if (m === datesLess.length - 1) {
alert("The following Bookings are taken:"+takendates.join("\n"));
}
}else{
this.logentry(startDay,startMonth,startYear,endDay,endMonth,endYear,entryinfo);
}
}
In essence im trying to display the alert on the last iteration of the loop so the user can see which dates are incorrect as to just displaying a popup with no details
I'm fairly sure what you really want to be doing is showing the alert after the loop
const takenDates = [];
for(const[m, value] of datesLess) {
console.log("Logging M:" + m);
if(startD == m || endD == m){
console.log(m)
takendates.push(m);
}else{
this.logentry(startDay,startMonth,startYear,endDay,endMonth,endYear,entryinfo);
}
}
if(takendates.length) {
alert("The following Bookings are taken:"+takendates.join("\n"));
}

Javascript execute a function of the number of indexes in two arrays are equal? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm trying to execute a function when two arrays have an equal length that is greater than zero.
My program assigns the class of 'letter' to each list item in the phrase div. If a button press matches a letter in that div, that letter gets assigned the class 'show' which reveals it to the user.
I don't understand why my win condition isn't being met. Is there something wrong with the way I'm comparing the length of the two indexes?
I've included my codePen here: https://codepen.io/Azo3307/pen/vPjwxr
My checkWin() function is on line 100, and then it is called on line 143 after each button press is triggered.
// Check win condition
function checkWin() {
let showClass = document.getElementsByClassName('show');
let lettersClass = document.getElementsByClassName('letters');
if (showClass.length == lettersClass.length && showClass.length > 0 && lettersClass.length > 0) {
console.log('you win');
addElement('win', `You Win!`, `"${phraseArray}" is correct! `);
} else if (missed == 5) {
console.log('you lose');
addElement('lose', 'Game Over!', 'Better luck next time!');
}
}
Any help is much appreciated. Thank you.
This is because you're asking for let document.getElementsByClassName('letters') instead of letter:
<li class="letter show">t</li>
Second point, if showClass.length == lettersClass.length and showClass.length > 0, you don't need to test lettersClass.length > 0 ;)
function checkWin() {
let showClass = document.getElementsByClassName('show');
let lettersClass = document.getElementsByClassName('letter');
if (showClass.length == lettersClass.length && showClass.length > 0) {
console.log('you win');
addElement('win', `You Win!`, `"${phraseArray}" is correct! `);
} else if (missed == 5) {
console.log('you lose');
addElement('lose', 'Game Over!', 'Better luck next time!');
}
}
Last one, it's easy to know the text before trying anything just by selecting all the block ;) You should display:none instead of put it transparent.
Line 102:
let lettersClass = document.getElementsByClassName('letters');
rename to
let lettersClass = document.getElementsByClassName('letter');
Looks like just small typo. Btw code looks great, thumbs up.

Value not assigned in while loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
So in the following code a= -1 so the statement in the while loop should be -1, but the while loop is never entered. I have looped through but don't understand why the while loop is never executed. I am sure this is frustratingly simple.
function translatePigLatin(str) {
var newStr = str.split("");
var vowels = ["a","e","i","o","u"];
var i = 0;
var a = vowels.indexOf(newStr[0]);
while (vowels.indexOf(newStr[i]) != -1) {
i = i++;
}
if(i===0){
return str + "way";
}
else{
str = str.substr(i) + str.substr(0,i) + "way";
}
//return str;
}
translatePigLatin("consonant");
In the while loop you are checking vowels.indexOf(newStr[i]) != -1 which mean that if vowels.indexOf(newStr[i]) is not -1 then while loop should bve executed. and as you say the expression results in -1 the loop should not be executed which is a expected behaviour.
Change the condition to
vowels.indexOf(newStr[i]) == -1 if you want to execute the while loop is the value returned is -1

numbers and words not numbers to words js [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a simple code gotten from the internet and it did not answer what I really wanted as output. I have two input fields; one for the input and another for the output and they are processed through this function:
<script type="text/javascript">
function AnEventHasOccurred() {
var x = document.getElementById("onkeyup").value
if (x >= "100") {
document.getElementById("eventlog").value = "" +
return x = ['Generalities'];
}
}
</script>
What I'm really needing is that when I enter numbers below 100, output must be Generalities. I haven't got it correctly. And I went here to ask some help. Thanks.
You're never outputting your value back into the output field. All you're doing is returning the value. You need to set the value of your output field to "Generalities".
Example
var input = document.getElementById("onkeyup").value;
// You should be giving your elements meaningful IDs.
if(+input < 100) {
document.getElementById("output").value = 'Generalities';
// Assumes an output field called "output".
}
Try this:
function AnEventHasOccurred() {
var x = document.getElementById("onkeyup").value;
if (x < 100){
document.getElementById("eventlog").value = "Generalities";
}
}
I see a few errors. Check this out for comparison:
function AnEventHasOccurred() {
// should probably save the elements to variables
// since you'll be checking and changing the values
var x = document.getElementById("onkeyup");
var y = document.getElementById("eventlog");
// should be 100, not "100"
if (x.value < 100) {
y.value = "Generalities";
} else {
y.value = "";
}
}
This should work fine. Check it out on jsfiddle.
More Recommendations
Your return statement doesn't correspond with your "output": it
does nothing valuable in this case.
You check or set the value of an input by getting the element and
using its value key.
You should put semi-colons at the end of most javascript lines, with the exceptions generally being curly brackets {}, comments // and /* */, and empty lines.

Categories