Use if-loop to calculate price depending on the input in js - javascript

I'm pretty new to Javascript and React, so please bear with me.
I have a component in my app, that is taking a timespan from the user, but now I want to calculate the price the user would have to pay, depending on their input. I figured that it would probably be the easiest way to use an if loop but something is very off with that and I am a little stuck.
Is my attempt okay in general or does it need a separate function that I have to call in order to do what I want to do?
onConfirm(hour, minute) {
this.setState({ time: `Dauer: ${hour}:${minute}` });
this.setState(if((hour) < 4){return price = `Preis: (${hour}* 1.5) €`;}
else {return price= 'Preis: 5.50 €';} );
this.TimePicker.close();
}

Within an object literal, you can't use statements, only expressions. if is a statement.
If you want to do that either/or logic in an expression, you use the conditional operator (? :), like this:
onConfirm(hour, minute) {
this.setState({
time: `Dauer: ${hour}:${minute}`,
price: hour < 4 ? `Preis: (${hour}* 1.5) €` : 'Preis: 5.50 €'
});
this.TimePicker.close();
}
The conditional operator expression in the above is:
hour < 4 ? `Preis: (${hour}* 1.5) €` : 'Preis: 5.50 €'
It's a ternary operator (an operator accepting three operands):
The condition to test (hour < 4)
The expression to evaluate if the condition is truthy¹ (`Preis: (${hour}* 1.5) €`)
The expression to evaluate if the condition is falsy¹ ('Preis: 5.50 €')
Also note you had a closing ' on a template literal (needed a backtick instead).
¹ "truthy" and "falsy" - JavaScript implicitly converts (or coerces) values. When you use a value as a test, such as in an if or a conditional operator, JavaScript converts the value you provide to a boolean value (true or false). Values that convert to true are called "truthy" values, ones that convert to false are called "falsy." The falsy values are NaN, null, undefined, 0, "", and of course false (on browsers, document.all is also falsy for various reasons I explain in my book). All other values are truthy.

Related

CAP framework CQL UPDATE with timestamp comparison or case-when statement

I am trying to UPDATE an entity set with a where condition containing the comparison of two timestamps. However, this is not working, as somehow the timestamps can't be compared (I don't get any hits no matter which manipulation I apply on the timestamps).
```UPDATE(CardReceiverAllocation).set({ isCurrentAllocation: true }).where({ card_ID: receiverEntryResult.card_ID, receiver_ID: receiverEntryResult.receiver_ID, timestamp: maxTimestamp })```
As an alternative I tried to write the UPDATE statement with an inclusive CASE WHEN statement, but this is generating the error "column is of type boolean but expression is of type text" even though I am returning boolean values in the statement.
```UPDATE`efa_CardReceiverAllocation`.set`isCurrentAllocation = ( case when timestamp = ( select max(timestamp) as maxTimestamp from efa.CardReceiverAllocation as CRA where CRA.receiver_ID = receiver_ID and CRA.card_ID = card_ID ) then true else false end )` ```
Does anybody know of a solution on how to achieve this update? Thank you in advance!

If/then calculation within Zap running even when statement is false

Essentially what I'm attempting to do is circumvent when users enter a number in a non-standard format. For example:
1.5 million should be 1500000
Previous Zap step extracts the number using the Formatter > Extract Number function. So the result is the variable rawNum and the original number is noformatNum.
var str = inputData.noformatNum;
var n = inputData.noformatNum.includes ("million");
if (n = true) return {
finalNum: Number(inputData.rawNum) * 1000000
};
else return { finalNum : inputData.noformatNum };
It works in that it completes the operation and turns 1.5 to 1500000, but it executes each time, even if noformatNum doesn't include "million" in the string. I'm not super experienced with Javascript, but after digging around W3C and the Zapier documentation for a couple hours I'm stumped. Any help is much appreciated. Thanks!
It looks like there's a small but significant syntax issue here. You'll want to use a triple equal sign === instead of a single = in your conditional.
if (n = true) return {
should be
if (n === true) return {
In an if...else statement, the part in parenthesis (the "condition") should be something that evaluates to either a "truthy" or "falsy" value. (MDN)
n = true assigns the value of true to the variable n, so JavaScript considers the whole thing "truthy" no matter what.
n === true compares n to true, which is what you want for the if...else statement to work. The value will be "truthy" or "falsy" depending on the value of n.

Even if, IF condition is false why statement executes in Javascript?

This is my code,
columnLength = tColumns.length;
if (parseInt(columnLength) ==2) {
tColumns[0].parentNode.insertBefore(tD, tColumns[0].nextSibling);
}
if (parseInt(columnLength) >= 3)
{
tColumns[0].parentNode.insertBefore(tD, tColumns[0].nextSibling);
tColumns[0].parentNode.insertAfter(tD, tColumns[0].nextSibling);
}`
Suppose columnLength is 1.. 1st IF condition is false and its not executing the inside statements.
Even 2nd condition is false since 1 is not greater than equals to 3, but the statements are being executed!
What is wrong with the code?
I'm using Visual Studio IDE to debug, even in immediate window also IF condition returns false as shown below.
ONTOPIC :
I assume your tColumns.length might not have the value you expect it to have. I guess it has the value of undefined which can not be parsed as an integer.
http://jsfiddle.net/FRXkM/1/
OFFTOPIC :
Might not be related to your problem. But parseInt requires a second parameter in conventional ways.
For example:
parseInt("34", 10);
For info on parseInt and its parameters go to http://www.w3schools.com/jsref/jsref_parseint.asp

Strange result while using Javascript not operator

Before anyone jumps in to answer and bash me for asking a silly question; I'm aware of what the not operator does, at least in other languages it should invert a result from true to false and vice versa. The thing I'm stuck on is the strange behavior I get from time to time. I.e. I had this in my code. It's not doing what I expect it to do.
_checkOnOff: function(inst) {
return (!$.suggestBox.onOff || !$.suggestBox._get(inst, 'onOff')) ? false : true;
},
The actual values for the 'onOff' variables that I'm dealing with here are 0 and 1. I'm assuming that the '!' operator will reverse them.
However I couldn't get it to work until I changed the function to explicitly state '== 0' like so...
_checkOnOff: function(inst) {
return ($.suggestBox.onOff == 0 || $.suggestBox._get(inst, 'onOff') == 0) ? false : true;
},
Edit: Added info Both $.suggestBox.onOff and $.suggestBox._get(inst, 'onOff') will be either 0 or 1.
My question is why didn't !$.suggestBox.onOff produce true when $.suggestBox.onOff was equal to 0? Is Javascript ! equivalant to the bitwise operator?
Edit: Second attempt
I tried using '!!' like was suggested (to get a bool) and found nothing changed. Here is the code and outputs:
console.log('val: ' + $.suggestBox.onOff); // outputs: 0
console.log('! : ' + !$.suggestBox.onOff); // outputs: false
console.log('!! : ' + !!$.suggestBox.onOff); //outputs: true
console.log('!!! : ' + !!!$.suggestBox.onOff); //outputs: false
The output doesn't change if $.suggestBox.onOff is 1 or 0!!! it's still false, true, false. What is going on?!
Edit: Third attempt I found out that it has something to do with my variable. I don't know how, but it has to do with the way that it has been set. Ok, prepare yourselves, what I'm about to tell you, may very well blow your mind and change the way you type on the keyboard. It's that incredible:
//this.onOff = 0;
console.log('this.onOff: ' + this.onOff); //output: 0
console.log('! : ' + ! this.onOff); //output: false
console.log('!! : ' + !! this.onOff); //output: true
If I uncomment out the 'this.onOff = 0', thereby explicitly assigning this.onOff to a literal, it changes the output to:
0
true
false
I just found out why. I will write it down in the answer section. Small clue is that it's the way the variable $.suggestBox.onOff was set.
It seems that $.suggestBox.onOff is set with "0" as a string, which in JavaScript is always truthy.
Since "0" is truthy and 0 is falsy, you'd expect 0 == "0" to be false, but it's not.
Try the following in your console:
!! "0"; // true
!! 0; // false
0 == "0"; // true
Weird? Yes. Welcome to the awkward world of JavaScript!
To get around this issue, you should either have $.suggestBox.onOff be an actual number, or convert it on the fly:
_checkOnOff: function(inst) {
return !! ( +$.suggestBox.onOff && +$.suggestBox._get(inst, 'onOff') );
}
Update: Since you pointed out in the comments that you're setting it by a text value, use this when setting it so that it's always set as a number:
$.suggestBox.onOff = +$(this).val();
I think you're confused, because you're negating a string, not a number. Strings are a bit different and handled a bit funny when it comes to their evaluation as a boolean.
!0
is true, as expected.
!"0"
is false... so, the question, is "0" truthy?
I wish I had a better source (sitepoint isn't bad, but it's not as authoritative as a w3 document), but, according to http://www.sitepoint.com/javascript-truthy-falsy/
The following values are always falsy:
false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number!)
All other values are truthy, including
"0" (zero in quotes), "false" (false in quotes), empty functions,
empty arrays, and empty objects.
So, what you are seeing is indeed expected.

What's the difference between & and && in JavaScript?

What's the difference between & and && in JavaScript?
Example code:
var first = 123;
var second = false;
var third = 456;
var fourth = "abc";
var fifth = true;
alert(first & second); // 0
alert(first & third); // 72
alert(first & fourth); // 0
alert(first & fifth); // 1
alert(first && second); // false
alert(first && third); // 456
alert(first && fourth); // abc
alert(first && fifth); // true
It seems like && is a logical and which gives me always the second value if both are true.
But what is &?
(By the way, && seems to be and in Python; & seems to be & in Python)
& is bitwise AND
This operator is almost never used in JavaScript. Other programming languages (like C and Java) use it for performance reasons or to work with binary data. In JavaScript, it has questionable performance, and we rarely work with binary data.
This operator expects two numbers and retuns a number. In case they are not numbers, they are cast to numbers.
How does it work? Wikipedia has an answer: https://en.wikipedia.org/wiki/Bitwise_operation#AND
&& is logical AND
Most usually, programmers use this operator to check if both conditions are true, for example:
true && true // returns true
true && false // returns false
However, in JavaScript, it is extended to allow any data type and any number of terms. It returns:
First term that evaluates to false
Last term otherwise (if all are true-y)
Here are some examples:
true && false && true // returns false
true && 20 && 0 && false // returns 0 (it is first false-y)
10 && "Rok" && true && 100 // returns 100 (as all are true-y)
&& short-circuiting
As can be seen from above, as soon as you find one that term is false-y, you needn't to care about the following terms. This allows Javascript to stop evaluation altogether. This is called short circuiting.
This statement doesn't alert anything and false is returned:
true && false && alert("I am quiet!") // returns false
Therefore, you could use the && operator as a shorter replacement for an if statement. These are equivalent:
if (user.isLoggedIn()) alert("Hello!")
user.isLoggedIn() && alert("Hello!")
Almost all JS compressors use this trick to save 2 bytes.
& is the bitwise "and". This means that if you have two numbers converted to binary, the result is a number that has the 1 digit at the positions where both numbers have 1.
100011 //35
& 111001 //57
---------
100001 //35 & 57 == 33
To determine whether two boolean values put together are true or false, if you want to check them both (like validation on the web page), you may use the & operator. & is bitwise AND.
With the && operator, once it finds the first value is false, it will end evaluation and not to check the second value.
With all the lofty, detailed insights throughout, they have mostly missed the truth that there is a conditional evaluation where ONLY the single & will work. The practical layman's answer that solved my head beating on an IF statement string of MULTIPLE chained && each !== to a condition was causing FAILURE and needed to legitimately use the single &. I thank Jake Wayne (and Russ) for their unfairly downvoted answer that got it right given that where there is more than one && that !== it has already ceased its evaluation and proceeds no further after the first evaluation is found ==!. With the && it thinks its job is done after the first evaluation shows !== [eg. false]. My failing code was
IF ((sessionStorage.myLable !== "LableStringA") && (sessionStorage.myLable !== "LableStringB") && (sessionStorage.myLableZ !== "LableStringA") && (sessionStorage.myLableZ !== "LableStringB")) { ...)
Here, properly substituting and using a single & for the && it was both practically in the real world and technically the correct answer. Thank you again Jake Wayne (and Russ) for the insight and understanding of code.

Categories