Simple if-else statement always returns true - javascript

I am trying to make a simple if-else statement, but when I run the code, it always returns true, even if I enter something in the prompt that I know should be false. I have ran it through JsFiddle, and it seems that the code snippet is perfectly valid.
var captchaTest = 5;
var captchaInput = prompt('What is five plus five?');
if ('captchaTest + captchaInput = 10') {
alert('You passed, you may continue'); window.location.href = 'pagepass.html';
}
else {
alert('Failed, try again.'); window.location.href = 'main.html';
}
Can someone tell me what I did wrong?

Non-empty strings in JavaScript are truthy. 'captchaTest + captchaInput = 10', when evaluated as Boolean, is true.
You need to remove the quotation marks and change = to ==:
if (captchaTest + captchaInput == 10)

Apart from the answer that other provided I would also make a point that as per your captcha question, your condition should be like this
if (captchaInput == 10){
alert('You passed, you may continue'); window.location.href = 'pagepass.html';
}
else {
alert('Failed, try again.'); window.location.href = 'main.html';
}
I don't see any use of the variable captchaTest

You shouldn't be using a 'captchaTest + captchaInput = 10' as it is a String and always evaluates to true unless it is an empty one.
Also you should use comparison operator == instead of assignment operator =
So remove the quotes
if ((captchaTest + captchaInput) == 10)

Related

A simple question regarding conditional statements and defining variables

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.
You don't use assignment operators (=) inside conditionals. Inside conditionals, you need to use comparison operators (==, !=, >=, <, etc.)
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
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)

Variable Returns False, but if statement doesn't acknowkedge it

I have an if statement that is supposed to execute code if a variable returns false, but even though I have checked and made sure the variable returns false, the code does not execute. Here is the code:
SOLUTION: i seem to have accidentally misplaced the if statement, and have moved it and fixed the program. thank you everyone who has helped me fix my problem
function letterCheck() {
var wordToGuess = puzzle;
var letterToGuess = guess;
console.log(letterToGuess);
matched = false;
for (x = 0; x < wordToGuess.length; x++) {
if (letterToGuess === wordToGuess[x]) {
console.log('Your guess was correct!');
console.log('You have', 6 - parts, 'incorrect guesses remaining');
blanks[x] = letterToGuess;
console.log(blanks);
var fillBlank = '';
for (y = 0; y < blanks.length; y++) {
fillBlank += blanks[y];
}
document.getElementById('puzzle').innerHTML = fillBlank;
matched = true
win++
if (win === puzzle.length) {
setTimeout(() => alert("You win!"), 100)
}
break;
}
}
}
//this is the if statement that is not working
if (this.matched === false) {
console.log("Your guess was incorrect!");
parts++;
graphics[parts - 1]();
console.log('You have', 6 - parts, 'incorrect guesses remaining');
}
"matched" and "this.matched" are 2 different variables. "matched" is global, "this. matched" is local to the function.
To fix: Use either of "matched" or "this.matched" everywhere - don't mix and match.
Some basic questions need to be asked first. What programming language are you using?
I will assume that you are using JavaScript, because that is the only language that comes to mind that has a === operator. The identity operator === behaves identically to the equality operator == except no type conversion is done. The identity operator requires that all types must be the same types to be considered equal.
Therefore, the == equality operator will compare for equality after doing any necessary type conversions, while the === identity operator will not do the conversion, so if two values are not the same type, the identity operator will simply return false.
Both operators execute at approximately the same speed, so if I were you, I would switch to the equality operator and try again. Let me know what you get!
Reference: http://www.c-point.com/javascript_tutorial/jsgrpComparison.htm

Else statement does not work

I don't know why my else statement didn't work.
It's my first time that actually happened and I checked using console.log().
This is my code:
setTimeout(function() {
var b = 2;
var d = 80000;
if ("div[class='resultInfo resultLose']") {
setTimeout(function() {
var a = ($("input[name='_4']").val().replace(/\s+/g, ''));
var c = a * b;
$("input[name='_4']").val(c);
$("input[value='Play!']").click();
}, 1000);
} else if ("div[class='resultInfo resultWin']") {
setTimeout(function() {
$("input[name='_4']").val(d);
$("input[value='Play!']").click();
}, 1000);
}
}, 4500);
I have tried to:
delete the setTimeout in if
delete the "if ("div[class='resultInfo resultWin']")"
This only uses first if even the elseif is true, I don't know what to do.
Your current if and else/if conditions are just testing the truthiness of a random string which will always evaluate to true. Since the first condition evaluates to true, you will always skip the else if condition (even though that will also evaluate to true in this instance).
What you actually seem to want to test is whether or not there are elements that exist that match the strings you have as selector strings. If that's the case, your simplest fix would be to change your if and else statements to look more like jQuery statements and checking the length of the result.
if ($("div[class='resultInfo resultLose']").length > 0)
and
else if ($("div[class='resultInfo resultWin']").length > 0)
You are having a non-empty string inside your if condition, which evaluates to true every time. So else block will never be reached.
Your code doesn't make sense.
You aren't entering the else if because your if will always evaluate to true.
if ("div[class='resultInfo resultLose']") will always be true, as you're not doing any comparision, you're evaluating a string. So that's the same as doing if (true).
I supose you're missing some code there, like a JQuery selection or something like that.

javascript isNaN() function not working?

I have a function to test if a prompt input is a number, like so:
function myFunction()
{
var person = prompt("Please enter your name", "");
if (person != null)
{
if(isNaN(person))
{
document.write("hello " + person + "<br><br>");
}
else
document.write("You gave me a number");
}
else
{
document.write("You didn't answer.<br><br>");
}
}
but every time I enter a number it keeps outputting hello + the number. I've been googling this function for quite some time and it doesn't make sense to me, it seems like it should work. Why is person returning true?
NaN is a special value in Javascript. What isNaN does is check to see if the value passed is equal* to this special value. If you want to check if something is, say, not a stream of numbers, you can use a regular expression:
if (!/^\d+(\.\d+)?/.exec(person)) {
Or parse the value as a number and see if it converts back to the same string:
var n = parseFloat(person);
if (n.toString() !== person) {
*There's a reason that we don't use === but it's outside the scope of this answer.
The isNaN function checks if a value is NaN. NaN is a value that occurs when making operations that require numbers with non-numbers. Please see the documentation.
However the function does not check if the value is of type number. Too check if a value is of type number use the typeof operator
typeof person === 'number'
Your code is the correct way of using the isNaN method. However for anyone else reading this post I have seen a strange anomaly where the documented usage of IsNaN hasn't worked properly and I got around the problem by combining the parseInt method with the IsNaN method. According to the W3c web site (https://www.w3schools.com/jsref/jsref_isnan.asp) the IsNan('123') should return false and IsNan('g12') should return true, but I've seen scenarios where this isn't the case.
If you're having trouble getting the documented methods to work try this code below:
var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}
Alternatively you can try this method which is well tested.
function isNumber(searchValue) {
var found = searchValue.search(/^(\d*\.?\d*)$/);
//Change to ^(\d*\.?\d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}
Hope this helps.

Javascript syntax issue

Here is my jsFiddle
Its on the Phone method, no the name one
Now is this line right? I only want it to be true if the first 3 letters are 087
var RightStarting3 = value.substring(0,2) == (087);
if (BlankPass || LessThan10 || RightStarting3 || GreaterThan10 || (HasSpaces > 0))
{
document.getElementById('Phone').style.background = "red";
return false;
}
else {
document.getElementById('Phone').style.background = "white";
document.getElementById("PhoneTick").style.visibility="visible";
return true;
}
var RightStarting3 = value.substring(0,3) === ('087');
value.substring(x) returns a string and 087 and 87 mean the same to javascript interpreter. You should change one of the datatypes so that they match...
Either the substring to an integer:
var RightStarting3 = parseInt(value.substring(0,2)) == 87;
Or the value you're comparing against to a string:
var RightStarting3 = value.substring(0,3) == "087";
Secondly -- you are invoking ValidateName() immediately (in your assignment to NamePass). Is this really necessary? There will be empty values on page load.
I think with the javascript substring(x,y) method, the y value is the value at which to stop the selection. So in your example the first 3 characters will not be selected and instead the first 2 characters will be selected.
var a = "123";
// this returns "12"
alert(a.substring(0,2));
You probably want to use var RightStarting3 = value.substring(0,3) == ('087'); instead.
KingKongFrom's answer is correct, I would add that you should make sure that value (whatever that is) isn't null first, cause if you try to call substring on null it will thrown an exception and die.

Categories