JS Logical And / Or - javascript

Can someone explain to me why both of these alert 'True'? The logical OR makes sense I think - The OR short circuits after the first test: 100 != 90, therefor it is true. By why does the AND short circuit after the first test and not keep going?
if (100 != 90 && 100 && 190 && 200 && 290){
alert("true");
} else {
alert("false");
}
if (100 != 90 || 100 || 190 || 200 || 290){
alert("true");
} else {
alert("false");
}
EDIT: THANK YOU EVERYONE FOR YOUR HELP! BASED ON YOUR SUGGESTIONS, I THINK I WILL AMMEND MY CODE TO THIS:
var trains = [90,100,190,200,290];
var testValue = 100;
if (trains.indexOf(testValue) >= 0){
alert("true");
}

This will evaluate to true:
if (100 != 90 && 100 && 190 && 200 && 290)
Because each part is truthy. Any non-zero value in javascript is consider to be equivalent to true. So you have:
if (true && true && true && true && true)
Which is, obviously, true. It's not short circuiting, because none of the values are false.
I suspect the mistake you've made is to think that this:
if (100 != 90 && 100)
Is doing the same thing as this:
if (100 != 90 && 100 != 100)
Which is simply not how the syntax works. It's easy to say in words "if 100 doesn't equal 90 and doesn't equal 100" and understand what that means, but in javascript (and most other languages) you have to be explicit.
Now obviously this gets really tedious if you have a value that you need to compare with a long list of values, for example:
if (x != 90 && x != 100 && x != 190...)
And in a case like that, it's usually easier to put all your values into an array and instead ask if x is contained (or not) in that array:
var values = [90,100,190,...]
if (!values.some(function(e) { return e === x; })) {
// the value x is not in the array values
}

For the &&, the first 100 != 90 evaluates to true. Then, the integers are implicitly converted to bools, where 0 = false, true otherwise. The true will carry through the numbers, of which none are 0.
Your comment about || is correct.

Related

Function in php or javascript - number between -200 and 200 but not zero

I'm looking for solution in php or javascript to check that given variable is a number between -200 and 200, and not zero.
This is the code I have so far
if ($myValue >= -200 && $myValue <= 200) {
print($myValue);
}
if ($value != 0 && abs($value) <= 200) {
echo $value;
}
you can use abs to shortend condition
http://php.net/manual/pl/function.abs.php
Just add && $myValue != 0 to your if statement
if ( !empty($myValue) && $myValue >= -200 && $myValue <= 200) {
empty will also give you the added benefit of checking if the variable is set. Then it will check it is not 'falsy'. e.g. false, zero, empty array, etc.

Need an elegant way to change the return results of a in line if statement based on inputs

To better explain what Im trying to do Im going to preface a bit with no code and then show you the code I am working with in the pertinent pieces.
I currently and working with a function that measures the width and height of a canvas element and divides half of each size by an inputted number. I then decide if the resulting number is even by using math.ceil() and %2===0. Using this formula I will decide if the width is boolean true or false and the same for the height.
In the end I will have
var A = True (or False)
var B = True (or False)
I then have the creation of a 3 dimensional array:
var pax = [];
for (var i = 0; i < stage.height()/12; i++){
pax[i] = [];
for (var j = 0; j < stage.width()/12; j++){
pax[i][j] = [];
pax[i][j].push("if statement here");
};
}
I need an elegant way to replace "if statement here" with something like a double if statement where
if (A === B) {
(((i%2)===0)===((j%2)===0)) ? 0 : 180)
||
(((i%2)===0)!==((j%2)===0)) ? 180 : 0)
} else {
(((i%2)===0)===((j%2)===0)) ? 180 : 0)
||
(((i%2)===0)!==((j%2)===0)) ? 0 : 180)
};
Im pretty sure this monstrosity that I just typed wont work, so I need both the correct way to type the syntax and a more elegant and resource light way to do it, just due to the amount of index locations I will be pushing to in the array.
Basically what Im trying to do is say "Based on the height and width of the canvas, if i is even, return 0, and if i is odd, return 180, OR based on the height and width of the canvas, if i is even, return 180, and if i is odd, return 0.
I can attempt to explain this again if this is unclear.
You want your modulus operations to match or not match. With x % 2, there can only be one of two results, so there's no point in converting to a boolean with ===. And the parens are just excessive. All that clutter doesn't help. So here's a first pass:
if (A === B) {
(i%2===j%2 ? 0 : 180) || (i%2!==j%2 ? 180 : 0)
} else {
(i%2===j%2 ? 180 : 0) || (i%2!==j%2 ? 0 : 180)
}
Then it seems that you want the numbers flipped based on comparison to A === B. So if they are equal and even you want 0, 180 or if they are unequal and odd, you want 180, 0. So basically if the i/j comparison and the A/B comparison are the same, you have one result, otherwise, the other.
The odd thing is that when one % test succeeds but yields 0 the || operation makes it attempt the opposite % test, which of course will fail. But because the numbers are reversed for the second test, we end up with the correct value. It's just that you're going about it in a roundabout way.
Ultimately, what your code does is simply this:
(A === B) === (i%2===j%2) ? 0 : 180
Here's a demo that shows that your original and short version achieve the same result.
DEMO: http://jsfiddle.net/jDWf6/3/
(EDIT: Updated demo to show all values tested.)
The condition:
if (A === B) {
(((i%2)===0)===((j%2)===0)) ? 0 : 180)
||
(((i%2)===0)!==((j%2)===0)) ? 180 : 0)
} else {
(((i%2)===0)===((j%2)===0)) ? 180 : 0)
||
(((i%2)===0)!==((j%2)===0)) ? 0 : 180)
};
(There's no need for a semi–colon after a block statement)
is overly complex and can be reduced to (assuming it should return something):
var result;
if (A === B) {
result = i%2 == j%2? 0 : 180 || i%2 != j%2? 180 : 0;
} else {
result = i%2 == j%2? 180 : 0 || i%2 != j%2? 0 : 180;
}
In the first assignment, the two || operands return the same value for any given values of i and j, so it might as well be:
result = i%2 == j%2? 0 : 180;
since if i%2 == j%2 returns true, then:
i%2 == j%2? 0 : 180
returns 0, which converts to false, so the second expression is evaluated:
i%2 != j%2? 180 : 0
and i%2 != j%2 must return false (since the opposite was true) and again 0 is returned. The exact opposite occurs if the original expression returned false:
i%2 == j%2? 0 : 180
returns 180, which is truthy, so the otehr side of the || is not evaluated.
So now you have:
if (A === B) {
result = i%2 == j%2? 0 : 180;
} else {
result = i%2 == j%2? 180 : 0;
}
That means that the result of:
i%2 == j%2? 0 : 180
is reversed based on A === B, so:
result = A === B? (i%2 == j%2? 0 : 180) : (i%2 == j%2? 180 : 0)
Of course this could be way off if your pseudo code isn't doing what you hoped…
ok my friend based on what you asking here is the answer.
*I don't know if this will be what you will looking for because your logic is a bit complicated and not so correct....
As you can see i reduced the code and i maximized the performance. Also i make clear what "i" is and what "j". Just to be more readable...
var pax = [];
var isHeightEven, isWidthEven;
for (var height = 0; height < stage.height() / 12; height++) {
pax[height] = [];
for (var width = 0; width < stage.width() / 12; width++){
pax[height][width] = [];
isHeightEven = !(height % 2); //calculate only once
isWidthEven = !(width % 2); //calculate only once
pax[height][width].push(
(A === B) ? ((isHeightEven && isWidthEven) ? 0 : 180) : ((isHeightEven && isWidthEven) ? 180 : 0)
);
};
}

Javascript if statement in RPG

I'm learning about canvas by making a simple RPG.
I'm trying to make it so that if you walk into a certain area, it runs a function. So I used an if:
if (x<150, x>50, y<150, y>50) {
(code I want to execute)
}
But even when the statement is false, it's still considered true. I want it so that all statements in the parentheses must be true for the code to execute. Any help?
Use &&:
if (x < 150 && x > 50 && y < 150 && y > 50) {
// (code I want to execute)
}
Or to separate each part for readability:
if ((x < 150) && (x > 50) && (y < 150) && (y > 50)) {
// (code I want to execute)
}
To learn more, check out:
Logical Operators
Use &&, not ,:
if (x<150 && x>50 && y<150 && y>50) {
Using && means you want all of the conditions between the brackets evaluated. The code below will be executed if x is less the 150 AND y is less than 150 AND x is greater than 50 AND y is greater than 50. If only 3 of the conditions are satisfied, the code will not run. As a result your new code will look like this:
if (x < 150 && x > 50 && y < 150 && y > 50) {
// (code I want to execute)
}
Using || basically means or, and the code gets executed if any of the conditions are valid. The code below will be executed if x is less the 150 OR y is less than 150 OR x is greater than 50 OR y is greater than 50. In effect, if even 1 of the conditions is met the code will run.
if (x < 150 || x > 50 || y < 150 || y > 50) {
// (code I want to execute)
}
You can find a simple tutorial here

regex for javascript pattern match

i'm looking for a regex expression or javascript which alerts me when a number is NOT between 48-47 or NOT between 96-105 or IS NOT 110 OR 190 OR 8 OR 13.
thanks for all the help friends !!
Regex is not appropriate for such specific numeric checks. Just do a few if statements to compare the value you're working with to the specific values and ranges you want to exclude.
var number = 19;
alert('Number is'+(numberIsValid(number) ? 'valid' : 'not valid'));
function numberIsValid(number) {
// test for numeric argument
if ((number - 0) != number)
return false;
// test for specific exclusions
if (number == 110 || number == 190 || number == 8 || number == 13 || number == 48 || number == 47)
return false;
// test for excluded range
if (number >= 96 && number <= 105)
return false;
return true;
}
I agree with Chris's response above, if you want to see what it would look like, it is kind of a mess. I wouldn't really recommend you use this.
Just to rephrase: Number may not be 8,13,47,48,96-105,110
var num = 10;
if (! /^(8|13|47|48|9[6-9]|10[0-5]|110)$/.test(num)) {
alert(num);
}
function allowedIntegers(n){
return !/^([^\d]|8|13|47|48|110|190|96|97|98|99|100|101|102|103|104)$/.test(String(n));
}

Multiple Logical Operators in javascript

I want to check the following
1: Is x a number
2. If x is less that 5 or greater than 15, sound alert
3. If all is ok, callMe()
var x = 10;
if (isNaN(x) && ((x < 5) || (x > 15))) {
alert('not allowed')
}
else
{
callMe();
}
What am I doing wrong?
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}
This way, if x is not a number you go directly to the alert. If it is a number, you go to the next check (is x < 5), and so on.
All the other answers about the && vs || are correct, I just wanted to add another thing:
The isNaN() function only checks whether the parameter is the constant NaN or not. It doesn't check whether the parameter is actually number or not. So:
isNaN(10) == false
isNaN('stackoverflow') == false
isNaN([1,2,3]) == false
isNaN({ 'prop' : 'value'}) == false
isNaN(NaN) == true
In other words, you cannot use it to check whether a given variable contains a number or not. To do that I'd suggest first running the variable through parseInt() or parseFloat() depending on what values you expect there. After that check for isNaN(), because these functions return only numbers or NaN. Also this will make sure that if you have a numeric string then it is also treated like a number.
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}

Categories

Resources