I have 3 values that I want to compare f, g and h. I have some code to check that they all equal each other and that none of them are null. I've had a look online but could not find anything that seemed to answer my query. Currently I am checking the code in the following way...
if(g == h && g == f && f == h && g != null && f != null && h != null) { //do something }
This is quite long winded and I might be adding more values, so I was just wondering if there is a quicker way to check that none of the values are null and that all the values equal each other?
Thanks in advance for any help.
To compare 3 values, use the logical AND (&&) operator to chain multiple conditions. When using the logical AND (&&) operator, all conditions have to return a truthy value for the if block to run. Copied!
Strict equality using ===If the values have the same type, are not numbers, and have the same value, they're considered equal. Finally, if both values are numbers, they're considered equal if they're both not NaN and are the same value, or if one is +0 and one is -0 .
The main difference between the == and === operator in javascript is that the == operator does the type conversion of the operands before comparison, whereas the === operator compares the values as well as the data types of the operands.
The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.
You could shorten that to
if(g === h && g === f && g !== null) { //do something }
For an actual way to compare multiple values (regardless of their number)
(inspired by/ simplified @Rohan Prabhu answer)
function areEqual(){ var len = arguments.length; for (var i = 1; i< len; i++){ if (arguments[i] === null || arguments[i] !== arguments[i-1]) return false; } return true; }
and call this with
if( areEqual(a,b,c,d,e,f,g,h) ) { //do something }
What about
(new Set([a,b,c])).size === 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With