How do you compare two variables in Javascript? - javascript

I am trying to compare two different variables with each other and execute certain code if they match.
The variables are: userInput and commandOne
Firstly, a button is pressed to call myTest().
function myTest() {
userInput = document.getElementById("runBox").value;
testInput();
}
The function gathers text from an input box on my page and stores it in a variable named userInput. It then calls my next function...
function testInput() {
if (userInput = commandOne) {
document.getElementById("demo").innerHTML += "<br>executed!";
}else {
alert("this is an alert message");
}
}
This part is designed to test if userInput matches the variable named commandOne. (commandOne's value is currently set to "ip").
If it does match, it will add text (executed!) to a paragraph with the "demo" ID. If it does not match, it will alert the user in an alert box.
My problem is that the variables do not seem to be comparing. No matter what the user puts into userInput the text (executed!) is always outputted to my paragraph. It appears that the browser thinks they are matching when they are not.

You missed your operator in the if statement.
if (userInput == commandOne)
== compares value
if (userInput === commandOne)
=== compares values and data types.

You had used the wrong operator. You must use == sign instead of a single = sign.
function testInput() {
if (userInput == commandOne) {
document.getElementById("demo").innerHTML += "<br />executed!";
} else {
alert("This is an alert message");
}
}
A single = sign (=) means that the value on the left side of the sign gets the same value as on the right side of the sign.
Double= sign (==) means that two values on the each side of the sign are equal.
Triple = sign (===) means that both the values are equal and of the same type.
Click here for more information.

As mentioned - you have the wrong operator - however i just wanted to show an alternative to the logic: - the ternary operator - makes it much nicer and cleaner to read and reduces the if / else markup.
Incidentally - given the code provided - you don't even need to call teh second function - the entire thing can be done in one function. Also - if the alert is purely to demonstrate the "else" outcome - you should investigae the use of the console.log() - its bettter for debugging.
To explain the ternary operator - the condition to be met is written first (note that there is no "if" preceding it. Following it - use the "?" charcter to give an action if hte comparison is true and use a ":" character for if the outcome is false.
Note that I always write the ternary operators on the three lines as i have done here - I find it easier to read - it can all be written on one line - personal preference.
And last thing - no ";" at the end of the "true" portion of the statemtn - it is all one expression that I happen to have written over three lines.
function testInput() {
userInput == commandOne
? document.getElementById("demo").innerHTML += "<br>executed!"
: alert("this is an alert message");
}

Related

while loop terminating early with nested if statement

I'm writing a condition check for a simple input via prompt() in JavaScript. The idea is to repeat a prompt until the user supplies a positive integer.
In particular, if I submit a negative integer, it correctly prompts me again via case 3. However, if I answer the second prompt again with a negative integer, the code unexpectedly leaves the while loop.
In the if statement:
Case 1: checks if the user 'cancels' the prompt box (or returns an empty string), in which case I set a variable 'cancelGridCreation' to 'true' to later cancel the encapsulating process (outside of the included code), and then terminate the while loop by setting the variable 'waitingForQualifyingAnswer' to 'false'.
Case 2: checks if the response is an acceptable integer (number, integer, positive), and sets the conditional variable 'false' to terminate the while loop.
Case 3: prompts the user again, with the idea that the newly entered data will be checked again by the same 3 'if' cases.
User inputs matching cases 1 and 2 seem to work fine. However, as mentioned above, entering a negative integer 2 times terminates the while loop. See the console output that I received, entering -10 and then -20. As well, the console.log() outputs don't seem to occur in an order matching their location in the code (perhaps a processing time-lag issue?). You'll see that the console.log() from case 3 outputs before the "initial size entered" console.log(), which is coded before the while loop even starts.
Similar results seem to occur whenever case 3 is followed by another case 3 (regardless whether input is negative integers, decimals, or strings), as well as case 3 followed by case 1 (of course, here case 1 would terminate the loop, but the console log statements still seem to occur out of order).
Link to interactive code at JSBin: https://jsbin.com/koheku/1/edit?js,console
JavaScript Code:
let cancelGridCreation = false;
let waitingForQualifyingAnswer = true;
let answer = prompt('Please enter the number of rows/columns, as a positive integer:', '16');
let gridSize = parseFloat(answer, 10);
console.log('initial size entered: ' + gridSize);
while (waitingForQualifyingAnswer === true) {
console.log('top of while loop');
if (answer == null || answer == "") {
console.log('prompt - canceled');
cancelGridCreation = true;
waitingForQualifyingAnswer = false;
} else if (typeof gridSize === 'number' && gridSize % 1 === 0 && gridSize > 0) {
console.log('prompt - good answer: ' + gridSize);
waitingForQualifyingAnswer = false;
} else {
console.log('prompt - BAD answer: ' + gridSize);
answer = prompt('Incorrect format entered. Please enter the number of rows/columns, as a positive integer:', '16');
gridSize = parseFloat(answer, 10);
console.log('new size entered: ' + gridSize);
}
console.log('end of while loop');
}
console.log('done:');
console.log(gridSize);
Console Output was as follows (having entered -10 at the first prompt, and -20 at the second prompt):
"prompt - BAD answer: -10"
"top of while loop"
"initial size entered: -10"
"new size entered: -20"
"end of while loop"
"done:"
-20
I'm pretty new, and realize there may be more concise ways to accomplish this. I'm interested in suggestions, however, I"m also keen to figure out why the while loop is ending when only case 3 inputs are being submitted.
Please note: The console.log() statements are only of a simple means of debugging. I realize a parseInt() would truncate any decimals, but I chose to allow integers as an acceptable size.
Thank you for any advice you can offer :)

JavaScript: Guessing password

Another JavaScript question I found on the internet, but I couldn't figure out how it works. The question basically asks what is the password. The password doesn't depend on external resources and it doesn't change over time (do not depends on current date or time). Also, question says that there is exactly one correct password. I am JavaScript begginer, so I apologize if this is a simple standard interview question. This is the function:
const checkPassword = a => {
if(a !== (a += '')) return false;
if(a !== (a = a.replace(/[^a-z]/g, ''))) return false;
a = (a.match(/^.{6}|.+/g) || []).join(({} + {})[7]);
a = [...a].reverse().join([] + []);
try{
Function('\'' + a + '\';++1..a')();
return false;
}catch(a){
return true;
}
};
alert(checkPassword(prompt('Enter password:')) ? 'Correct password.' : 'Wrong. Try again.');
At first, this didn't look hard too me, because everything is open, so I can simply follow code line by line and figure out how does it work. Ok, I understand that in the first line of check function they check if password is a string (why? Can it be something else?). Then, if I understood that regex well, they check if script consists only of small alphabet letters (or am I wrong?). So, for now I know I know it must consists only of letters. After that they perform some weird regex I cannot fully understand. It seems to me that this regex will match whole string, so why they are joining it?
Then they reverse string and join by an empty array (is it same as normally reversing string or what?). After that in try block I cannot understand what is happening? What does Function constructor actually do here? What is the meaning of ++1..a? Im just wondering how to approach questions like this one?
I'll jump straight to the key line:
Function('\'' + a + '\';++1..a')();
It creates and then immediately executes a new function with a function body set from that weird-looking string. If the variable a is, say, 'abcde' then the new function's body will be:
'\'' + 'abcde' + '\';++1..a'
which is like having this function:
function() {
'abcde';++1..a
}
Or with some whitespace:
function() {
'abcde';
++1..a
}
Note that the string on the first line is dynamically set based on what is in the a variable, but the ++1..a part is hardcoded.
Now, noting that the function is inside a try/catch() block, if the new function runs without error then checkPassword() will return false, but if the new function crashes checkPassword() returns true. In other words, it is expected that the behaviour of that dynamic function will change to crash or not depending on what is in the string from the a variable.
So what string, by itself on the first line of a function, can possibly change the behaviour of the function? There is only one possibility, and that is (hover to reveal spoiler):
'use strict' ...which would have to be entered as the password 'tcirtsesu' because of the first few lines of the function doing the .match() and .reverse().
With that in mind it doesn't even really matter what the ++1..a part does, but it is basically taking the .a property of 1, which is undefined, and trying to increment it, which...
is an error in strict mode but not in non-strict mode.
For completeness, a very brief explanation of these lines:
a = (a.match(/^.{6}|.+/g) || []).join(({} + {})[7]);
a = [...a].reverse().join([] + []);
The .match() function returns an array. /^.{6}|.+/g matches the first six characters, OR any number of characters, which means that "abcdefghijkl".match(/^.{6}|.+/g) returns ["abcdef", "ghijkl"]. Then ({} + {})[7] is basically just a space character because {} + {} is the string "[object Object][object Object]". So that line basically inserts a space after the sixth character.
The .reverse() line then reverses the result of that.

what would happen if you use two equals rather than only one in your execution block after an if conditional in JavaScript?

I am still learning, so I'm sorry if my question is not well formatted.
I was trying to write a function to insert a word to a string in a specified position, however I made a mistake which is writing two equal signs == rather than one in the execution block and this resulted in wrong output when tested.
However, I already know that the execution of code after if/else needs to not be boolean and I noticed this typo and I corrected it by removing one equal sign and the function worked perfectly fine but I was just left wondering why have I never questioned the significance of strictly having one equal sign when executing code after if conditionals.
so here is the wrong code:
function insert(original,to_insert,position){
if (to_insert == "undefined" && position == undefined){return original;}
else if (position == undefined){position == 0}
var x = original.slice(0,position);
var y = original.slice(position);
console.log(x + to_insert + y);
}
insert('We are doing some exercises.','JavaScript ');
//Wrong output >>>> "We are doing some exercises.JavaScript We are doing some exercises."
insert('We are doing some exercises.','JavaScript ', 18);
//correct output>>>> "We are doing some JavaScript exercises."
and here is the correct code:
function insert(original,to_insert,position){
if (to_insert == "undefined" && position == undefined){return original;}
else if (position == undefined){position = 0}
var x = original.slice(0,position);
var y = original.slice(position);
console.log(x + to_insert + y);
}
insert('We are doing some exercises.','JavaScript ');
//correct output >>>> JavaScript We are doing some exercises."
insert('We are doing some exercises.','JavaScript ', 18);
//correct output>>>> "We are doing some JavaScript exercises."
would you please explain what happens inside my wrong code, like what causes the function to not run properly when booleans were used, obviously the function runs once at a time, so what difference would an absolute value of position make compared to a variable value of position.
Thanks in advance
else if (position == undefined){position == 0}
In your wrong code, position remains undefined since you did not do an assignment, you simply checked if position (which is undefined) is equal to 0
So, when you did var x = original.slice(0,position); slice() simply ignored the 2nd argument, which in this case is undefined and sliced from start to end, which is the default behaviour in case the 2nd argument is not used.
From MDN:
The slice() method extracts a section of a string and returns a new string.
str.slice(beginSlice[, endSlice])
endSlice
Optional. The zero-based index at which to end extraction. If omitted, slice() extracts to the end of the string. If negative, it is treated as sourceLength + endSlice where sourceLength is the length of the string (for example, if endSlice is -3 it is treated as sourceLength - 3).
In your case, since you pass undefined (because position == undefined), it's like you omitted it
One equal is to assign values to variables, two equals are for camparing two variables. This is the simplest way to explain it.
= - assigning operator
== - comparing operator
if (position == undefined){position == 0}
This mean if your position is undefined position must be 0. Like it should be 0 but you are not defining it. Two equals is usually use to do comparution actually : does position is equals to 0
However one equal mean you assign the value 0 to position.
I can see two problems in your code.
if (to_insert == "undefined" && position == undefined){return original;}
Here you are checking if to_insert is equal to the string "undefined", but not undefined.
else if (position == undefined){position == 0}
Writing position == 0 will just return a boolean. So in this case, it'll return false (because it execute only if position == undefined returns true).
So it's like if in your code, you had a false between two lines, and you don't change the value of any variable.
else if (position == undefined){position = 0}
By writing only one =, you assign the value 0 to the variable position.
So, when you call the slice() method, the second argument is still undefined, so the method ignore it and just slice the string to the end.
Hope I helped you understand !
You're essentially asking, "What is the difference between using one equals sign (=) and using two equals signs (==)?"
Assume we have the following initialization for both examples:
var pikachu_hp;
One equality sign (=):
pikachu_hp = 50;
This sets the variable, pikachu_hp, to have the Number data type with a value of 50.
Two equality signs (==):
pikachu_hp == 60;
This compares the value (not data type, that's three (===) equals signs in JavaScript) of pikachu_hp against what is on the right hand side; in this case, that's the Number 60. If pikachu_hp has a data value of 60, the expression returns true. If pikachu_hp has a data value of anything else but 60, the expression returns false. Again, I call this an "expression" because it does not equate to anything; it represents either a true or false value.

If statement in a switch

I am working on a question for a course for learning javascript. I am running into trouble trying to add an if statement inside of a switch. I currently have:
var user = prompt("Are you ready for battle?!").toUpperCase();
switch(user) {
case'YES':
if(YES && NO) {
console.log("Great, let's do it.");
} else {
console.log("Bye");
}
console.log("Great! It will be a long exciting battle.");
break;
case'NO':
console.log("Come back when you are ready.");
break;
case'MAYBE':
console.log("Go away. This is only for the brave");
break;
default:
console.log("You obviously do not belong here. It was a simple yes/no question.")
}
The question is this:
Add some if/else statements to your cases that check to see whether one
condition and another condition are true, as well as whether one condition
or another condition are true. Use && and || at least one time each.
The error I am getting is this: ReferenceError: YES is not defined
What can I put in the if's condition to make this work or how do I define YES?
It would appear that you have two problems working against you here.
First is the issue pointed out in comments that you're treating YES and NO like variables, and they aren't. To avoid robbing you of the opportunity to learn by providing a corrected version of your code, I'll only give relevant examples.
var word = "test";
// If we compare against the string literally, it will have an error
// because it's looking for a variable with that name.
if (word === test) { } // ReferenceError: test is not defined
// we fix this by quoting what we're comparing against
if (word === "test") { } // Code inside the block would be executed :)
// But what about checking the value of "test" by itself?
// A string is "truthy", meaning that it passes the conditional test always.
if ("test") { } // Code would be executed always regardless of the content of var word
// Stringing multiple constants together doesn't make sense
if ("test" && "word") { } // This is equivalent...
if (true && true) { } // ... to this, which doesn't make sense
This brings us to the second problem you're trying to solve. The requirements for your problem specify checking if one condition AND another are true, as well as one condition OR another. The problem is that you only have one conditional to check: the status of the variable user.
It only makes sense to test the condition of something if you don't know what it is. Input received from a user is a perfect example. So I'd recommend that you take more inputs from the user such as name, age, gender, shoe size, or anything else. You can then check conditions as follows:
// You would need to store user input in variables username and age previously...
if (username === "vastlysuperiorman" && age < 13) { console.log("You're awfully young!"); }
// Or to only allow people within an age range...
if (age < 13 || age > 31) { console.log("You must be between 13 and 31 years old to play this game!"); }
Once you have multiple conditions to check, you can check them anywhere--inside a function, inside a case statement, inside another if. It doesn't matter. Just add an if block and test the conditions. :)

JavaScript: an if statement is changing outcomes of a random generator?

Basically I'm creating a program similar to a blackjack program where two cards are dealt according to a random number generator, with the possibility of the same card being dealt twice at the same time (i.e. two Queen of hearts showing up at once) and I want to create a counter of how many times that event occurs, but when I implement an if statement, it affects the outcome so that the two cards are ALWAYS the exact same...can someone tell me what I'm doing wrong here? The code is as follows:
function dealHand() {
var randomCardOne = Math.floor ((Math.random() *13) +2);
var randomCardTwo = Math.floor ((Math.random() *13) +2);
if (randomCardOne = randomCardTwo) {identicalCards()};
}
var identicalPairs = 0;
function identicalCards(){
document.getElementById("identical").value=++identicalPairs;
}
You are assigning the value of one card to another
if (randomCardOne = randomCardTwo) {identicalCards()};
should be
if (randomCardOne == randomCardTwo) {identicalCards()};
In the first case you are simply evaluating if randomCardOne is "truthy" after being asigned the value of randomCardTwo.
Consider if you might want to use === instead of == since
2 == '2' // yields true
2 === '2' // yields false
It's not an issue in this case but it might be in others so it's good to be aware of this. I try to stick with === since it is more strict.
You're using =, that's an assignment operator in JavaScript. You should be using ==
e.g.
if (randomCardOne == randomCardTwo) {identicalCards()};

Categories

Resources