JavaScript IF statement not recognizing variable - javascript

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

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

How to check if eval returns nothing in JS

If I want to check if an eval function returns nothing, how do I do it?
I tried to do something like:
if (eval("iwuoinuvwoienvuwope") == "") {
// Do something
alert("Oh NO!");
}
But when I do like that nothing happends.
Here is my full code:
function calc() {
var cal = prompt("Your math....", "1 + 1");
if (cal == null) {
alert("If you don't have a math problem you can gtfo!");
} else if (cal == false) {
alert("If you don't have a math problem you can gtfo!");
}
/* Here I Check if eval is empty */
/* Here it doesn't work */
else if (eval(cal) == "") {
alert("Could you be more specific");
}
/* */
else {
alert("The answer is " + eval(cal));
}
}
<button onclick="calc();">Calculator</button>
eval(code) returns "the completion value of evaluating the given code. If the completion value is empty, undefined is returned." MDN
In your case, a valid math expression returns a Number. Thus you would have to check for typeof result == "Number". If you want to exclude NaN, Infinity and the like, perform additional checks e.g. by isFinite(result).
If you are trying to build a calculator, you should either be expecting a response, an exception or null.
try {
if (r === undefined) {
} else {
// handle response
}
} catch (error) {
// invalid
}
Validating whether it's a Number, and if the mathematical formula is valid will help you identity possible error outputs.

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