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

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.

Related

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

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.

for_each inside if_else in JS

I am new to the coding world, just started learning javascript. Im trying to design a table kind of output but unable to complete it. here is what I am trying to achieve
"Jan - 1 - quarter1" and on second row
"Feb - 2 - quarter1" ...etcetera
I made use of foreach , if/else and combine them both but couldn't get output maybe because we cannot add a foreach inside an if statement or so! can someone help where I am going wrong here?
const Months = ['jan','Feb']
if (Months = 'Jan'||'Apr'||'Jul'||'Sep') {
Months.forEach(function(Month, index) {
console.log(`${Month}--${index + 1}`)}
} else {
console.log(`${Month}--${index + 1}`)
}
It's pretty unclear what you're trying to accomplish but I wanted to offer a few things that I saw in your code. Since you are quite new, I understand you may not be super familiar with the language yet.
First, if (Months = 'Jan'||'Apr'||'Jul'||'Sep') will always return true no matter what, because you're making three separate mistakes! No worries, let me break them down for you.
The first mistake is that you are using a single equals sign in Months = 'Jan'. The single equals sign is what is known as an ASSIGNMENT operator. You are setting your variable Months equal to the string 'Jan'. What you are looking for is the STRICT EQUALITY operator === which tests to see whether two things are equal.
Please see this for reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators
Your second mistake is that you are looking at the entire Months variable and trying to compare its values against strings. If you had used strict equality like so:
if (Months === 'Jan')
it still would have failed because Months is an Array. What you need to do is use Months.forEach to iterate over each element of the array, and then do an equality comparison over each month.
Your third mistake is the way you are using the OR operator ||.
Let's look at this code that will have fixed the prior two errors:
var months = ['Jan','Feb','Apr','Jul','Sep'];
months.forEach(element => {
if (element === 'Jan' || 'Feb' || 'Mar'){
console.log('Gotcha');
}
});
This will still always return true because EACH THING SEPARATE BY THE OR OPERATOR WILL BE EVALUATED INDEPENDENTLY. In order to properly run your test, you need a separate equality test in each section separated by an OR.
Run the following code snippet and look at the output:
var foo = "Hi";
const test1 = (foo === "Boo" || "You");
const test2 = (foo === "Boo" || foo === "You");
console.log(test1);
console.log(test2);
if (test1) {
console.log("This is true??")
}
So, what is going on there?
test1 winds up being assigned the value of "You" because the first part evaluates to false, so it assigns the second part.
test2 is false as we would expect.
But what happens if we use an "if" statement on test1, which is currently set to the string "You"?
Take a look at this answer for clarity. why does if("string") evaluate "string" as true but if ("string"==true) does not?
At the end of it all, what you want is something like this:
var months = ['Jan','Feb','Apr','Jul','Sep'];
months.forEach(element => {
if (element === 'Jan' || element === 'Feb') {
console.log('woot');
}
});
You want this? Make an array with the data that you want.. and go through the array with a foreach ?
var months = ['Jan','Feb','Apr','Jul','Sep'];
months.forEach(element => {
console.log(element + " - " + "quarter1");
});

Finding neighbors in a game of five-in-a-row

I can declare a winner if a player gets five of their tokens in a row, and now I am trying to implement the feature of capturing an opponent's pieces. For example, I am player X, I can trap O's pieces like this X00X in any direction on the board. In order to implement this, is the following logic correct:
Find all neighbors around O, check and see if the neighbor is an X or an O, if there are two 0's in a row surrounded by an X on each side, I can take those pieces. Is there a better way to approach this problem? I am thinking of something like this:
function isOCaptured(token, row, col){
if(gameBoard[row][col]==="O" && gameBoard[row][col+1] === "X"
&& gameBoard[row][col-1] === "X"){
return true;
}
return false;
}
But it does not seems to return true when I place one O in between two X's.
Here is what my server.js and app.js look like right now: https://jsfiddle.net/Amidi/s3gnx3rL/4/ The HTML is just a 13 x 13 grid of buttons with an event attached to each which sends the buttons coordinates to the add() function in my app.js
Now, the problem seems to be that the code only works if the "O" was placed last. This can be solved with a for-loop.
for(var i = -1; i <= 1; i++) {
if (gameBoard[row][col+i]==="O" && gameBoard[row][col+i+1] === "X"
&& gameBoard[row][col+i-1] === "X") {
return true;
}
}
return false;
You can also use a slice:
// The closest 5 cells to the left/right of the newly added piece, as a string
var str = gameBoard[row].slice(col-2,col+3).join("");
// Look for the pattern "XOX" in those 5 cells. Double negation to return bool.
return !!str.match("XOX");
Old answer
According to your comment, the code was called like this:
if(isOCaptured(x,y)===true){console.log("y is between 2 x\s");
This means that the function is called with two instead of three arguments. That will result in the following values of the arguments: token = x, row = y and col = undefined.
The expression being evaluated will thus be:
gameBoard[y][undefined]==="O" && gameBoard[y][undefined+1] === "X"
&& gameBoard[y][undefined-1] === "X"
Which would evaluate as follows:
Evaluating gameBoard[y] will succeed, resulting in a column (the wrong one though).
Then we try indexing the column with undefined, and since the array doesn't contain an element called undefined, it will fail, resulting in (again) undefined.
Then we compare this value undefined with "0", which is obviously false.
The expression false && ... will return false, as will the whole function.
If the second part would have been executed, it would calculate undefined+1, which is (quite accurately) evaluated to NaN (not a number). The array doesn't contain NaN either, so this calculation would evaluated to false as well.
Now, for some advice:
The statement if(expr){return true} else {return false} can be simplified to just return expr.
These kinds of bugs are pretty easy to find if you use the Chrome Debugger (or Firebug for firefox), where you can step through the code and see exactly what happens and where stuff goes wrong.

JavaScript While Loop Conditional Abberation

I am curious as to why this while loop is not breaking as expected. It is my understanding that when using the OR operator (||), if any of the conditions are found to be false, the loop breaks.
However, I noticed in a test document (I am learning JS for the first time) that my while loop is requiring ALL conditions to be found false before breaking.
This is a stub example:
var stringName="", numhours=0, numRate=0;
document.write("Exit at any time by entering -1");
while (stringName != "-1" || numHours != -1 || numRate != -1){
stringName = prompt("Enter name","");
numHours = prompt("Enter num hours","");
numHours = parseFloat(numHours);
numRate = prompt("Enter rate per hour","");
numRate = parseFloat(numRate);
}
I would like it so that a user can enter -1 at any stage, and once the loop completes, it will re-check the conditions again, and after finding that the it is false that the name does not equal "-1", or false that the hours does not equal -1, or that it is false that the wage does not equal -1, it will break the loop.
Instead, it seems the loop is requiring that all of those conditions are met to exit, where name == "-1" AND hours == -1 AND wage == -1, only then will it break.
Any insight would be appreciated. You guys rock!
You have your understanding of the OR operator backwards. You're treating it like AND.
Instead of:
It is my understanding that when using the OR operator (||), if any of the conditions are found to be false, the loop breaks.
It's actually
If any of the conditions are found to be true, the loop continues.
To fix the problem you can rewrite your loop to be:
while (stringName !== "-1" && numHours !== -1 && numRate !== -1)
Also it is preferable to use !== instead of != because != does something weird called type coercion that can give you results you don't expect.
You have it backwards. The || operator evaluates to true if either operand has a "truthy" value (true, non-null, etc.). Your while loop will exit only when all the individual inequality tests are false. If you want it to exit when any of them is false, use the && operator instead.
while(condition) will loop until condition == false.
Your question can be answered when we test this using the console:
true||false||false||false||true will evaulate to true
since OR statements evaluate to true if any one of their conditions are true.
Logical OR Operator

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