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
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
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
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
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')
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)))
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_)
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_)