Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare values of 3 javascript variable

Tags:

javascript

I would like to compare the 3 javascript variable values and they are equal, need to perform a function.

if(vcount === tcount === lcount){

//do something;
}

and (as per this previous answer)

if((vcount == tcount) && (tcount == lcount)){

    //do something;
    }

But its not working for me.

like image 593
anoopcr Avatar asked May 25 '26 02:05

anoopcr


2 Answers

consider the following code-

1===1===1

As === operator is left-right associative hence the first part that is 1===1 is evaluated first.

1===1 returns true. then there is the following comparison

true===1

Which is definitely false because boolean true is not same as 1 because === considers value as well as datatype.

So whenever the 3rd parameter is not boolean it will definitely return false if you use === to compare them. Hence you should always use the 2nd syntax to compare any 3 values.

like image 101
Rajesh Paul Avatar answered May 27 '26 15:05

Rajesh Paul


Try with Conditional(Ternary) Operator (?:) which will help. Please refer below example This is one way of alternative solution

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction()
{
document.getElementById("demo").innerHTML= getResult(7,5,5);
}

function getResult(x,y,z){
 return x===y?x===z?true:false:false;
}

</script>

</body>
</html>
like image 25
Hariharan Avatar answered May 27 '26 16:05

Hariharan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!