1

I need a way to compare 3 values in a short way like this:

'aaa'=='aaa'=='aaa'
false

but as you can see, it doesn't work. Why?

With 2 values it does work obviously:

'aaa'=='aaa'
true
xRobot
  • 25,579
  • 69
  • 184
  • 304

5 Answers5

4

Comparing of first two values evaluates to true and then that true is compared with "aaa" which evaluates to false.

To make it correct you can write:

const a = 'aaa';
const b = 'aaa';
const c = 'aaa';

console.log(a === b && b === c); //true
Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52
2

if you have those strings stored in variables you can do

let a = 'aaa', b = 'aaa', c = 'aaa'

console.log(a === b && b === c) // true
  • note that i use strict equality (===) as discussed in [thread](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons) – Franceso Russo Sep 05 '18 at 13:28
1

The expression 'aaa'=='aaa'=='aaa' is evaluated as ('aaa'=='aaa')=='aaa'.

The sub-expression in parentheses evaluates to true and it becomes true=='aaa' which is false because when compares two values of different types, JavaScript first converts one of them or both to a common type. It converts the boolean true to the number 1 and the string 'aaa' to the number 0 which are, obviously, not equal.

What you need is

console.log('aaa'=='aaa' && 'aaa'=='aaa')
axiac
  • 68,258
  • 9
  • 99
  • 134
0

You can put all values in an Array and then use Array.prototype.every() function to test if all satisfy the condition defined in the callback you pass to it:

let a = 'aaa', b = 'aaa', c = 'aaa'

let arr = [a, b, c]

let arr2 = [1, 2, 1]

console.log(arr.every(i => [arr[0]].includes(i)))
console.log(arr2.every(i => [arr2[0]].includes(i)))
connexo
  • 53,704
  • 14
  • 91
  • 128
0

Also, you may get the unique values from a given sequence, and if you get a single element is because all equal:

const same = xs => new Set (xs).size === 1

const x = 'aaa'
const y = 'aaa'
const z = 'aaa'

const areSame = same ([ x, y, z ])

console.log(areSame)

const x_ = 'aaa'
const y_ = 'bbb'
const z_ = 'aaa'

const areSame_ = same ([ x_, y_, z_ ])

console.log (areSame_)

With variadic arguments

const same = (...xs) => new Set (xs).size === 1

const x = 'aaa'
const y = 'aaa'
const z = 'aaa'

const areSame = same (x, y, z)

console.log(areSame)

const x_ = 'aaa'
const y_ = 'bbb'
const z_ = 'aaa'

const areSame_ = same (x_, y_, z_)

console.log (areSame_)
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206