If condition for value assignment check in JavaScript - javascript

I have a condition as below to check the variables Qmart and linearstatus.
Though they have the values as required, my if statement is always going to the else condition. Is there some mistake I'm making for checking these values?
var Qmart = "A2";
var linearstatus = "linear"
if (Qmart === ("E2" || "A2" || "B2" || "D2") && linearstatus == "linear") {
} else {
alert("it is an else condition");
}

Change the if condition to the following
if ((Qmart === "E2" || Qmart === "A2" || Qmart === "B2" || Qmart === "D2") && (linearstatus == "linear")) {
} else {
alert("it is an else condition");
}
Hope it helps

If you want to check for multiple values you cannot use Qmart === ("E2" || "A2" || "B2" || "D2"), you need to check each condition separatelly:
if ((Qmart === "E2" || Qmart === "A2" || Qmart === "B2" || Qmart === "D2") && linearstatus == "linear") {
} else {
alert("it is an else condition");
}
You might ask why your code did not throw any runtime error. The issue is that code
"E2" || "A2" || "B2" || "D2"
is a valid JavaScript code, and it returns first truthy value. This feature is called short-circuit evaluation and is used often in JavaScript. In your case above statement returns first truthy value, which is always "E2". This means that, your code is identical to
if (Qmart === "E2" && linearstatus == "linear")
and when Qmart is A2, then the condition evaluates to false and else statement is executed.

You could do something like this.
var QMart = "E2",
linearstatus = "linear";
var conditions = ["E2", "A2", "B2", "D2"];
if (conditions.indexOf(QMart) !== -1 && (linearstatus == "linear")) {
console.log("In truthy condition");
} else {
console.log("it is an else condition");
}

Related

Firebase Data validation not matching with data

I have a click button which is validating data from firebase firestore, but it is not giving the correct output as in the checks applied are getting failed.
createAptBtn.onclick = () => {
if (category.value === "" || email.value === "" || day.value === "" || time.value === "") {
promptContent.innerText = "All fields are required."
}
else if (category.value === "New") {
db.collection("recordsDb").onSnapshot((querySnapshot) => {
querySnapshot.forEach((doc) => {
//Condtion 1
if (email.value === doc.data().email && day.value === doc.data().day && time.value === doc.data().time) {
promptContent.innerText = "Email already exists."
}
//Condition 2
if (email.value !== doc.data().email && day.value === doc.data().day && time.value === doc.data().aptTimeSlot) {
promptContent.innerText = "Slot already filled."
}
//Condition 3
if (email.value === doc.data().email || mobile.value === doc.data().mobile) {
promptContent.innerText = "User already exits."
}
// Condition 4
if(email.value !== doc.data().email && day.value !== doc.data().day && time.value !== doc.data().time) {
promptContent.innerText = "Account created."
}
})
})
}
}
Also even when one of the condition is true it still outputs the else statement which should work when all ifs are getting failed.
However, condition 4 is an else statement but since its not working I'm using it as an if statement by adding some checks in it which though fails.
How do I fix this?

How can I push data into an array?

I have pushed some data into an array:
if(target === 'create'){
if(name === 'form[username]' || name === 'form[name]' || name === 'form[slug]' || name === 'form[plainPassword]'){
errors.push(name);
}
} else {
if(name === 'form[username]' || name === 'form[name]' || name === 'form[slug]' ){
errors.push(name);
}
}
It actually works fine. But it seems to me that it is really too much repeating code, but I still cannot find a way to reduce the code, or make a simpler better solution.
I would do it in two methods
function CheckErrors(target,name){
switch(target){
case 'create':
SaveError(name,true);
break;
default:
SaveError(name);
break;
}
}
function SaveError(name,checkPassword){
if(name === 'form[username]' || name === 'form[name]' || name === 'form[slug]' ||(checkPassword && name === 'form[plainPassword]')){
errors.push(name);
}
}
You could use arrays to simplify your if statement:
if((target === 'create' && name === 'form[plainPassword]') || ['form[username]', 'form[name]', 'form[slug]'].includes(name)){
errors.push(name);
}
If I rigth understand you, you want to simplify your statements. From my perspective it could be like this:
if(name === 'form[username]' || name === 'form[name]' || name === 'form[slug]'
|| (name === 'form[plainPassword]' && target === 'create')){
errors.push(name);
}
Since:
name === 'form[username]' || name === 'form[name]' || name === 'form[slug]'
is repeated two times, it doesn't matter if target === 'create' is true or false for this statements.
In fact just add (name === 'form[plainPassword]' && target === 'create') to if statement and that's all

Javascript Syntax - if statement

i have the following object:
var quarters = {
q1:false,
q2:false,
q3:false,
q4:{name: "i'm q4"}
}
My question is why the following IF is returning true?
if (quarters.q1 == quarters.q2 == quarters.q3 == quarters.q4 == false)
How can i ask if all quarters are false?
The reason I'm not using !quarters.q1 && !quarters.q2 && !quarters.q3 && !quarters.q4 is because sometimes, some of the properties are not defined at all.
why the following IF is returning true?
Assuming toppingOrder is quarters, lets fill it in and see what we have
if (toppingOrder.q1 == toppingOrder.q2 == toppingOrder.q3 == toppingOrder.q4 == false)
// same as
if (false == false == false == {name: "i'm q4"} == false)
// same as
if ((((false == false) == false) == {name: "i'm q4"}) == false)
// same as
if (((true == false) == {name: "i'm q4"}) == false)
// same as
if ((false == {name: "i'm q4"}) == false)
// same as
if (false == false)
// same as
if (true)
How can i ask if all quarters are false?
You either have to loop, use a logical AND && or some Array method like .every
// logical AND `&&`
if (
false === toppingOrder.q1
&& false === toppingOrder.q2
&& false === toppingOrder.q3
&& false === toppingOrder.q4
) // ...
// Array `.every`
if (
[toppingOrder.q1, toppingOrder.q2, toppingOrder.q3, toppingOrder.q4].every(
function (e) {return e === false;}
)
) // ...
It is actually much easier to test all true, so consider if you can phrase your if like that instead, e.g. using logical NOT !
if (!toppingOrder.q1 && !toppingOrder.q2 && !toppingOrder.q3 && !toppingOrder.q4) // ...
// or
if (
[!toppingOrder.q1, !toppingOrder.q2, !toppingOrder.q3, !toppingOrder.q4].every(Boolean)
) // ...
quarters.q1 == quarters.q2 == quarters.q3 == quarters.q4 == false
true == quarters.q3 == quarters.q4 == false
false == quarters.q4 == false
true == false
What you are essentially doing is this
everything will execute from left to right, unless you set the order (with ( ))
you could go this way about it
function get_bool(quarters){
for(k in quarters)
{
if(quarters[k] != false)
{
return true;
}
}
return false;
}

OR and AND conditions not returning as expected - What is best way to implement it?

I have an If statement that using || with an && operator e.g if((a || b) && c) however it is only works with the first condition i.e a but not with second i.e b even though running the debugger I can see that the condition is met and it goes to the correct line of code. Is there a better way to get this to work on both conditions?
code I have now:
function _getCatFormGUID(catName) {
debugger;
var dept = Browser.getValue(getElement("126D81CA203C21CF014C8A3550227892FE4B4A6A"));
if((catName == '1' && dept == "Entwicklung") || (catName == '7' && dept == "Entwicklung")){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
if((catName == '1' && dept != "Entwicklung") || (catName == '7' && dept != "Entwicklung")) {
return "8EDD0768A7CDF8FD8AE90DB473F41EF0B33FA14F";
}
return "";}
I have tried the following also:
if((catName == '1' || catName == '7') && dept == "Entwicklung"){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
and
if(catName == '1' && dept == "Entwicklung"){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
if(catName == '7' && dept == "Entwicklung"){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
It only returns for catName =='1'.
If I understood your problem correctly, I will write your first bit of code as bellow
function _getCatFormGUID(catName) {
var dept = Browser.getValue(getElement("126D81CA203C21CF014C8A3550227892FE4B4A6A"));
if (catName == '1' || catName == '7') {
if(dept == 'Entwicklung'){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
else{
return "8EDD0768A7CDF8FD8AE90DB473F41EF0B33FA14F";
}
}
else{
return "";
}
}
The problem is that you have to understand how those 2 logical operators do the comparison: because your first condition catName == '1' is true, it will never go to second conditions from the first parenthesis nor in the second paranthesis.Given your example, you might rewrite your logical condition from:
if((catName == '1' && dept == "Entwicklung") || (catName == '7' && dept == "Entwicklung")){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
to
if(dept == "Entwicklung" && catName == '1' || catName == '7'){ return something; }
}

JavaScript: Parsing a string Boolean value? [duplicate]

This question already has answers here:
How can I convert a string to boolean in JavaScript?
(102 answers)
Closed 4 years ago.
JavaScript has parseInt() and parseFloat(), but there's no parseBool or parseBoolean method in the global scope, as far as I'm aware.
I need a method that takes strings with values like "true" or "false" and returns a JavaScript Boolean.
Here's my implementation:
function parseBool(value) {
return (typeof value === "undefined") ?
false :
// trim using jQuery.trim()'s source
value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
Is this a good function? Please give me your feedback.
Thanks!
I would be inclined to do a one liner with a ternary if.
var bool_value = value == "true" ? true : false
Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:
var bool_value = value == 'true';
This works because value == 'true' is evaluated based on whether the value variable is a string of 'true'. If it is, that whole expression becomes true and if not, it becomes false, then that result gets assigned to bool_value after evaluation.
You can use JSON.parse for that:
JSON.parse("true"); //returns boolean true
It depends how you wish the function to work.
If all you wish to do is test for the word 'true' inside the string, and define any string (or nonstring) that doesn't have it as false, the easiest way is probably this:
function parseBoolean(str) {
return /true/i.test(str);
}
If you wish to assure that the entire string is the word true you could do this:
function parseBoolean(str) {
return /^true$/i.test(str);
}
You can try the following:
function parseBool(val)
{
if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1)
return true;
else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0)
return false;
return null;
}
If it's a valid value, it returns the equivalent bool value otherwise it returns null.
You can use JSON.parse or jQuery.parseJSON and see if it returns true using something like this:
function test (input) {
try {
return !!$.parseJSON(input.toLowerCase());
} catch (e) { }
}
last but not least, a simple and efficient way to do it with a default value :
ES5
function parseBool(value, defaultValue) {
return (value == 'true' || value == 'false' || value === true || value === false) && JSON.parse(value) || defaultValue;
}
ES6 , a shorter one liner
const parseBool = (value, defaultValue) => ['true', 'false', true, false].includes(value) && JSON.parse(value) || defaultValue
JSON.parse is efficient to parse booleans
Personally I think it's not good, that your function "hides" invalid values as false and - depending on your use cases - doesn't return true for "1".
Another problem could be that it barfs on anything that's not a string.
I would use something like this:
function parseBool(value) {
if (typeof value === "string") {
value = value.replace(/^\s+|\s+$/g, "").toLowerCase();
if (value === "true" || value === "false")
return value === "true";
}
return; // returns undefined
}
And depending on the use cases extend it to distinguish between "0" and "1".
(Maybe there is a way to compare only once against "true", but I couldn't think of something right now.)
Why not keep it simple?
var parseBool = function(str) {
if (typeof str === 'string' && str.toLowerCase() == 'true')
return true;
return (parseInt(str) > 0);
}
You can add this code:
function parseBool(str) {
if (str.length == null) {
return str == 1 ? true : false;
} else {
return str == "true" ? true : false;
}
}
Works like this:
parseBool(1) //true
parseBool(0) //false
parseBool("true") //true
parseBool("false") //false
Wood-eye be careful.
After looking at all this code, I feel obligated to post:
Let's start with the shortest, but very strict way:
var str = "true";
var mybool = JSON.parse(str);
And end with a proper, more tolerant way:
var parseBool = function(str)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if(str == null)
return false;
if (typeof str === 'boolean')
{
if(str === true)
return true;
return false;
}
if(typeof str === 'string')
{
if(str == "")
return false;
str = str.replace(/^\s+|\s+$/g, '');
if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
return true;
str = str.replace(/,/g, '.');
str = str.replace(/^\s*\-\s*/g, '-');
}
// var isNum = string.match(/^[0-9]+$/) != null;
// var isNum = /^\d+$/.test(str);
if(!isNaN(str))
return (parseFloat(str) != 0);
return false;
}
Testing:
var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", " true ", " TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");
var array_2 = new Array(null, "", false, "false", " false ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");
for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}
for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}
I like the solution provided by RoToRa (try to parse given value, if it has any boolean meaning, otherwise - don't). Nevertheless I'd like to provide small modification, to have it working more or less like Boolean.TryParse in C#, which supports out params. In JavaScript it can be implemented in the following manner:
var BoolHelpers = {
tryParse: function (value) {
if (typeof value == 'boolean' || value instanceof Boolean)
return value;
if (typeof value == 'string' || value instanceof String) {
value = value.trim().toLowerCase();
if (value === 'true' || value === 'false')
return value === 'true';
}
return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
}
}
The usage:
var result = BoolHelpers.tryParse("false");
if (result.error) alert(result.msg);
stringjs has a toBoolean() method:
http://stringjs.com/#methods/toboolean-tobool
S('true').toBoolean() //true
S('false').toBoolean() //false
S('hello').toBoolean() //false
S(true).toBoolean() //true
S('on').toBoolean() //true
S('yes').toBoolean() //true
S('TRUE').toBoolean() //true
S('TrUe').toBoolean() //true
S('YES').toBoolean() //true
S('ON').toBoolean() //true
S('').toBoolean() //false
S(undefined).toBoolean() //false
S('undefined').toBoolean() //false
S(null).toBoolean() //false
S(false).toBoolean() //false
S({}).toBoolean() //false
S(1).toBoolean() //true
S(-1).toBoolean() //false
S(0).toBoolean() //false
I shamelessly converted Apache Common's toBoolean to JavaScript:
JSFiddle: https://jsfiddle.net/m2efvxLm/1/
Code:
function toBoolean(str) {
if (str == "true") {
return true;
}
if (!str) {
return false;
}
switch (str.length) {
case 1: {
var ch0 = str.charAt(0);
if (ch0 == 'y' || ch0 == 'Y' ||
ch0 == 't' || ch0 == 'T' ||
ch0 == '1') {
return true;
}
if (ch0 == 'n' || ch0 == 'N' ||
ch0 == 'f' || ch0 == 'F' ||
ch0 == '0') {
return false;
}
break;
}
case 2: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
if ((ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'n' || ch1 == 'N') ) {
return true;
}
if ((ch0 == 'n' || ch0 == 'N') &&
(ch1 == 'o' || ch1 == 'O') ) {
return false;
}
break;
}
case 3: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
if ((ch0 == 'y' || ch0 == 'Y') &&
(ch1 == 'e' || ch1 == 'E') &&
(ch2 == 's' || ch2 == 'S') ) {
return true;
}
if ((ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'f' || ch1 == 'F') &&
(ch2 == 'f' || ch2 == 'F') ) {
return false;
}
break;
}
case 4: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
var ch3 = str.charAt(3);
if ((ch0 == 't' || ch0 == 'T') &&
(ch1 == 'r' || ch1 == 'R') &&
(ch2 == 'u' || ch2 == 'U') &&
(ch3 == 'e' || ch3 == 'E') ) {
return true;
}
break;
}
case 5: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
var ch3 = str.charAt(3);
var ch4 = str.charAt(4);
if ((ch0 == 'f' || ch0 == 'F') &&
(ch1 == 'a' || ch1 == 'A') &&
(ch2 == 'l' || ch2 == 'L') &&
(ch3 == 's' || ch3 == 'S') &&
(ch4 == 'e' || ch4 == 'E') ) {
return false;
}
break;
}
default:
break;
}
return false;
}
console.log(toBoolean("yEs")); // true
console.log(toBoolean("yES")); // true
console.log(toBoolean("no")); // false
console.log(toBoolean("NO")); // false
console.log(toBoolean("on")); // true
console.log(toBoolean("oFf")); // false
Inspect this element, and view the console output.
Enough to using eval javascript function to convert string to boolean
eval('true')
eval('false')

Categories