What should be the value of x? - javascript

what value should X have so this condition would work?
// insert code here
if (x == 1 && x === 2) {
console.log('Succes!');
}

X should be defined like so:
Object.defineProperty(window,'x',{
get: function() {
this.__tmp = this.__tmp || 2;
this.__tmp = 3-this.__tmp;
return this.__tmp;
}
});
Then:
if( x == 1 && x === 2)
MIGHT work. Demonstration

The following code should do the trick (Demo here):
x = {};
x.valueOf = function (){
x = 2; // this is important
return 1;
};
if (x == 1 && x === 2) {
console.log('Success !!!');
}
Explanation:
The statements are executed from left to right (so first x == 1, then x === 2). When checking x == 1, it will go to the valueOf function, which returns 1, so it will be true. But at the same time, x is changed to be 2, thus the next statement that will be checked (x === 2) will also be true.
PS: As far as I know, this has no practical application. However, it can lead to better understanding of how javascript works - which is the point of such questions :)

X can't hold a value equals to 1 and identical to 2 at the same time, this expression is logically incorrect.

There is no such value.
x === 2 checks if x equals exactly to 2, while 2 cannot be 1 at the same time.
Only the following would make sense:
if (x && x === 2) { ... }
(or getter overloading, as demonstrated in #Niet the Dark Absol's answer, which is not a pure case)

Using === (identity) operator it will never work, but it's possible to construct an object that will be "equal" (==) to 1 and 2 at the same time:
x = { valueOf: function() { return this.foo ? 2 : this.foo = 1 } }
console.log(x == 1 && x == 2) // true
"valueOf" is the method JS implicitly calls when you convert or compare an object to a number.
Needless to say, this exercise doesn't have any practical sense.

Related

Bitwise - Why 0 & 1 !== 1 & 1 return false in VSCode/Leetcode?

I was writing an algorithm to compare how many bits are different between 2 numbers using this function
var hammingDistance = function(x, y) {
let result = 0;
while (x !== 0 || y !== 0) {
// This line is incorrect
if (x & 1 !== y & 1) result++;
x = x >> 1;
y = y >> 1;
}
return result;
};
But my result is always 1 less than the correct answer, and it turns our my function is wrong when comparing the left most digit, such as 0011 and 0100. It returns 2 instead of 3.
https://i.imgur.com/P46RyZr.png
I can use XOR instead of !== to get the correct answer. But I'm wondering why?
Your problem is that !== has a higher precedence than &. So your condition is actually (x & (1 !== y)) & 1. Use explicit grouping instead:
if ((x & 1) !== (y & 1)) result++;
It works with ^ because that has a lower precedence than &.

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);
}

jQuery explanation of (!= and == and others) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am learning jQuery and I have seen that people in plugins use following quite a lot, and I don't know the meaning of each. So explanation of each would be really appreciated.
So here's the list, maybe I have type wrong some of but anyone is welcome to edit my post.
==, ===, !0, !1, !=, !==
Please explain to me... Thanks!
Check out this list of javascript logical operators:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators
and comparison operators:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comparison_Operators
Operator Description
== is equal to
=== is exactly equal to (value and type)
!= is not equal
!== is not equal (neither value nor type)
> is greater than x>8
< is less than x<8
>= is greater than or equal to
<= is less than or equal to
!0 Not 0 (could be used as not false)
!1 Not 1 (could be used as not true)
source
// Comparison operators
var foo = 1;
var bar = 0;
var baz = "1";
var bim = 2;
foo == bar; // returns false
foo != bar; // returns true
foo == baz; // returns true; but note that the types are different
foo === baz; // returns false
foo !== baz; // returns true
foo === parseInt( baz ); // returns true
foo > bim; // returns false
bim > baz; // returns true
foo <= baz; // returns true
Link: http://stage.learn.jquery.com/javascript-101/operators/
Simply put, these are used to compare 2 values in an "if" statement. They are called comparison operators. Each one makes a different comparison. The most confusing are the 2= and the 3=. The third equals sign compares data types as well as value. More often than not, you will not need the 3rd = sign unless you are creating "strict" code. The operators break down like so:
== is equal to
Example: if (x == z) // this would return true if both x and z were the number 7
=== is exactly equal to (compares value and type)
Example: if (x == z) // if x is the String 7 and z is the Integer 7, this would return false
!= is not equal
Example: if (x != z) // if x is 7 and z is 8 then this if statement would return true
!== is not equal (again, compares both value and type)
Example: if (x !== z) // If both x and z are 7 but one is a String, while the other is an integer, then this would return true, because they are not the same type
> is greater than
Example: if (x > z) // If x is 8 and z is 7, then this would return true
< is less than
Example: if (x < z) // If x is 8 and z is 7, then this would return false
>= is greater than or equal to
Example: if (x >= z) // If x is 8 or 7 and z is 7, then this would still be true in either case
<= is less than or equal to
Example: if (x <= z) // If x is 8 and z is 7, then this would return false, but if x was 7 then it would be true
For more information, please follow these links:
http://www.w3schools.com/js/js_comparisons.asp
http://www.javascriptkit.com/jsref/comparison_operators.shtml
http://www.how-to-code.com/javascript/javascript-tutorial/comparison-operators-in-javascript.html

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();
}

How to check several local variables for the same if conditions

Alright, I find the code below to be quite repetitive and annoying. Any other way to refactor the code without using an array as a starting point (that is, to avoid using array[x], array[y], array[z] later on in the code as a result of starting with an array because x,y,z are completely unrelated and it makes no sense to group them for the sake of readability)
var x = "";
var y = "";
var z = "";
...
...variables get set
if(x != undefined && x != "")
doSomethingHere();
if(y != undefined && y != "")
doSomethingThere();
if(z != undefined && z != "")
doSomethingElse();
...
At very least you can factor out your validation rules to their own function:
function IsValid(x)
{
return (x != undefined && x != "");
}
var x = "";
var y = "";
var z = "";
//...
//...variables get set
if(IsValid(x)) doSomething();
if(IsValid(y)) doSomething();
if(IsValid(z)) doSomething();
In addition to what joel said you could also do the following:
function doOnValid(x, func){
if(x != undefined && x != "") func();
}
Then you could do:
doOnValid(x, doSomething);
doOnValid(y, doSomethingElse);
doOnvalid(z, function() { /*Yay lambda function*/ });
If you're trying to avoid repetition, be it vertical (var x;\r\n;var y;\r\n...) or horizontal (if (x || y || z || ...), a nice way to tidy things up is to gather your variables into an object as properties:
var vars = {
x: 42,
y: "",
z: undefined
};
for (var v in vars) {
var value = vars[v];
if (value != undefined && value != "") {
doSomething();
}
}
On top of that, if the action to be taken is different for each variable, you can also define an "actions" structure:
var actions = {
x: doSomething,
y: doSomethingElse,
z: doSomething
};
for (var v in vars) {
var value = vars[v];
if (value != undefined && value != "") {
actions[v]();
}
}
Is there a reason you initialize x,y and z to "" ?
If you just do
var x;
..... maybe set x .....
if (x)
doSomething()
You save quite a lot of fuzz. You can do the same for y and z ;) The initial value of x is undefined, which you can check with if (x), which means the same as if (x != undefined)
First of all, because both undefined and the empty string ("") evaluate as "false" in javascript, you can change your conditionals to:
if (x)
doSomething();
if (y)
doSomething();
if (z)
doSomething();
If the Something to be Done is always the same, you can certainly do
if (x || Y || z)
doSomething();
I'm guessing the original should have used y != undefined and doSomething () is the same function in all cases:
if((x != undefined && x != "") ||
(y != undefined && y != "") ||
(z != undefined && z != ""))
doSomething();
So to follow up on krosenvold's answer I think what you want is
var x;
var y;
var z;
// do stuff
if (x||y||z)
doSomething();
Which is much neater
This is about as concise as I can make it, assuming you want a unique action for each condition.
(x && doX());
(y && doY());
(z && doZ());
This works because your particular variable test just reduces to the value of the variable. You can, of course, also write a custom condition function:
function is_valid(x){
// return true or false
}
( is_valid(x) && doX() );
( is_valid(y) && doY() );
( is_valid(z) && doZ() );

Categories

Resources