Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript compare 3 values

Tags:

javascript

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.

like image 854
Phil Avatar asked Apr 02 '12 08:04

Phil


People also ask

How do I compare 3 numbers in JavaScript?

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!

How === works in JavaScript?

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 .

Is == and === same in JavaScript?

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.

What is === in JavaScript example?

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.


2 Answers

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 } 
like image 95
Gabriele Petrioli Avatar answered Oct 10 '22 05:10

Gabriele Petrioli


What about

(new Set([a,b,c])).size === 1 
like image 39
olidem Avatar answered Oct 10 '22 07:10

olidem