Bad Assignment, Logical Operators [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 9 years ago.
Improve this question
Am learning Javascript in code academy. This is the test I have been given,
"Inside the eat function, create an if statement that returns true only if both hungry and foodHere are true, and false otherwise."
My code below is executing but it has a warning. What could be the problem?
var hungry = true;
var foodHere = true;
var eat = function() {
if(hungry && foodHere){
console.log("I am hungry");
}else if(hungry && foodHere = false){
console.log("Choose one");
}
};
eat();

var hungry = true;
var foodHere = true;
var eat = function() {
if(hungry && foodHere){
console.log("I am hungry");
}else {
console.log("Choose one");
}
};
eat();
the problem was, that you tried to assign a value in the condition foodHere = false. If you want to compare things you need == and if you want to be sure that the types are the same use ===.
But you don't need that condition at all!
The assignment want you to return a boolean value (true or false) and not to print something, so i guess your code should look like this:
var hungry = true;
var foodHere = true;
var eat = function() {
return (hungry && foodHere)
};
eat();

Single = is for assignment, == is for comparison
var hungry = true;
var foodHere = true;
var eat = function() {
if(hungry && foodHere){
console.log("I am hungry");
}else if(hungry && foodHere == false){
console.log("Choose one");
}
};
eat();
Anyways, you don't need the second comparison since if the first one is false it will always go through the else

I just want to give additional information for emilioicai's answer, there are two kind of "equal comparison" in JavaScript
equal to ( == )
exactly equal to ( === )
Reference: http://www.w3schools.com/js/js_comparisons.asp

= is for assignment, == is for value comparison and === is for value and datatype comparison. So you can use == while comparing with the false. But this is not the best practice. We always uses '!' negation operator while converting true to false
var hungry = true;
var foodHere = true;
var eat = function() {
if(hungry && foodHere){
console.log("I am hungry");
}else if(!hungry || !foodHere){
console.log("Choose one");
}
};
eat()
I am using || operator assuming that any one needs to be false.You can go for && if both false are required

Related

How to compare an array with another element with javascript vanilla [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 1 year ago.
Improve this question
I want to do a simple check using the if statement, I'm comparing an element with an array using this function, I want to show the result based on the conditions but when a run the function it didn't execute the first if, even if it equal to one of the elements in the array it goes to the second statement.
function TalkTheTalk(msg) {
const talk = +msg;
const greetings = ["I'm good", "I'm fine", "I'm Ok"];
greetings.map((greeting)=> {
if(greeting === talk) {
MessageEl.innerHTML = '<div> Im so happy to hear that! what can i do for you today ! </div>';
}
else if (greeting !== talk) {
MessageEl.innerHTML = '<div>Sorry I didnt hear !Would you Repeat</div>';
}
else {
MessageEl.innerHTML = '<div>Would you repeat</div>';
}
});
}
function TalkTheTalk(msg) {
// const talk = +msg; This makes it a NaN
const talk = msg;
const greetings = ["I'm good", "I'm fine", "I'm Ok"];
// greetings.map((greeting)=> { map means convert each one to something else, not suitable
const result greetings.find((greeting)=> {
return greeting === talk
});
if (result) {
MessageEl.innerHTML = '<div> Im so happy to hear that! what can i do for you today ! </div>';
} else {
MessageEl.innerHTML = '<div>Sorry I didnt hear !Would you Repeat</div>';
}
}
Javascript unary operator + is for Numbers, not for strings.
console.log(+'hello'); // NaN
There are some issues in your code.
First is const talk = +msg;
it makes greeting === talk will never be true.
And second is map function.
So the last loop condition will be render.
I think you should do like this.
function TalkTheTalk(msg) {
const talk = msg;
var MessageEl = document.getElementById("message");
console.log(talk);
var heargreeting = false
const greetings = ["I'm good", "I'm fine", "I'm Ok"];
greetings.map((greeting)=> {
if(greeting === talk) {
heargreeting = true;
}
else if (greeting !== talk) {
MessageEl.innerHTML = '<div>Sorry I didnt hear !Would you Repeat</div>';
}
else {
MessageEl.innerHTML = '<div>Would you repeat</div>';
}
});
if(heargreeting)
{
MessageEl.innerHTML = '<div> Im so happy to hear that! what can i do for you today ! </div>';
}
}
TalkTheTalk("I'm good");
<div id="message"></div>

JS OR statement just not working

I know this question has been asked a million times but I've gone through just about every method suggested in other threads and cannot seem to figure out why the OR statement in my IF is not working. And would like some explanation as to how to use the OR function if I am doing this completely wrong.
I have the following code
if((a != 'error') || (a != 'stay')) {
//Do something here
}
And regardless if the a is error or stay the code is being executed anyway
I have also tried
if((!a == 'error') || (!a == 'stay')) {
//Do something here
}
And without brackets, but noting seems to work.
Thanks in advance
Your condition is a tautology. It's true no matter what the value of a is. If a is 'error' then a is not 'stay' and vice versa. It seems like what you want is
if (a != 'error' && a != 'stay') { /* ... */ }
You are including the (!) sign together in the brackets which is an error and will not make the logical operator work. You need to put the (!) sign outside and before the bracket. Check this code below for more clarity.
var a = "hello";
var b = "stay";
var c = "error";
if(!(a == 'error') || !(a == 'stay')) {
console.log("Hello");
};
for best practice, you should have it like this
var a = "hello";
var b = "stay";
var c = "error";
if(!(a == 'error' || a == 'stay')) {
console.log("Hello");
};

Why wont the randomization in this code work?

Thank you for answering my original question, and the reason i am simply editing this post for my second question about this code is because the site wont let me make very many questions. my question is why isnt makesjump1 randomly true or false? it always seems to come out true. please help #Yhlas and #codeConcussion
var isjumping1 = true;
while(isjumping1) {
var makesjump1 = Math.random()
if(makesjump1 => .51) {
makesjump1 = true }
else if(makesjump1 <= .50) {
makesjump1 = false }
var jump1 = prompt("Do you choose to JUMP, or let the fairies help you FLY").toUpperCase()
switch(jump1) {
case 'JUMP':
if(makesjump1 = true) {
console.log("You made the jump on your own, so the fairies reward you with a steel sword(9 DMG)")
damage = 9;
weapon = 'steel sword(9 DMG)'; }
else if(makesjump1 = false) {
console.log("You attempt the jump but miss it, and are hanging on by a thread")
console.log("The fairies rescue you, but you got scratched up, doing 3 damge to you.")
health = health - 3; }
isjumping1 = false;
break;
case 'FLY':
console.log("The fairies help you over the pit")
isjumping1 = false;
break;
default:
alert("That was not a choice!")
break; }
}
You're assigning it to true with every loop. Use == instead or just...
while(isjumping1)
while(isjumping1==1) - comparison
while(isjumping1=1) - assignment(always returns true)
The way that you're assigning the random value to makesjump1 is incorrect. It would fail if Math.random() returned a value in the range (0.50,0.51). Instead, try this:
var makesjump1 = Math.random()<0.5;

How to reduce "if statement" conditions? [reduce the conditions inside the if statement]

after days of hard thinking i choose to ask that question. I have if statement with multiple conditions:
//var current is array of arrays of integers
if((current[rot][0] + x)<blocks.length
&& (current[rot][1] + x)<blocks.length
&& (current[rot][2] + x)<blocks.length
&& (current[rot][3] + x)<blocks.length
&& !$(blocks[current[rot][0]+x]).hasClass("blockLand")
&& !$(blocks[current[rot][1]+x]).hasClass("blockLand")
&& !$(blocks[current[rot][2]+x]).hasClass("blockLand")
&& !$(blocks[current[rot][3]+x]).hasClass("blockLand"))
{
//something to happen here ONCE!
}
Because i want something inside to happen just once i think i cant use for loop.
So my question is: is there a possible way to reduce the conditions number? and how?
P.S.: Yes i figured out that i can use flag (true/false) inside and do my stuff outside this if, in another if - but i think that not always gonna work, because for every loop the flag will be different.
var b = true;
for (var i = 0; i <= 3; i++) {
// In two lines for being clear, but it's possible just in one
b = b && (current[rot][i] + x)<blocks.length
b = b && !$(blocks[current[rot][i]+x]).hasClass("blockLand");
// You could speed it up this way.
if(!b) break;
}
if (b) {
//something to happen here ONCE!
}
I think I understand what you are asking but let me know if there is anything else I can do.
JavaScript has a ternary (conditional operator) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
This operator allows you to assign true/false values based on an internal if/else condition.
Here is some code for you to explain this...
window.onload = function() {
var one = 1;
var two = 2;
console.log(one > two ? "greater" : "not greater");
};
You can also use a Switch statement which you can read about here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch.
Here is an example of a switch statement.
window.onload = function() {
var string = "testing this out";
switch (string) {
case "testing this out":
console.log('testing this out found in condition one');
break;
case "testing":
console.log('found testing');
break;
default:
console.log('not found');
break;
}
};
Let me know if I can improve this.

mutation(["hello", "Hello"]); - Return true if Hello is equal to hello but my code returns false? [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 7 years ago.
Improve this question
I am comparing t to u which returns the same string which is "HELLO" but my
code returns false instead of true. I have also tried the array.indexOf()
function and still the same result. Help please.
function mutation(arr) {
var uppercaseArray = arr.toString().toUpperCase().split(","),
t = uppercaseArray[0].toString();
u = uppercaseArray[1].toString(),
n = t.localeCompare(u);
if (n = 1) {
return true;
} else {
return false;
}
}
mutation(["hello", "Hello"])
if(n = 1) will always be true, I think you're looking for == or ===
Maybe you can change to if (n == 0) {
function mutation(arr) {
var uppercaseArray = arr.toString().toUpperCase().split(",");
t = uppercaseArray[0].toString();
u = uppercaseArray[1].toString();
var n = t.localeCompare(u);
if (n == 0) {
return true;
} else {
return false;
}
}
console.log(mutation(["hello", "Hello"]));
The localCompare function returns 0 when they are equal.

Categories