Is this bad if/else programming practice? - javascript

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".)

Related

Javascript - More than one condition

I just started to learn JS and I want to ask about a task that I could not complete.
var balance = 325.00;
var checkBalance = true;
var isActive = false;
//The first question
if (checkBalance = true) {
// the second question
if(isActive = false) {
console.log("Your account is no longer active.");
} else if(isActive = true) {
if(balance > 0) {
console.log("Your balance is " + balance.tofix(2) +"$.");
} else if(balance = 0) {
console.log("Your Accunt is empty");
} else {
console.log("Your balance is negetive, please contant bank");
}
}
else {
console.log("Thank you. Have a nice day");
The goal is to write an ATM and in order to do that I want to write more than one condition in the same time (as you can see in the code).
Why this code doesn't work?
Is it possible to write if statement inside another if statement?
Is there a better solution?
In javascript you should use === for condition equal
your code:
if (checkBalance = true) {
correct is:
if (checkBalance === true) {
same for
if(isActive = false) {
correct is:
if(isActive === false) {
= is assignment, == is used to check, change = to ==, === is used to check equality and type.
if (checkBalance = true) {
You are on the right track, it is indeed possible to write an if statement inside another one. But, you're missing a bracket and the way you check equality should be done differently. I edited your code so I can explain:
var balance = 325.00;
var checkBalance = true;
var isActive = false;
//The first question
if (checkBalance) {
// the second question
if(isActive = false) {
console.log("Your account is no longer active.");
} else if(isActive) {
if(balance > 0) {
console.log("Your balance is " + balance.tofix(2) +"$.");
} else if(balance === 0) {
console.log("Your Accunt is empty");
} else {
console.log("Your balance is negetive, please contant bank");
}
}
else {
console.log("Thank you. Have a nice day");
}
I mainly changed 2 things in your code. The first is changing
if (checkBalance = true)
Into this:
if (checkBalance)
Edit 1: Shorter if statements
You can omit the = true part because checkBalance is already a boolean value. This means that it is already true or false, which are values an if statement accepts. This brings me onto my second edit, which is the most important one.
Edit 2: Checking for equality
In your code, you use = true inside your if statements. Using only one = sign unfortunately is not checking for equality, but instead is your to assign values. You can only use one = when your assigning values like var a = 1;. Instead, you should use three = sings like ===. This actually checks two things. First, it checks if the type of values are the same. Then, it checks if the values are equal. You can also use two = sings like ==, this will check equality more loosely because it doesn't check if the types are the same. As noted in other answers, === is preferable here.
I hope this answers your question. If not, please comment below.
First one:
= : is assign
=== :is compare
One more thing wrong is :
balance.tofix(2)
It should be:
balance.toFixed(2)
and I just edited your code like this:
var balance = 325.00;
var checkBalance = true;
var isActive = false;
//The first question
if(!checkBalance) console.log("Thank you. Have a nice day");
else {
if(!isActive) console.log("Your account is no longer active.");
else{
if(balance > 0) {
console.log("Your balance is " + balance.toFixed(2) +"$.");
} else if(balance = 0) {
console.log("Your Accunt is empty");
} else {
console.log("Your balance is negetive, please contant bank");
}
}
}
You've been given good answers on the syntax errors. Regarding 'is there a better way', the need for equality checking of true and false using === is not necessary, because the true/false is already implied in the if condition. You can use it as the variable by itself. Also, since it is a boolean that can only be true or false, using if and then else is totally fine to do. No need to do if and else if.
Using a helper function to handle your complex case makes your code much more readable.
var balance = 325.00;
var checkBalance = true;
var isActive = false;
//The first question
if (checkBalance) {
// the second question
if(isActive) {
handleIsActive(balance);
} else {
console.log("Your account is no longer active.");
}
} else {
console.log("Thank you. Have a nice day");
}
function handleIsActive(balance) {
if(balance > 0) {
console.log("Your balance is " + balance.tofix(2) +"$.");
} else if(balance === 0) {
console.log("Your Accunt is empty");
} else {
console.log("Your balance is negetive, please contant bank");
}
return;
}

Javascript IF blocks get skipped

I'm using this code to validate a form:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
if (isEmpty(name)) {
alert("3");
return false;
}
if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
if (isEmpty(city)) {
alert("6");
return false;
}
if (isEmpty(comments)) {
alert("7");
return false;
}
When hitting the "Submit" button, if the first two conditions do work(The ones that check if the email var is empty or not in email address format) - meaning that if I leave the email input empty or not in an email address format I get the alert (1 or 2).
The problem is that the rest of the validations get skipped and it doesn't matter if I leave another input empty or not in format.
Also, if I take the first IF block:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
And move it to the end of the validation block, everything works just fine.
I'm guessing I have a wrong syntax somewhere but I spent 2 hours looking and just couldn't find it.
P.S.
here are the two validation functions I'm using:
function isEmpty(field) {
if ((field == null || field == "")) {
return true;
}
return false;
}
function isEmail(field) {
var atpos = field.indexOf("#");
var dotpos = field.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
return false;
}
}
You use x.length in the isEmail function, but x is not defined.
the return statement exits the function to get all the validations run
keep all the validations in if else if blocks and keep on using return false every time.
or
set a variable to false whenever condition fails and then return the value. as j00lz said.
The
return false;
ends the function and stops the rest of the code being executed.
Instead set a variable:
result="false";
and at the end of the function add
return result;
What happens if you change it to this:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
else if (isEmpty(name)) {
alert("3");
return false;
}
else if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
else if (isEmpty(city)) {
alert("6");
return false;
}
else if (isEmpty(comments)) {
alert("7");
return false;
}
I'm just curious as to what happens if you make the whole thing one big if statement rather than breaking it up into parts, considering it's not going to change the validation process.
P.S.
I'm not sure if you realize or not, but with the way you have it set up, once one of the first if statements comes back false, returning false with in that if statement will end the whole method you're working in, meaning it won't run any other parts of it. So if you're shooting for displaying an alert for each and every empty input, etc, it won't happen this way.

Returning true or false from javascript function

I'm doing a regex check on a string within a function:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/,
matches = regex.exec(listOfZipCodes);
if (regex.exec(listOfZipCodes) === null) {
console.log('validation failed');
return false;
} else {
console.log('validation passed');
return true;
}
}
The regex is correctly detecting a valid/invalid list of zip codes.
I'm calling the function with this:
console.log('zip code: ' + listOfZipCodes);
if (ValidateZipCodeString(listOfZipCodes)) {
$tr.find('label#lblCoverageEditError').text('There is invalid text in the list of zip codes. Only 5-digit zip codes allowed.').show();
} else {
console.log('validate function returned true');
}
The problem is that the above if/else goes to the else clause, when the console output within the validation function shows "validation failed". So I must not be calling that function right.
What's the correct way to do what I'm trying to do?
Your function could be greatly simplified to:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/;
if (regex.test(listOfZipCodes)) {
console.log('validation passed');
return true;
} else {
console.log('validation failed');
return false;
}
}
...or:
function ValidateZipCodeString(listOfZipCodes) {
var regex = /^([, ]*\d{5})+[, ]*$/;
return regex.test(listOfZipCodes);
}
...or even just:
function ValidateZipCodeString(listOfZipCodes) {
return /^([, ]*\d{5})+[, ]*$/.test(listOfZipCodes);
}
...but the real issue (as Teemu points out) is not in your function, but in the use of it. Your function answers the question, "Is this a valid zip code string?", but your use of it is saying, "Say this is invalid if my function says it is."
Actually your validation function doesn't return true when validation fails. You just check the value incorrectly, it should be:
if (!ValidateZipCodeString(listOfZipCodes)) {
$tr.find('label#lblCoverageEditError').text('There is invalid text in the list of zip codes. Only 5-digit zip codes allowed.').show();
} else {
console.log('validate function returned true');
}
Others correctly pointed out that you just had your tests in the wrong order. However, and more importantly, your regex is incorrect, as it will for example return true for "1234567890".
Here is a suggestion:
function ValidateZipCodeString(listOfZipCodes) {
return /^\d{5}(\s*,\s*\d{5})*$/.test(listOfZipCodes);
}

Prompt JavaScript If Else Unexpected Token else

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.

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