Reputation: 33
I'm wondering 1. why the console is throwing out a specific result 2. how to get the console to throw out the result I want based on the code
I've tried both removing the else condition and adding it, but I'm stuck because I don't know what the code is thinking.
isMarried = false;
if (isMarried = false) {
isMarried = 'Nope, not at all! ';
}
console.log(firstName + ' is a ' + age + ' year old ' + job + '. Is he married? ' +isMarried );
//This outputs false for isMarried instead of "Nope, not at all!"
If I add an else like so:
if (isMarried = false) {
isMarried = 'Nope, not at all! ';
} else {
isMarried = 'Oh yeah';
}
//The same code outputs "Oh yeah." I'm a bit confused why it's happening like this. Any thoughts?
Basically, I expected the computer to see isMarried as a false boolean, and if this is the case, I wanted to set the variable to the string seen above. Otherwise, if I changed it to true, for example, the it would be a different string.
Upvotes: 0
Views: 66
Reputation: 446
Try this, Give me green tick if this code satisfied ya..
var isMarried = false;
if(isMarried==false){
isMarried = "Not at all";
}else{
isMarried = "Oh yeah";
}
console.log(isMarried)
Upvotes: 0
Reputation: 3108
You are assigning a value to your isMarried
(false
) inside the IF statement .. you need to use compare operators like ==
a == b // this operator will return a `Boolean` value (`true` Or `false`)
a = b // this operator will return the value of `b` (right value)
So :
isMarried = false // this will return the right value (false) which means the IF statement
// won't work and the else code will be auto executed
Upvotes: 1
Reputation: 2070
You don't use assignment operators (=) inside conditionals. Inside conditionals, you need to use comparison operators (==, !=, >=, <, etc.)
Upvotes: 2