How to avoid to repeat a variable - javascript

Hi I'm new to javascript and was wondering if the community could help me in re-writing more logically the following snippet:
var userAnswer = prompt("Are we there yet?")
while ((userAnswer != "yes" && userAnswer != "yeah") && (userAnswer.indexOf("yes") === -1)) {
var userAnswer = prompt ("Are we there yet?")
}
alert ("Yuppie we made it!")
the part that I think could be improved is in the while loop when I have to repet the entire string of var userAnswer = prompt....
there must be a dry way of doing it. Any help would be much appreciated!

Since you want to run ask for a value at least once you could use do-while instead. You could define variable within the do block, it still will be hoisted.
do {
var userAnswer = prompt("Are we there yet?")
} while ((userAnswer != "yes" && userAnswer != "yeah") && (userAnswer.indexOf("yes") === -1))
alert("Yuppie we made it!")
PS. I kept the condition assuming it works for you.

Instead of prompt to enter free text use confirm that will return true or false:
while (!confirm("Are we there yet?"));
alert("Yuppie we made it!")

A way of doing it without using a while loop.
var answer = prompt ("Are we there yet?", "YES or NO")
answer != "yes" ? prompt ("Are we there yet?", "YES or NO"): alert("We made it !!");

Related

How to make an if statement with conditions that include "and" in javascript

I am trying to make a password and confirmation password match, without them both being just left blank.
I would like to add in this part about the password fields not being able to be left blank, in the if statement, by saying the passwords have the same value, and these values are not blank.
The function worked fine when it was just the if statement, saying that the passwords had to match in order for the welcome alert to come up, and have found that the and symbol in javascript is && but i don't know how to use it in the context.
var check = function() {
if (document.getElementById('psw').value ==
document.getElementById('psw-repeat').value)
&&
(document.getElementById('psw').value) != ""
&&
(document.getElementById('psw-repeat').value) != "" }
else {
alert("passwords do not match")
}
}
I would expect this code to say that the passwords haven't been filled out, if they haven't, to say welcome if the password and confirmation password match, and to say the passwords do not match if they do not match.
I'm not sure what I've done wrong but would love if anyone could help.
:))
You're not closing the whole if statement with ()
Okay, best way to do conditions it like following.
why best
optimized, you don't need to get values from dom again and again for
condition checking
easy to read if condition.
If code is not readable then not the best code
So always try to break the conditions
function() {
var password = document.getElementById('psw').value;
var password_repeat = document.getElementById('psw-repeat').value;
if (password == password_repeat && password != "" && password_repeat != "")
{
// code ..........
}
else
{
alert("passwords do not match")
}
}
For better code checking and styling, use some IDEs like VSCode Atom Bracket
but personally I like the VSCode
The only real problem is out-of-place parentheses and curly braces, but this way adds a couple of improvements beyond those simple fixes.
// Select HTML elements
const psw = document.getElementById("psw");
const pswRepeat = document.getElementById("psw-repeat");
const checkBtn = document.getElementById("checkBtn");
// Listen for button clicks
checkBtn.addEventListener("click", check);
// Validate passwords
function check(){
if(pswRepeat.value === psw.value && psw.value != ""){
// We know they are the same, and psw is not empty (so neither is pswRepeat)
alert("good");
}
else{
alert("passwords do not match");
}
}
<input id="psw" />
<input id="psw-repeat" />
<button id="checkBtn">Check</button>
You forgot to close the parenthesis.
You need better indentation to detect these kinds of problems early and some separation of logic to keep the code readable.Something like this :
var check = function() {
if (isValid()) {
//Welcome here
} else {
alert("passwords do not match")
}
}
function isValid() {
var psw = document.getElementById('psw').value;
var repeatPsw = document.getElementById('psw-repeat').value;
//Logic to check for password
if (psw == repeatPsw &&
psw != "" &&
repeatPsw != ""
)
return true;
return false;
}

Whats wrote with this break;

After adding break, my code no longer works.
alert("Warning: Game is made for the age of 18 and over.");
var a = prompt("Are you ready to enter this game?");
if (a == "yes") {alert("Entering");}
else if (a == "no") {while(true)
var a = prompt("Are you ready to enter this game?");
if(a == "yes") {break; alert("Entering");} }
You have a few syntax errors in your JavaScript. You are missing out on a curly brace. The break statement needs to be after the alert statement. See the following snippet after the fixes and try to learn your mistakes.
alert("Warning: Game is made for the age of 18 and over.");
var a = prompt("Are you ready to enter this game?");
if (a == "yes") {alert("Entering");}
else if (a == "no") {
while(true) {
//var b = prompt("Are you ready to enter this game?");
if(a == "yes") {
alert("Entering");
break;
}
}
}
break; alert("Entering");
It's to late to alert after breaking as it immediately exits the loop and doesn't execute instruction after itself there.
I believe you intend to prompt the user repeatedly until he answers yes. In that case, use this code:
alert("Warning: Game is made for the age of 18 and over.");
let response = "";
while(response !== "yes") {
response = prompt("Are you ready to enter this game?");
}
alert("Entering");

Alert message is wrong

I am currently new to JavaScript and am learning in school! There is an assignment that I am doing by creating a game but the alert keeps popping up with the wrong one. Every time it alerts as "You found a match!" for every card, however this is not supposed to happen. I have been trying to figure this out for the last hour. Thanks
var cards = ["queen", "king", "queen", "king"];
var cardsInPlay = [];
var cardOne = cards[0];
cardsInPlay.push(cardOne);
console.log("User flipped " + cardOne);
var cardTwo = cards[1];
cardsInPlay.push(cardTwo);
console.log("User flipped " + cardTwo);
if (cardsInPlay.length === 2){
cardsInPlay[0] === cardsInPlay[1];
alert("You found a match!");
} else {
alert("Sorry, try again");
}
You have a simple syntax error.
if (cardsInPlay.length === 2){
cardsInPlay[0] === cardsInPlay[1];
By putting your second conditional inside the bracket {, you've made it ineffective. Try this:
if (cardsInPly.length === 2 && cardsInPlay[0] === cardsInPlay[1]) {
The condition always goes inside the parenthesis ( ). If it's outside of it, it won't work.
Typing cardsInPlay[0] === cardsInPlay[1]; when they aren't equal is effectively like typing false;. It's technically valid, but doesn't do anything.
I think you ment to put the condition like below:
if (cardsInPlay.length === 2 && cardsInPlay[0] === cardsInPlay[1]) {
alert("You found a match!");
}

Why is only the first case of my switch list working correctly?

For the life of me, I can't figure out what's wrong with it. When I run this script, the first 'STAY' case works just fine. Running any of the other cases gives me an error (undefined is not a function).
Ran it thru my JS checker and it looked ok on there. Googled it and everyone else I'm seeing with the same problem has been told their breaks are either used incorrectly or not there. All of the syntax looks right to me from what I've learned. Compared it against the sample 'game' and it looks very similar to how they did it. What am I doing wrong?! Thank you for any help
var user = prompt("You see God. Do you want to STAY, PUNCH HIM, or CRY?").toUpperCase();
switch(user) {
case 'STAY':
var curious = prompt("Are you a curious person?").toUpperCase();
var insight = prompt("Are you an insightful person?").toUpperCase();
if (curious === "YES" && insight === "YES") {
console.log("Maybe it was a good idea to stay and speak to him");
} else if (curious === "YES" || insight === "YES") {
console.log("Well, maybe you can scrunge up something to say");
} else {
console.log("Why would you stay if you have nothing intelligent to say?");
}
break;
case 'PUNCH HIM':
var strong = prompt("Are you ridiculously stronger than God?").toUpperCase();
var fast = prompt("Are you faster than a minute man?").toUpperCase();
if (strong === "YES" && fast === "YES") {
console.prompt("You still dead, but not as dead as you would've been");
} else if (strong === "YES" || fast === "YES") {
console.prompt("One ain't good enough, homie");
} else {
console.prompt("Slow and weak? Bad choice, dag");
}
break;
case 'CRY':
var convincing = prompt("Are you superbly convincing with crying?").toUpperCase();
var female = prompt("Are you a female?").toUpperCase();
if (convincing === "YES" && female === "YES") {
console.prompt("You'll prolly be ok, boo");
} else if (convincing === "YES" || female === "YES") {
console.prompt("Hope you're a female");
} else {
console.prompt("You dead!");
}
break;
default:
console.prompt("Answer the question with the supplied answers");
}
Use console.log instead of console.prompt.

How do i check for a specific value in a field using javascript?

The javascript checks form values for not being empty
if(!$('nradulti').value){ok=2;}
if(!$('transport').value){ok=2;}
if(!$('plata').value){ok=2;}
if(ok==1){return true;}
else if(ok==2){
$('mesaj').innerHTML="
<span class='notarea'>Please complete all fields.</span>";
return false;
}
I need to add a new variable called spam for captcha and check that it is equal to a certain number, e.g. "what's 2+2" and the script to proceed only if the number is 4
What line do i need to add please?
Thanks!
You can accomplish this with a basic equality check. I'm not exactly sure what framework your using, but given your other calls.
if(!$('spam').value == '4'){
ok=2;
}
Add this line to your js file and declare the value for spam before this.
if($('spamInput_field_selector').value!=spam){ok=2}
Try this way
var answer = document.getElementById("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var spam = digit1 + digit2;
if(answer == ""){
alert("Please add the numbers");
}else if(spam==answer){
// call script //
}

Categories

Resources