JavaScript if else problems - javascript

everyone!
I have been having problems with my code. I think I know what is wrong but I can't seem to fix it, no matter how much I tried so I decided to take it up with the community. I think it is because of the second if statements contradict the one before it. Here, take a look.
if (Character.style.backgroundImage === "url(../images/animations/moveRightAnimation/1.png)") {
Character.style.backgroundImage = "url(../images/animations/moveRightAnimation/2.png)";
} else (Character.style.backgroundImage != "url(../images/animations/moveRightAnimation/1.png)") {
Character.style.backgroundImage = "url(../images/animations/moveRightAnimation/1.png)";
Hopefully, you see what I am talking about and know what the answer is. As I said in my last post I am not a great coder, so don't judge me too hard, XD.

There is no reason to repeat the conditional check negated with an else, that is only needed for an else if. Change
} else (Character.style.backgroundImage != "url(../images/animations/moveRightAnimation/1.png)") {
Character.style.backgroundImage = "url(../images/animations/moveRightAnimation/1.png)";
}
to something like
} else {
Character.style.backgroundImage =
"url(../images/animations/moveRightAnimation/1.png)";
}

Else doesn't take any parameters it's literally what runs in the case the if evaluates false.
If you want multiple exclusive if blocks, you need to use 'else if' where you currently have else

Syntax for if condition :
if ( condition ){
// code
}
else {
// code
}
Note : After else there cant't be any condition . Or you must use if-else.(Only if you want to use multiple conditions.And you seem to check only one,so its not needed.)
Syntax for if condition :
if ( condition ){
// code
}
else if ( condition ){
// code
}

Related

A question about a little gusess the age game i made with Js

in my udemy course, we just got introduced to JS!
I love this language, and right now I'm pretty much a novice.
I hope you can help me, i want my code to keep asking the user to guess the age that I've set as the sercretNumber.
i got 2 problems :
1) I think my code can and need to be shorter maybe with some OR and AND.
2) I can't get it to tell the user that if the number is negative or above 100, to prompt the user again for input by saying - Your number needs to be from 1-100.
I get it to work once and it's gone!
here's the Js code :
var secretNumber=98;
var numbGues=Number(prompt("Can you guses My age? (Hint - its 1-100"))
while (numbGues!=secretNumber){
// here I want this message to keep repeating if the user enters a non-valid input such as: -987 , or 54564654//
if (numbGues<0 || numbGues>100 ){
var numbGues=Number(prompt("Pleae choose a valid number between 1-100"))
}
if (numbGues<secretNumber){
var numbGues=Number(prompt("Too low! try again"))
}
else if (numbGues>secretNumber) {
var numbGues=Number(prompt("Too High! Try again!"))
}
if (numbGues==secretNumber) {
alert("You guessed it!")
}
}
Think about the if, if - else if, if structure you have here. It's possible to streamline it. Once you've covered all bases, you don't need another if, you just need an else to end the conditional statement.
As to your second point, in your first if statement, you're already prompting the user for the very same situation you mentioned. Just replace it with the error message you want to be displayed in that block.
little bit changed your code. you need to change
if (numbGues==secretNumber) {
alert("You guessed it!")
}
this if statement. finally your code looks like this.
var secretNumber=98;
var numbGues=Number(prompt("Can you guses My age? (Hint - its 1-100"));
while (numbGues!=secretNumber){
// changed if else statements
if (numbGues<0 || numbGues>100 ){
numbGues=Number(prompt("Pleae choose a valid number between 1-100"));
}else if (numbGues<secretNumber){
numbGues=Number(prompt("Too low! try again"));
}else if (numbGues>secretNumber) {
var numbGues=Number(prompt("Too High! Try again!"));
}
}
//you need to check this if statement in here otherwise if user entered secret number first time didn't show any alert
if (numbGues==secretNumber) {
alert("You guessed it!")
}

Javascript innerHTML method returning wrong value

I'm looking for some support with this math's project I'm doing. Basically I've created four boxes, and populated one with the correct answer. When I click on the correct answer, the if statement doesn't run; it always shows as wrong.
I include a snippet, if someone can see something glaringly wrong then I'd appreciate a response.
I'm only trying it with box 1 to see if it works, and the correct answer does populate in 1 of the 4 boxes, however it always says it's the wrong answer, even when correct answer is in box1.
document.getElementById("box1").onclick = function() {
if (playing == true) {
if (this.innerHTML == correctAnswer) {
score++;
document.getElementById("scorevalue").innerHTML = score;
hide("wrong");
show("correct");
setTimeout(function() {
hide("correct");
}, 1000);
} else {
hide("correct");
show("wrong");
setTimeout(function() {
hide("wrong");
}, 1000);
}
}
}
Instead of comparing two values with ==, try === in your if-statements.
Example: if (playing === true) {
This is most likely related to your HTML, and the way you have setup your tags. For example, if box1 is a div, then if your code looks like this:
<div id="box1">
answer
</div>
Then in some explorers, specifically Chrome and FireFox, it considers linebreak as empty space.
So, if var correctAnswer = "answer";
and you compare correctAnswer with box1.innerHTML like so:
if (correctAnswer == box1.innerHTML)
Then you will always get false returned.
In order to fix the issue, change your HTML like so:
<div id="box1">answer</div>
Basically remove the linebreaks.
Everything else seems to be fine.

How to user a condition in a String inside an IF sentence

I have the following situation:
var answer = 'three';
var isClosed = true;
var condition = "answer != null && !isClosed";
The condition is a literal string and it's dynamically set by the user. Once they set the condition, I need to evaluate it inside an IF/ELSE sentence:
if(condition)
//Do something
else
//Do something
Can I do that without using "eval()"? How? I want to avoid it:
if(eval(condition))
...
NOTE: This is a simple example, the real situation is a bit complex with dynamic conditions :)
If you want to evade eval at all cost (as it can be really dangerous for the security reasons), you basically need a rules engine adapted to your dsl that you get from the database.
I googled this one and it seems prety decent C2FO , didn't actually tried it, but now you know where to start.
A bit confused..
But if the answer and isClosed set by the user.. then just something like this will suffice..
answer = null
isClosed = false // the default value for isClosed
if(answer != null && !isClosed){
//Do something
}
else{
//Do something
}

Adding multiple parameters to an else if statement?

Let me explain in more detail, I'm making a little sketch for my maths teacher that will calculate the missing sides and angles of a triangle. I have if/else/else if statements but I want an else if statement that will output something like "Check spelling" if none of the other statements are true. Basically, I want something that would do something like this (keep in mind I don't know how to program this yet)
// More code above
else if (side != "hypotenuse and adjacent"; "hypotenuse and opposite"; "opposite and adjacent") {
confirm("Please check spelling.");
}
Can you see what I am trying to do? A previous variable is called side and it prompts the user to input which sides of the triangle they have, so the sketch can work out the angle. What if they have a spelling mistake and it doesn't match any of the parameters I set, how would I make it follow out this block of code if they don't match? I may have just over-complicated things here but if someone could tell me how to do this, it would be greatly appreciated
You can try indexOf:
possibilities = ["hypotenuse and adjacent", "hypotenuse and opposite", "opposite and adjacent"]
// so if side not in that array (the same as not in any of that values)
if (possibilities.indexOf(side) == -1) {}
Are you asking for a default statement if none of the others are matched? Wouldn't that just be an normal else statement?
else{//what you want here}
The simplest way I can think of is to use if, else if and else. By using the else at the end, you won't need to write a huge check for the last line since all the previous.
if (A) { A is true }
else if (B) { Not A, but B }
else if (C) { Not A or B, but C }
else { Not A, B or C }
An much nicer way to do this trick, is to use a switch/case, which is described here.
switch(n) {
case A:
A is true
break;
case B:
B is true
break;
default:
Not A or B
}
However, if you only want the last check for "spell checking", I'd say #zishe has a neat answer to that.
The most simple way to do this is to use jQuery function:
$.inArray(value, array)
which returns either positive index if the string can be found inside of array or -1 otherwise. So the solutions should be something like this:
var myArray = ["hypotenuse and adjacent", "hypotenuse and opposite", "opposite and adjacent"];
// more code above
else if($.inarray(side, myArray) == -1) {
confirm("Please check spelling.");
}

Why would Javascript `if...else if` not end with an `else`?

Here is a snippet of JavaScript code from a tutorial I was working with. I don’t understand why it doesn’t end with a final else clause; I thought that was a rule.
var curScene = 0;
function changeScene(decision) {
var message = "";
if(curScene == 1) {
message = " welcome";
} else if (curScene == 2) {
message = " this is scene two";
} else if (curScene == 3) {
message = " this is scene three";
}
document.getElementById("sceneimg").src = "scene" + curScene + ".png";
if(message != ""){
alert(message);
}
}
I thought it was always supposed to end with an "else"?
The else block is optional. You can have if without else.
For the same reason as why you can have just a single if:
if( /*condition*/ ) {
//some code
}
//other stuff
Consider 3 Scenario
Scenario 1: Boolean condition
if (condition) {}
else {}
Specifying a condition as else if would be redundant, and it's really obvious to the reader what the code does. There is no argument for using else if in this case.
Scenario 2: Infinite states
Here we are interested in testing for conditions A and B (and so on), and we may or may not be interested in what happens if none of them holds:
if (conditionA) {}
else if (conditionB) {}
else {} // this might be missing as it is in your case
The important point here is that there isn't a finite number of mutually-exclusive states, for example: conditionA might be num % 2 == 0 and conditionB might be num % 3 == 0.
I think it's natural and desirable to use a reasonable amount of branches here; if the branches become too many this might be an indication that some judicious use of OO design would result in great maintainability improvements.
Scenario 3: Finite states
This is the middle ground between the first two cases: the number of states is finite but more than two. Testing for the values of an enum-like type is the archetypal example:
if (var == CONSTANT_FOO) {}
else if (var == CONSTANT_BAR) {} // either this,
else {} // or this might be missing
In such cases using a switch is probably better because it immediately communicates to the reader that the number of states is finite and gives a strong hint as to where a list of all possible states might be found (in this example, constants starting with CONSTANT_). My personal criteria is the number of states I 'm testing against: if it's only one (no else if) I 'll use an if; otherwise, a switch. In any case, I won't write an else if in this scenario.
Adding else as an empty catch-errors block
This is directly related to scenario #2 above. Unless the possible states are finite and known at compile time, you can't say that "in any other case" means that an error occurred. Seeing as in scenario #2 a switch would feel more natural, I feel that using else this way has a bad code smell.
Use a switch with a default branch instead. It will communicate your intent much more clearly:
switch(direction) {
case 'up': break;
case 'down': break;
default: // put error handling here if you want
}
This might be a bit more verbose, but it's clear to the reader how the code is expected to function. In my opinion, an empty else block would look unnatural and puzzling here.
It doesn't have to, for the same reason an if on its own doesn't require an else.
Usually it's a good idea to have one, as a sort of "catch-all" situation, but the above code could be written as:
switch(curScene) {
case 1: message = " welcome"; break;
case 2: message = " this is scene two"; break;
case 3: message = " this is scene three"; break;
}
In the above code, I could also add:
default: message = " invalid curScene value"; break;
But it's completely optional to do so. It depends on how reliable the curScene variable is whether or not I personally would add it in.
Not having an else clause is fine syntactically. MDN Documentation Basically the second if becomes the body of the else, see the section on "how it would look like if the nesting were properly indented".
As to whether it's bad practice I think that depends on intent. By not explicitly defining the final else clause, you might end up with a bug where a condition you didn't cover comes through. Consider this:
if(myVariable > 0) {
doSomething();
} else if(myVariable < 0) {
doSomethingElse();
}
Nothing happens if myVariable is 0. It would be hard to see if you were just glancing through the code. I would say if you run into this pattern it would be a code smell, something might be wrong, but it could be fine.
The same logic could always be expressed with nested if statements. I would go with whatever is more readable.
else is a default case for the if statement.
If there is no else then if none of the conditions in the if or else if cases are met than the if statment will do nothing.
Usually it is good practice to have a default case but there are a lot of times where it is not necessary and thus excluded from the code.
In this case, if the curScene was anything other than 1, 2, 3 then the else statment would be used, but since there is no processing to be done on other cases the coder has not included an else.
yes, always have a else is VERY GOOD habit(when using with if-elseif). sometimes people might even write this:
if(curScene == 1) {
message =" welcome";
else if (curScene == 2) {
message = " this is scene two";
}
else if (curScene == 3) {
message = " this is scene three";
} else {
// empty.
}
to tell people there is indeed nothing to do in the else.
change the if condition for answer validation if(answer==100) to if(answer===100)
it is working fine now...

Categories