Why does 1 == 1 == 1, but not 'A' == 'A' == 'A' [duplicate] - javascript

This question already has answers here:
Javascript if (x==y==z): [duplicate]
(2 answers)
Closed 2 years ago.
I'm trying to write a flexible query logic based on a config payload, e.g:
{
"test": "( fieldA == fieldB == fieldC )"
}
When my app replaces 'fieldA', 'fieldB' and 'fieldC' value with text data, the result is always false.
This clearly has to do with me confusing the way javascript runs the comparison (it must have something to do with data types and math ordering), but can anyone explain this with a simple example for alphanumeric values?
e.g. 'John Smith' == 'John Smith' == 'John Smith' is always false;

x == y == z does not do what you think :
it translates to (x == y) == z.
With the quirks of javascript's == operator :
1 == 1 and 'A' == 'A' both translate to true
however : true == 1 returns true, while true == 'A' doesn't
You probably want to rewrite your condition to :
(x == y) && (x == z)
and very probably want to use the unambiguous === operator :
(x === y) && (x === z)
to avoid pitfalls such as the one you falled upon (true == 1 checks, but not true === 1)

A==B==C or A==A==A is legally allowed.
But the problem is, A==C never happens or in your case fieldA==fieldC never happens. Hence this leads to ambiguity

Related

JQuery selector check the number of checkboxes has been checked

What I'm trying to is run some code if the number of input[type="checkbox"] is checked equal to the value of 2 or 3.
Here is an example of my JQuery:
if ($('input:checkbox:checked').length == 2 or 3) {
// run some code
}
Im not sure how to program it to understand whether the value is 2 or 3.
Any ideas?
Use the or operator ||
if ($('#id').length === 2 || $('#id').length === 3) {
// run some code
}
Please read up on Javascript logical operators. This is basic stuff.
Logical operators are used to determine the logic between variables or values.
Given that x = 6 and y = 3, the table below explains the logical operators:
Operator Description Example
========================================================
&& and (x < 10 && y > 1) is true
|| or (x === 5 || y === 5) is false
! not !(x === y) is true

Javascript if (x==y==z): [duplicate]

This question already has answers here:
Double structural equality operators: if(a==b==c)
(2 answers)
Closed 8 years ago.
I've got 3 random numbers (in this specific case between 1 and 7 but it doesn't really matter).
I want to check whether I got "three of a kind" by using
if (x==y==z) {
code
}
The problem is that when x==y and z==1 x==y==z will return true. How do I check whether x, y and z actually got the SAME value?
Example: 5==5==1 will return true, how do I check for 5==5==5 specifically? (Excluding 5==5==1)
By doing a proper comparison:
x === y && y === z
// due to transitivity, if the above expression is true, x === z must be true as well
x==y==z is actually evaluated as
(x == y) == z
i.e. you are either comparing true == z or false == z which I think is not what you want. In addition, it does type conversion. To give you an extreme example:
[1,2,4] == 42 == "\n" // true
The problem is that when x==y and z==1, x==y==z will return true.
Yes, because x == y will be true, so you compare true == 1. true will be converted to the number 1 and 1 == 1 is true.
You should check with separate && operations
if(x == y && x == z){
//all are equal
}

When should you use parentheses inside an if statement's condition?

I have a if condition like so:
$(document).ready(function(){
var name = 'Stack';
var lastname = 'Overflow';
if( name == 'Stack' && lastname == 'Overflow' )
alert('Hi Stacker!');
});
So my alert is fired...
If I put my condition inside a brackets like this:
$(document).ready(function(){
var name = 'Stack';
var lastname = 'Overflow';
if( (name == 'Stack') && (lastname == 'Overflow') ){
alert('Hi Stacker!');
}
});
My alert is also fired...
My question is: When and why I should use parentheses inside my if condition? Thank you!
There is no much difference in your example.
You can read that for reference
Operator Precedence (JavaScript)
You use it to force associations, in your example this won't change anything. But consider this case:
A and B or C
is a lot different from
A and (B or C)
Here you would be preventing the expression from being understood as (A and B) or C which is the natural way javascript and maths do things.
Because of operator precedence :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
you'd better read this if you want more details
But basically == (equality) weights more than && (logical-and) , so A == B is evaluated before C && D given
C <- A == B
and
D <- E == F
so adding parenthesis to C or D dont matter,in that specific situation.
Brackets can be used, if multiple conditions needs to be checked.
For ex: User is also a Stacker if full name is 'StackOverflow' then add another condition with 'Or' operator.
if(((name == 'Stack') && (lastname == 'Overflow')) || FullName =='StackOverflow')
As you can see, name and last name are placed inside one bracket meaning that it gives a result either true or false and then it does OR operation with FullName condition.
And having brackets around name, lastname and fullname fields are optional since it doesn't make any difference to the condition. But if you are checking other condition with FullName then group them into bracket.
Brackets are never required in such situations.
Of course, try to read first solution (without) and second solution (with). Second one it's clear, fast-readable and easy to mantain.
Of course if you have to change precedence (in this case you just have an AND condition, but what if you need and AND and an OR? 1 and 2 or 3 priority changes between "(1 and 2) or 3" - "1 and (2 or 3)"
Brackets () are used to group statements.
Ex - if you have an expression '2 + 3 * 5'.
There are two ways of reading this: (2+3)*5 or 2+(3*5).
To get the correct o/p based on operator precedence, you have to group the correct expression like * has higher precedence over +, so the correct one will be 2+(3*5).
first bracket requires for complex condition to ensure operator precedence correctly. lets say a example
var x=1,y=1,z=0;
if(x==0 && y==1 || z==0)
{
//always true for any value of x
}
what will happen here
(0 && 1 ||1) ----> (0 ||1)----->1
&& has high precedence over ||
if(x==0 && (y==1 || z==0)) alert('1');
{
//correct way
}
if you do not use (y==1 || z==0) bracket the condition always will be true for any value of x.
but if you use (..) the condition return correct result.
Conditional statements can be grouped together using parenthesis. And is not only limited to if statements. You can run the example below in your Chrome Developer Tools.
Example 1:
Console Execution
false && false || true
// true
flow
false && false || true
| | |
|________| |
| |
| |
false or true
| |
|_________________|
|
|
true
Example 2:
Console Execution
false && (false || true)
// false
flow
false && (false || true)
| |
|______________|
|
|
false
Helpful resources for playing around with JSInterpreter and AST's:
https://neil.fraser.name/software/JS-Interpreter/
https://esprima.org/demo/parse.html#
Consider the statement
if( i==10 || j == 11 && k == 12 || l == 13)
what you would want is if either i is 10 or j is 11 And either k is 12 or l is 13 then the result shouldbe true, but say if i is 10, j is 11, k is 10 and l is 13 the condition will fail, because the fate of equation is decided at k as aoon as && comes in picture. Now if you dont want this to happen the put it like this
if( (i==10 || j == 11) && (k == 12 || l == 13))
In this ORs will be executed first and the result will be true.

Should I use == or === In Javascript? [duplicate]

This question already has answers here:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
(48 answers)
Difference between == and === in JavaScript [duplicate]
(2 answers)
Closed 8 years ago.
I am learning Javascript with codecademy, and I was doing some comparisons, and for my code I did:
`console.log(1 == 2)`
and it returned False.
I also did:
`console.log(2*2 === 3)`
and that also returned False.
To check that I have not made a mistake, I did:
`console.log(1 == 1)`
and that returned True
The instructions tell me that === means equal to.
Are there any problems with using == instead of ===? And, which is better to use and why?
Thanks for any help you can give me!
Using == compares only the values, === compares the type of the variable also.
1 == 1 -> true
1 == "1" -> true
1 === 1 -> true
1 === "1" -> false, because 1 is an integer and "1" is a string.
You need === if you have to determine if a function returns 0 or false, as 0 == false is true but 0 === false is false.
It really depends on the situation. It's usually recommended to use === because in most cases that's the right choice.
== means Similar while
=== means Equal. Meaning it takes object type in consideration.
Example
'1' == 1 is true
1 == 1 is true
'1' === 1 is false
1 === 1 is true
When using == it doesn't matter if 1 is a Number or a String.
http://www.w3schools.com/js/js_comparisons.asp
== is equal to || x==8 equals false
=== is exactly equal to (value and type) || x==="5" false
meaning that 5==="5" false; and 5===5 true
After all, it depends on which type of comparison you want.

Exact behaviour of == and === operator in JavaScript

While writing simple snippet for comparison in JavaScript I observed some weird behavior.
Case 1:
typeof(window.WHTStatement.DDL_TPTypeID.size()) ==> "number"
typeof(window.WHTStatement.Txt_TPTypeValue.size()) ==> "number"
window.WHTStatement.DDL_TPTypeID.size() == 1 == window.WHTStatement.Txt_TPTypeValue.size()
returns true -- OK
Case 2:
window.WHTStatement.DDL_TPTypeID.size() === 1 == window.WHTStatement.Txt_TPTypeValue.size()
returns true -- OK
Case 3:
window.WHTStatement.DDL_TPTypeID.size() === 1 === window.WHTStatement.Txt_TPTypeValue.size()
returns false, why?
What exactly happening here in case 3. Can somebody elaborate?
Unlike Python, in JS x == y == z is not equal to x == y && y == z but (x == y) == z. So you are actually comparing a boolean to a number which obviously fails in a type check.
The == comparison worked because 1 == true is true.

Categories