Prompt JavaScript If Else Unexpected Token else - javascript

I'm teaching myself JavaScript using Code Academy and I'm trying to make some simple code so that when prompt asks a question, the user reply gives a response.
example.
prompt says "what's your favourite colour?"
user says "blue"
response "that's the same colour as the sky!"
But when I try to add different options, I get Syntax error: unexpected token else.
I tried making it so that if I asked a question, the reply gets a response but anything else gets a response.
Here's the code.
prompt("what do you want?");
if ("coke");
{console.log ("no coke, pepsi.")};
else
console.log ("pepsi only.")};
If anyone has any ideas, I'd be very grateful!

Disclaimer: I don't work for Coca Cola.
You need to save the return value of prompt if you want to use it later. Also, you have some syntax errors that should be corrected:
var answer = prompt('what do you want?');
if (answer === 'coke') {
console.log('you said coke!');
} else {
console.log('why didn\'t you say coke!?');
}
You could also use a switch as you get more cases:
var answer = prompt('what do you want?');
switch (answer) {
case 'coke':
console.log('you said coke!');
break;
default:
console.log('why didn\'t you say coke!?');
break;
}
Or an object, as most people prefer this to switch:
var answer = prompt('what do you want?');
var responses = {
coke: 'you said coke!',
defaultResponse: 'why didn\'t you say coke!?'
};
console.log(responses[answer] || responses.defaultResponse);

The if does not need a semicolon at the end. Instead do:
if ("coke") {
console.log ("no coke, pepsi.");
} else {
console.log ("pepsi only.");
}

Remove the trailing semicolons:
prompt("what do you want?");
if ("coke") {
console.log ("no coke, pepsi.");
} else {
console.log ("pepsi only.");
}

You have a semi-colon after the close brace. Try:
var ans = prompt("what do you want?");
if (ans == "coke") {
console.log ("no coke, pepsi.");
} else {
console.log ("pepsi only.");
}

var name = prompt("what do you want?");
if (name == "coke")
{
console.log ("no coke, pepsi.")
}
else
{
console.log ("pepsi only.")
}
Like above

Actually DO NOT do
if (ans == "whatever") {
console.log ("whatever");
} else {
console.log ("whatever.");
}
DO
if (ans == "whatever") {
confirm ("whatever");
} else {
confirm ("whatever.");
}

A variable needs to be identified. Also the bracketing and the semi colons between the "if" "else" statements are problematic. I am not sure about the console log, but if you want a popup alert try this:
var brand = prompt ('what do you want?');
if (brand="coke") {
alert ("no coke, pepsi.")
}else {
alert ("pepsi only.")
};
DICLAIMER: I am novice at best, jut happened to debug a similar issue.
Hope it helps.

Related

How to turn this Password validation right?

var password=123;
var input;
var opp=0;
for(var t=0;t<=2;t++){
if(password!=input && t<=2){
input=prompt("enter your password");
}
else{
opp++;
}
}
if(opp!=0){
alert("success");
}
else if(opp<1){
alert("fail");
}
im expect it to be a password validation which can only try three times.
but it will failed even with typing correct password in the third try.
Let's begin saying this should just be a didactic excercise.
I suggest you to drop the for loop strategy and embed the logic inside a while loop that will keep running as long as the attempt counter variable will be <=3.
Until the typed password still doesn't match the expected one, it will keep asking for a new password after saying fail for a total amount of 3 attemps max.
If the typed password matched, it just alerts the user saying success and exiting the loop.
Of course as just said by other users, this approach is very wrong in terms of security starting from the fact that the expected password is stored in plain text.
As a side note, the expected password defined as a literal should be a string literal and not a number.
let password = '123';
let attempt = 0;
let input;
let wasSuccess = false;
while(++attempt<=3){
input = prompt("enter your password");
if(input == password){
wasSuccess = true;
alert('success');
break;
}else{
alert('fail');
}
}
if(wasSuccess){
//perform any logic expected to run after successfully logged in
}
I am not sure what it is you are trying to do, this is totally unsafe.
To easily crack your password challenge, click 'view source' on the browser, and lookup the password.
Please use better authentication, preferably on the server, not in javascript.
Of course you can use Javascript, but not for actual password checking.
Since OP is just trying and will never use this in a production environment, here is a working piece of script:
var password= "123";
var input;
var tries=1;
var maxTries = 5;
var passed = false;
while ( (!passed) && (tries <= maxTries) ){
input=prompt("enter your password (attempt nr "+tries+")");
if (input === password){
passed = true; // Yeah!
} else {
tries = tries + 1;
}
}
if (passed){
alert("success");
} else {
alert("fail");
}

Javascript If/Else Issue

I might have it coded a bit wrong for the part I'm asking about but I'll give the solutions that work and the one that doesn't.
First example works:
function SignUpClick(){
if (document.UserSignUp.UserEmail.value == document.UserSignUp.ConfirmEmail.value);
else {alert ("Your email does not match - Please re-enter"); return;}
if (document.UserSignUp.UserPassword.value == document.UserSignUp.ConfirmPassword.value);
else {alert ("Your password does not match - Please re-enter"); return;}}
This second example also works:
function SignUpClick(){
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value)
{alert ("Your email does not match - Please re-enter"); return false;}
else return true;}
But this last one doesn't work:
function SignUpClick(){
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value)
{alert ("Your email does not match - Please re-enter"); return false;}
else return true;
if (document.UserSignUp.UserPassword.value != document.UserSignUp.ConfirmPassword.value)
{alert ("Your password does not match - Please re-enter"); return false;}
else return true;}
The interesting part about the last example is that the first confirm works but when I add and test out the second confirm, then it doesn't work and I'm not entirely sure why. As a side note, I tested out the second confirm on its own without the first and it worked fine. Has something to do with when a second one or more is added.
Any thoughts or suggestions of what I might be missing?
This is because you are returning in either of the if else case(1st) so the second if else wont be excuted.. :)
function SignUpClick(){
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value)
{alert ("Your email does not match - Please re-enter"); return false;}
else return true;
//the execution doesnt reach this part of the code given below
if (document.UserSignUp.UserPassword.value != document.UserSignUp.ConfirmPassword.value)
{alert ("Your password does not match - Please re-enter"); return false;}
else return true;}
In your last example, it will not reach the second if condition since you are returning true in the else condition of first if
function SignUpClick()
{
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value )
{
alert ("Your email does not match - Please re-enter"); return false;
}
else
return true; // this line will ensure that second if will not be reached
if (document.UserSignUp.UserPassword.value != document.UserSignUp.ConfirmPassword.value)
{
alert ("Your password does not match - Please re-enter"); return false;
}
else
return true;
}
instead try this
function SignUpClick()
{
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value )
{
alert ("Your email does not match - Please re-enter");
return false;
}
else if (document.UserSignUp.UserPassword.value != document.UserSignUp.ConfirmPassword.value)
{
alert ("Your password does not match - Please re-enter");
return false;
}
return true;
}
That's because when you do a return, it ends the function right there, and does not continue to the final if/else statement
You use return in first if else which break the running code,
Try this -
function SignUpClick(){
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value)
{
alert ("Your email does not match - Please re-enter");
return false;
}
else if (document.UserSignUp.UserPassword.value != document.UserSignUp.ConfirmPassword.value)
{
alert ("Your password does not match - Please re-enter"); return false;
}
else return true;
}
You just returned true or false on first if/else check. So when function runs it will return data anyway and never go to password check. Following will work:
function SignUpClick(){
if (document.UserSignUp.UserEmail.value
!= document.UserSignUp.ConfirmEmail.value) {
alert ("Your email does not match - Please re-enter"); return false;
}
if (document.UserSignUp.UserPassword.value
!= document.UserSignUp.ConfirmPassword.value) {
alert ("Your password does not match - Please re-enter"); return false;
}
return true;
}
I went with AkshayJ answer because his made more sense. Essentially they said since I had a return in both the first If and first Else, that is why it didn't go to second If and Else. Basically you can have only one return per If & Else if you're gonna have multiple If & Else statements. I can confirm that because I had tried what others said such as taking out the False and True, I had also tried making it look like else {return true;} and else {return;}. So it had nothing to do with whether it had True or False and whether it had { }.
Though the ones saying that its just because of one return in any of the first If and Else or because any If and Else that has a return in the else statement... that's just wrong and a assumption. Its a assumption because of my first example proves that wrong by it showing a return in its Else and the 2nd If & Else worked.
Also when I tested out what AkshayJ said by changing the code to else {} or just simply taking out the Else statement, both ways let the second confirm work.
Plus to continue with two paragraphs/sentences above, a return can work in the If statement as well to let it go on to the second If, so it doesn't just work only in the Else:
function SignUpClick(){
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value)
{alert ("Your email does not match - Please re-enter"); return false;}
if (document.UserSignUp.UserPassword.value != document.UserSignUp.ConfirmPassword.value)
{alert ("Your password does not match - Please re-enter"); return false;}}
The above code works. Thanks for the info AkshayJ and thank you for everyone else that helped as well.
As side note for those that gave their example with a Else If, because of the context of what is in the If & Else, its bad practice to try to change the dynamic flow of how conditions are currently set up. Wasn't asking to combine them when they were already separate. For reference, go to here: w3schools.com/js/js_if_else.asp
So, yes the combine examples worked but its not what I asked about. Nor does it solve the fact that with those combine examples, it doesn't fix the problem if I were to add another If & Else statement. Since AkshayJ explained it, the answer goes to them, thanks again.

Is this bad if/else programming practice?

I have this if/else loop here in a function, and I just want to know if this is an 'acceptable' way to do things. It does what I want it to do but I think there must be a more elegant solution.
var signUpCheckAll = function(username, password, passwordconf, email){
if (emptyChecker(username, password)) {
if (emptyChecker(passwordconf, email)) {
if (lengthChecker(password)) {
if (passwordCheck(password, passwordconf)) {
return true;
}
else{
console.log("Passwords don't match!");
}
}
else{
console.log("Password isn't long enough!");
}
}
else{
console.log("Some fields are empty!");
}
}
}
Thanks
I personally (and possibly many others too) consider this much more readable:
if (!emptyChecker(username, password)) {
console.log("Some fields are empty!");
}
else if (!emptyChecker(passwordconf, email)) {
//Where’s the message?
}
else if (!lengthChecker(password)) {
console.log("Password isn't long enough!");
}
else if (!passwordCheck(password, passwordconf)) {
console.log("Passwords don't match!");
}
else {
return true;
}
I would also recommend renaming your functions. It is not clear what function name passwordCheck does. A function name should always include a verb representing the action or return of the function. passwordsMatch is way better. (You can then read the line as "else if (not) passwords (don’t) match".)

If, Or, while Not.... Javascript help needed

Hi folks I was curious if someone could help me out. I don't usually post on here but I have exhausted all my efforts and can't figure this out. I have this code here
function insertVideo(link)
{
if (link)
{
if(link.substring(0,29)!="http://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
else{
link = link.replace(/watch\?/,"").replace(/\=/,"/");
}
var editpane = document.frmPost.addesc;
var linkcode = "[EMBED]" + link + "[/EMBED]";
editpane.focus();
/*if (document.selection)
{
document.selection.createRange().text = linkcode;
}
else*/
if (editpane.selectionStart || editpane.selectionStart == '0')
{
var selstart = editpane.selectionStart;
var selend = editpane.selectionEnd;
editpane.value = editpane.value.substring(0, selstart) + linkcode + editpane.value.substring(selend);
editpane.selectionStart = selstart + linkcode.length;
editpane.selectionEnd = editpane.selectionStart;
}
else
{
editpane.value = editpane.value + linkcode;
}
editpane.focus();
}
}
The problem I am having is when the user trys top post a youtube video with https in the address.
I understand that if I change
{
if(link.substring(0,29)!="http://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
to
{
if(link.substring(0,30)!="https://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
It works. But then when the user enters the http address without the https it no longer works. I figured I could combine the statement with an OR, but this doesnt work either, I had
if(link.substring(0,29)!="http://www.youtube.com/watch?" || link.substring(0,30)!="https://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
else{
link = link.replace(/watch\?/,"").replace(/\=/,"/");
}
So basically I need it to work in both situations (https and http) not just one or the other.
I am stumped, Im no pro with javascript so I sure its a minor error but I have spent far too much time trying to figure this out on my own. Please help if you can. Thanks!
It's as simple as changing the OR (||) to an boolean AND (&&).
if (link.substring(0,29) !== "http://www.youtube.com/watch?" && link.substring(0,30) !== "https://www.youtube.com/watch?") {
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
// the else is unnecessary
// else {
link = link.replace(/watch\?/,"").replace(/\=/,"/");
// }
This works as in your original code, if your URL is http://, it will fail the https:// check (or vice versa), making the conditional true, therefore running your failure code. Changing it to && fixes it as the URL is now required to fail both tests to be invalid.
Just a little note: unless you're doing it deliberately (or in other special circumstances), you should use the === and !== forms of equality testing (instead of == and !=), as these fail automatically if they are of different types instead of converting the types implicitly.

Javascript switch statement with wildcard?

If my javascript ajaxes away to my server and returns an ID of 49 in the plain text format of [49] is there a way in which i an do something like this... (i have tested and doesnt work)
switch(data)
{
case '[*]':
(..etc.)
break;
}
Where the wildcard is the * and i want to make sure it is enclosed within two square parenthesis?
Because i need to check that there wasnt another word returned like error and i am reserving the default for unexpected errors, any ideas? :) Thanks!
You can do a switch on true explicitely, which will use evaluation on each case statement.
switch (true) {
case ((/^\[\d+\]$/).test(data)):
//matches data;
break;
case (data == "something else"):
//...
break;
default:
//...
}
However, if you have less than say 4-5 cases, it would be better to use if/else if/else if/else blocks.
if ((/^\[\d+\]$/).test(data)) {
//matches data;
} else if (data == "something else") {
//...
} else {
//...
}
I usually do some error trapping in my response methods for service/rest calls so that I almost always return a proper json with an error property if there is an error.
try {
if (response.responseText.indexOf("<html") >= 0) {
throw response.responseText;
}
var data = JSON.parse(response.responseText);
if (data.error)
throw data.error;
//handle response data object.
if ((/^\[\d+\]$/).test(data)) {
//matches data;
} else if (data == "something else") {
//...
} else {
//...
}
} catch(err) {
if (err && err.message) {
//use err.message
} else if (err && err.toString().indexOf("<html") >= 0) {
//handle error text
}
}
You could create a list of patterns and associated callbacks and do a simple loop and check for matches. For example:
var patterns = [];
function myCallback(){ document.write('myCallback!'); }
function myOtherCallback(){ document.write('myOtherCallback!'); }
function myLastCallback(){ document.write('You will never see me!'); }
patterns.push({'pattern':new RegExp(/\[.+\]/),'callback': myCallback});
patterns.push({'pattern':new RegExp(/.+/),'callback':myOtherCallback});
patterns.push({'pattern':new RegExp(/A-Z{3}/),'callback':myLastCallback});
var f = "[49]";
for(var i=0;i<patterns.length;i++){
if(patterns[i].pattern.test(f)){
patterns[i].callback();
}
}
Which outputs the following:
myCallback!myOtherCallback!
You could try to use if else and regex for matching wildcard patterns.
Assuming data = "[49]"; or any digits inside brackets.
if(/\[\d+\]/.test(data)){
//do something
}else{
//default
}
Short answer: No, switch/case can't handle wildcard.
You should probably do some preprocessing/sanity checking before entering the switch, or simply discard it completely since it's more appropriate for specific case scenarios rather than processing streamlined data. Regexp will serve you better here.

Categories

Resources