Javascript - More than one condition - javascript

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;
}

Related

Is there a better way to reduce multiple if statements?

I have a function that validates few different conditions. Here is the example of my function:
function checkData() {
var errorMsg = "",
fld1 = 0, //Number(document.getElementById('fld1').value),
fld2 = 5, //Number(document.getElementById('fld2').value),
fld3 = 1, //Number(document.getElementById('fld3').value),
fld4 = 0; //Number(document.getElementById('fld4').value);
if (!fld1) {
errorMsg += "Error 1\n\n";
}
if (fld1 === fld4) {
errorMsg += "Error 2\n\n";
}
if (fld2 > fld4) {
errorMsg += "Error 3\n\n";
}
if (fld3 > 3) {
errorMsg += "Error 4\n\n";
}
if (errorMsg !== "") {
var check = confirm(errorMsg + "\n Do you want to submit the form?");
if (check) {
return true;
} else {
return false;
}
}
return true;
}
<button onclick="checkData();">Click Here</button>
In the example above I hard coded some values for testing purpose. However, I'm wondering if I can refactor this code and find the better way of achieving the same result? Would ternary operators fit better? Or there is another way to get this to work? Thank you.
In this use-case I think the 'multiple-ifs' solution is quite clear so it is the one to use.
If you want to optimize a bit, I can only suggest
if(check){
return true;
}else{
return false;
}
to become
return !!check;
(the two exclamatives simply cast any object to a boolean vale :-))
The whole check variable is pointless. So return confirm is all that you need
function checkData() {
var errorMsg = "",
fld1 = 0, //Number(document.getElementById('fld1').value),
fld2 = 5,//Number(document.getElementById('fld2').value),
fld3 = 1,//Number(document.getElementById('fld3').value),
fld4 = 0;//Number(document.getElementById('fld4').value);
if(!fld1){
errorMsg += "Error 1\n\n";
}
if(fld1 === fld4){
errorMsg += "Error 2\n\n";
}
if(fld2 > fld4){
errorMsg += "Error 3\n\n";
}
if(fld3 > 3){
errorMsg += "Error 4\n\n";
}
return errorMsg !== "" ? confirm(errorMsg + "\n Do you want to submit the form?") : true
}
<button onclick="checkData();">Click Here</button>
You could refactor your if statements using the ternary operator. But chances are that it would make your code far harder to read. You could replace
if(check){
return true;
}else{
return false;
}
With just return check; as this is a boolean statement anyway.
Also, as far as readability goes it would be nice to label your field variables something more meaningful, as knowing that fld2 should always be greater than fld4 isn't immediately obvious from the name.
And if you don't care about highlighting the specific error codes then you could of course merge some of your checks together and just return false without the error codes specified, but I suspect you will want to keep that functionality.

JavaScript form validation with else if

I have been creating JavaScript validation for a form though run into difficulties. There are currently two parts to parts at (at the moment) for JavaSCript to check (email and sms). THe script is only running email and not checking sms at all when should be checking both together. If both are fine then return true. Any ideas?
function validateForm() {
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
var errordiv = document.getElementById('error');
var errorsms = document.getElementById('errorsms');
/*postOptOutSix.checked = false;
postOptOutForever.checked = false*/
// Conditions
if (document.getElementById("emailradios") ==null && document.getElementById("emailforever") ==null) {
if (document.getElementById("smsforever") ==null && document.getElementById("smsforever") ==null) {
return true;
}
else if (document.getElementById("checksms").checked ==false && document.getElementById("smsOptOutSix").checked ==false && document.getElementById("smsOptOutForever").checked ==false) {
errordiv.innerHTML += "<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
else if (document.getElementById("checkemail").checked ==false && document.getElementById("emailOptOutSix").checked ==false && document.getElementById("emailOptOutForever").checked ==false) {
errorsms.innerHTML += "<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
You'd need to separate the 2 conditions checks, and only then check if some failed or not before returning.
Something like this should do the trick:
function validateForm () {
var errors = [];
// Empty any previous errors
document.getElementById('error').innerHTML = "";
// Check for SMS
if (!document.getElementById("checksms").checked &&
!document.getElementById("smsOptOutSix").checked &&
!document.getElementById("smsOptOutForever").checked) {
// add the SMS error to the array
errors.push("<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'");
}
// Check for Email
if (!document.getElementById("checkemail").checked &&
!document.getElementById("emailOptOutSix").checked &&
!document.getElementById("emailOptOutForever").checked) {
// add the Email error to the array
errors.push("<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'");
}
// Display the error(s) if any
if (errors.length > 0) {
errors.forEach(function (err) {
document.getElementById('error').innerHTML += err;
});
return false;
}
return true;
}
Also, I noticed that id='errorp' is there twice. Rename one of them.
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
You are setting the same variable from different elements. Shouldn't it be like this?
var emailBoxChecked = document.getElementById("checkemail").checked
var smsBoxChecked = document.getElementById("checksms").checked
Use HTML required and pattern attributes along with inputElement.checkValidity() which returns true or false. You could look on keyup, for example, to make sure all inputs are valid and if so enable the submit button and if not disable it.

JavaScript IF statement not recognizing variable

I am having a problem with an if statement not recognizing a variables' value
The input is coming from a CSV file, saved to a variable and then passed into this function to check if it is true,
the checkusage console.logs are coming through with the value of "Y" but when ran it seems to keep skipping the checkusage if statement and executes the else statement.
VolumeChargeCalc = function(meterSize, checkusage){
console.log("Check usage value passed to function is = " + checkusage );
if(meterSize <= 20) {
console.log("METER SIZE HAS PASSED");
if(checkusage == "Y") {
console.log("Check usage has been found");
return [0.8042,0.8042,0.6879,0.6627];
} else {
console.log("no check usage found " + checkusage);
return [2.1442,0.8042,0.6879,0.6627];
}
} else if(meterSize == 999){
return [0.03035,0,0,0];
}
else {
return [0.8042, 0.8042, 0.6879, 0.6627];
}
}
I have tried a few different ways and the all have the same outcome, any ideas would be appreciated.
Thanks #mplungjan,
if (checkusage.trim() == "Y")
solved the problem, I guess the CSV was passing spaces through as well.
Not sure how to mark your comment as the answer sorry

true == false evaluates to true somehow?

I've been working to scrape some webpage that is using the OWASP CRSFGuard project for protection. The library seems to be causing one of my requests to get a 401 so I started digging through their code and noticed the following;
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if(current == target || current == 'localhost') {
result = true;
} else if(true == false) {
if(target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
From what I can tell, there must be instances where this code is executed; result = current.endsWith('.' + target);. Given true == false is inherently false, how would the code reach that statement? Is this some JS oddity (I know we're not using the strict === equality, but seriously...)?
Answer: It will never reach that code block.
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if (current == target || current == 'localhost') {
result = true;
} else if (true == false) {
if (target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
var trueFalse = document.getElementById('trueFalse');
trueFalse.innerHTML = isValidDomain('true', 'false') ? 'WTF!' : 'All is good in the JS World';
trueFalse.addEventListener('click', function(e) {
trueFalse.innerHTML = (true == false) ? 'WTF!' : 'All is good in the JS World Still';
});
<div id="trueFalse"></div>
I would say that Blazemonger is most likely correct.
That else if probably had some other condition at some point, and for whatever reason, they decided they didn't want that block of code to execute anymore, so they changed the condition to something that is always false.
It's also not entirely uncommon to see programmers use 1 === 0 as an indication for false. Why they would want to do this is anybody's guess.

How to get my loop to start from the beginning after error detected

I am trying to get my loop to restart when it comes across an user input error. I need it to restart at the very beginning and not just the last question.
So below when it says validImput = false this is where I am trying to get it to restart.
{
var validInput = true;
var start = confirm('Add item to shoping cart');
if (start == true) {
// ask first question
var orderProductCodeArr = parseInt(prompt('Enter input: '), 10);
if (isNaN(orderProductCodeArr)) {
alert("input is not a valid number");
validImput = false
} else if (orderProductCodeArr < 0 || orderProductCodeArr >= PRODUCT_LIST.length) {
alert("code does not match any item");
validInput = false;
}
// ask second question
else if(validInput == true) {
var item = PRODUCT_LIST[orderProductCodeArr];
alert("item is: " + item);
}
// get quantity input
var quanityArr = parseInt (prompt('Enter quality amount'),10);
if (isNaN(quanityArr)) {
alert("input is not a valid number");
validInput = false;
}
} else {
document.writeln('still to come')
}
}
The usual method of starting something over is some sort of loop construct, often using while like this:
while (true) {
// your loop code here
// you can use break; to break out of the while loop
// anywhere to stop repeating
// you can use continue; to jump to the next iteration immediately
}
Or, sometimes you use a loop condition like this:
var doAgain = true;
while (doAgain) {
// within the loop, you set doAgain to false when you are done
// and don't want to repeat the loop again
}
try
function test()
{
for(var s=0;s<5;s++)
{
try
{
//body of the for loop
}catch(e){s=0;}
}
}

Categories

Resources