Multiple comparison operators in a JavaScript boolean expression - javascript

I'm trying to check whether the variable y is less than x and greater than z, but this boolean expression is returning false for some reason. Does JavaScript allow boolean expressions to be written concisely like this? If so, what is the correct syntax?
x = 2;
y = 3;
z = 4;
if(x > y > z){
alert("x > y > z"); //Nothing happens!
}

Try using the logical and operator:
if (x > y && y > z) {
to guarantee both conditions are true.
DEMO: http://jsfiddle.net/3sxvy/
If you need to put this into a function, you could try:
function compareNumbers(direction) {
var inOrder = (function () {
if (direction === "desc") {
return function (current, before) {
return current <= before;
};
} else if (direction === "asc") {
return function (current, before) {
return current >= before;
};
}
})();
var valid = true;
for (var i = 2; i < arguments.length; i++) {
if (!inOrder(arguments[i], arguments[i-1])) {
valid = false;
break;
}
}
return valid;
}
if (compareNumbers("desc", 33, 5)) {
console.log("Good");
} else {
console.log("Bad");
}
DEMO: http://jsfiddle.net/kn6M4/1/

Change your test to
if (x > y && y > z){
When you write (x > y > z), this is equivalent to ((x>y)>z), so you're comparing a boolean (x>y) to z. In this test, true is converted to 1, which isn't greater than 2.

You want
if(x > y && y > z){
alert("x > y > z"); //Nothing happens!
}
Javascript will try to parse your original statement from left to right and you'll end up comparing z to a boolean value which will then be parsed to a number (0 or 1).
So your original statement is equivalent to
if( (x > y && 1 > z) || (x <= y && 0 > z))

Related

Javascript even and odd range

I an trying to solve an online quiz but i don't seem to be able to pass all the tests. here is the question
Given two numbers X and Y, write a function that:
1 returns even numbers between X and Y, if X is greater than Y else it returns odd numbers between x and y
For instance, take the integers 10 and 2 . the function would return all the even numbers between 2 and 10.
Examples:
12, 0 => [2,4,6,8,10]
2, 12 => [3, 5, 7, 9, 11]
0, 0 => [ ]
Here is my code:
function number_game(x, y){
let numbers = [];
if (x > y){
for (let i = y; i <= x; i++){
if (i > y){
numbers.push(i);
}
}
}else{
for (let i = x; i <= y; i++){
if (i > x){
numbers.push(i);
}
}
}
const result = numbers.filter(function(num){
return x > y ? num % 2 === 0: num % 2 === 1;
});
return result;
}
While not written optimally, your code is essentially OK, except that it includes the higher number in the result. You're skipping the lower number with your if (i > y) test, although it would be simpler to just start your loop at y + 1.
To exclude the higher number, simply change the repetition criteria from <= to <.
It would also be simpler to perform the even or odd test in those loops.
function number_game(x, y) {
let numbers = [];
if (x > y) {
for (let i = y + 1; i < x; i++) {
if (i % 2 == 0) {
numbers.push(i);
}
}
} else {
for (let i = x + 1; i < y; i++) {
if (i % 2 == 1) {
numbers.push(i);
}
}
}
return numbers;
}
console.log(number_game(12, 0));
console.log(number_game(2, 12));
console.log(number_game(0, 0));
console.log(number_game(3, 13));
console.log(number_game(1, 1));
Because I'm such a damn sucker for code golfing:
const number_game = (x, y) => {
const min = Math.min(x, y), max = Math.max(x, y);
return Array.from(Array(max - min), (_, i) => i + min).slice(1)
.filter(v => v % 2 == (x < y));
};
Perhaps something like this could help.
function number_game(x, y) {
let result = [];
let min=0, max=0;
if(x==y) {
return result;
} else if (x > y) {
min = y;
max = x;
} else {
min = x;
max = y;
}
for (let i = min; i <= max; i++){
if (i%2===0 && x > y && i!=min && i!=max) {
result.push(i);
}
if (i%2===1 && x < y && i!=min && i!=max) {
result.push(i);
}
}
return result;
}
console.log(number_game(12,0));
console.log(number_game(2,12));
console.log(number_game(0,0));
console.log(number_game(13,1));
console.log(number_game(3,13));
console.log(number_game(1,1));
console.log(number_game(1,1000));
console.log(number_game(3,1300));
Instead of generating all the numbers, and then filtering them, you can generate just the numbers that you need:
function number_game(x, y) {
const start = Math.min(x, y);
const end = Math.max(x, y);
const base = x > y ? 2 - start % 2 : start % 2 + 1; // how much you need to add, to get from start to the first number in the result
const numbers = [];
for(let i = start + base; i < end; i+= 2) numbers.push(i);
return numbers;
}
console.log(JSON.stringify(number_game(9, 1)));
console.log(JSON.stringify(number_game(1, 9)));
console.log(JSON.stringify(number_game(12, 2)));
console.log(JSON.stringify(number_game(2, 12)));
console.log(JSON.stringify(number_game(12, 1)));
console.log(JSON.stringify(number_game(1, 12)));
console.log(JSON.stringify(number_game(2, 2)));
function returnOddOrEven(x,y){
// return empty array if both x and y are equal to 0
let mixedArr = [];
if (x ===0 && y===0){
return [];
}
// first condition of x greater than y
else if ( x > y){
for (var i = 1; i < x; i++){
if( i % 2 === 0){
mixedArr.push(i)
}
}
}
// second condition of y > x
else if( y > x){
for (var i = 1; i < y; i++){
if(i > 1 && i % 2 === 1){
mixedArr.push(i)
}
}
}
return mixedArr;
}
function number_game(x, y) {
var numArray = new Array();
if (x > y) {
for (i=y+1; i<x; i++) {
if (i%2 == 0) {
numArray[numArray.length] = i;
}
}
} else {
for (i=x+1; i<y; i++) {
if (i%2 != 0) {
numArray[numArray.length] = i;
}
}
}
return numArray;
}

Can't make the code recognize 0 as a value

I'm making an editable RPG sheet. For this specific section, I need it to compare the 1_7, 2_7 and 3_7 to the result of the equation, and have it select the smaller value. However, while it works on most situations, it doesn't recognize 0 as a value. 1_7, 2_7 and 3_7 are inputted manually.
What should I do in order to get the code to recognize 0 as a value?
var x =
this.getField("1_7").value;
var y =
this.getField("2_7").value;
var z =
this.getField("3_7").value;
var f = Math.floor((this.getField("Des Temp").value - 10) / 2);
var temp;
if(!x)
{
x = f;
}
if(!y)
{
y = f;
}
if(!z)
{
z = f;
}
if(x <= y && x <= z)
temp = x;
else if(y <= z)
temp = y;
else
temp = z;
if(f > temp)
f = temp;
if(f > 0){
event.value = "+" + f;
}
else{
event.value = f;
}
O is a "falsy" value so
if(!x)
Is doing what it is supposed to do. The empty value is probably an empty string so you could do
if ( ! x.length )
instead.
$('#x').on( 'input', function() {
console.log( ! $(this).val().length );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='x' >
It's because 0 is considered as false inside a javascript comparaison. If you want to verify if the field have data, you can use the length property.
var x = 0;
var y = 5;
var z = 3;
var f = 10;
if(0)
{
console.log("0 is false");
}
if(1)
{
console.log("1 or any number != 0 is true");
}
if(x.length)
{
x = f;
console.log("x is not set");
}
if(y.length)
{
y = f;
console.log("y is not set");
}
if(y.length)
{
z = f;
console.log("z is not set");
}

Why can't I assign and then check a variable in the same if statement in Javascript?

In other words, why doesn't this show an alert?
var x;
if (x = 1 && x > 0) {
alert(x);
}
As far as I understand, x = 1 should assign 1 to x and also return 1. The x > 0 check is failing. Why?
Actually, the && operation will have precedence over the assignment.
In you case, x will be the result of 1 && x > 0 which is false.
var x;
if (x = 1 && x > 0) {
alert(x);
}
console.log(x); // false
You can enforce the order of operations using parentheses, as shown by Nina Scholz.
You need some parens to separate the assignment from the ongoing expression.
var x;
if ((x = 1) && x > 0) {
alert(x);
}

Boolean equality

I got this out of an exam question, and couldn't understand how the solution works. This function is supposed to return "true" if the values "x" and "y" are equal, and return False otherwise.
The solution:
function equal_boolean (x , y) {
return x ? y : y ? x : true;
}
Why does this work? As much as I can understand, it would turn out to be evaluating if X is true. If X is true, it would return Y. How is X supposed to be "true"?
If it isn't, it would evaluate whether Y is true, if it's true it would return X, and if it isn't - it would return True.
Is there something wrong with my understanding?
return x ? y : y ? x : true;
parses as
if x
return y // if y is true, then x == y. if y is false, then x != y
else (x is false)
if y
return x // x is false and y is true, y != x, return false
else
return true // x is false and y is false, return true
This is of course a pretty convoluted way to express boolean equality (aka Logical biconditional aka iff). More natural would be an expression like this:
(x && y) || (!x && !y)
The first thing you should do is group the ternary operators together:
(x ? y : (y ? x : true))
if x is true, then return y, whose value also tells you whether x and y are equal
if x is false, then start with the second ternary:
if y is true, then return x (false) as the two are not equal
if y is false, then x and y are equal, so return true
Let's try expanding this a bit:
var myBool = x ? y : (y ? x : true)
return myBool;
First block
x ? y : ...
if X is true, then return value of Y. If Y happens to be true, both are equal. Otherwise return false (no match).
Second block if X was false:
y ? x : true
if Y is true, return X. X was false, so false is returned (no match)
if Y is false, return true - both values are false.
First identify the expressions
return x ? y : y ? x : true;
//turns into
return x ? y : (y ? x : true);
Replace the ?: ternary operators by if statements
if (x) {
return y;
} else {
//here x is false, so we will be able to replace x by false in the next step
if (y) {
return x;
} else {
return true;
}
}
Make if statements more verbose, replace return x by return false
if (x == true) {
return y;
} else {
if (y == true) {
return false;
} else {
return true;
}
}
Finally replace return y; by if (y == true) { return true; } else { return false; }, and check all the possibilities
if (x == true) {
if (y == true) {
return true; // x == true and y == true
} else {
return false; // x == true and y == false
}
} else {
if (y == true) {
return false; // x == false and y == true
} else {
return true; // x == false and y == false
}
}
It works. (As long as x and y are booleans)

Division in javascript

function subtraction(num1, num2){
var num3;
num3 = num1 - num2;
document.writeln("Difference "+ num3);
return (num3);
}
function division(num1, num2){
difference = parseFloat(subtraction());
var x;
while(difference > 0){
difference = num1-num2;
x = x + 1;
}
document.writeln("Quotient" + x);
}
Hi! I wanted to do a division function but the catch is I will not use "/". This is what I got and so far this prints out "undefined" and if I stated x = 0 it will print out "0".
I fixed some problems with your code:
function division(num1, num2){
var difference = num1-num2; // difference is now a local variable
var x = 0; // x should be initialized
while(difference > 0){
difference = difference-num2; // difference should change, not always be num1-num2
x = x + 1;
}
console.log("Quotient" + x);
console.log("Remainder" + (difference+num2));
}
http://jsbin.com/UQIqejo/1/edit
You still have some problems with the algorithm itself, as num2 being less than or equal to 0 will result in an infinite loop, but i expect finding those problems is part of the fun.
EDIT: Smaller version of the same code:
function divisionSmall(a,b) {
var x = 0;
while ((a-=b) > 0) x++;
console.log('Quotient', x);
console.log('Remainder', a+b);
}
EDIT2: Correct division:
function divisionSmall(a,b) {
var x = 0;
while ((a-=b) > 0) x++;
return [x, a+b];
}
function divisionCorrect(a,b) {
var ans;
if (b === 0) return ['INF', 0];
if ((a > 0) && (b > 0)) {
return divisionSmall(a,b);
}
if ((a > 0) && (b < 0)) {
ans = divisionSmall(a,-b);
return [-ans[0], ans[1]];
}
if ((a < 0) && (b > 0)) {
ans = divisionSmall(-a,b);
return [-ans[0] - 1, b-ans[1]];
}
if ((a < 0) && (b < 0)) {
ans = divisionSmall(-a,-b);
return [ans[0] + 1, -b-ans[1]];
}
}
console.log(divisionCorrect(11,3)); // 3, 2
console.log(divisionCorrect(11,-3)); // -3, 2
console.log(divisionCorrect(-11,3)); // -4, 1
console.log(divisionCorrect(-11,-3)); // 4, 1
There is still the challenge of doing the logic without ifs :). Good luck.
If your doing numbers their is a simpler way to do this using recursion:
function divide(num,denom) {
if (num < denom) return 0;
return (1 + divide(num - denom, denom));
}
For negative numbers you would have to extend this to track if numbers were less than 0. Also, while concise and neat, this breaks down for large numerators and small denominators as the max call stack size will be exceeded.
I believe your issue is with your while loop. If the subtraction method returns a negative number it will not compute.
User Math.abs to get absolute value.
<script>
function division(num1, num2){
var difference = Math.abs(parseFloat(subtraction(num1, num2)));
var x = 0;
while(difference > 0){
difference = difference-num2;
x = x + 1;
}
document.writeln("Quotient" + x);
}
function subtraction(num1, num2){
var num3;
num3 = num1 - num2;
document.writeln("Difference "+ num3); return (num3);
}
</script>

Categories

Resources