goodson
goodson

Reputation: 757

Why do these ternary expressions give different results?

My first reduce returns an expression of the form: a + (condition)? b : c, and my second reduce returns the equivalent (???) expression: (condition)? a+b : a+c Why do they behave differently?

function addressLengthWrong(address) {
  let keys = ['street', 'city', 'state', 'zip']
  return keys.reduce((acc, key) => acc + (address[key]) ? address[key].length : 0, 0)
}

let address = {
  street: 'My Street',
  city: '',
  state: '',
  zip: ''
}
console.log(`wrong address len ${addressLengthWrong(address)}`)

address.zip = '01234'
console.log(`wrong address len ${addressLengthWrong(address)}`)

Running the alternative...

function addressLengthCorrect(address) {
  let keys = ['street', 'city', 'state', 'zip']
  return keys.reduce((acc, key) => (address[key]) ? acc + address[key].length : acc, 0)

}

address = {
  street: 'My Street',
  city: '',
  state: '',
  zip: ''
}
console.log(`correct address len ${addressLengthCorrect(address)}`)

address.zip = '01234'
console.log(`correct address len ${addressLengthCorrect(address)}`)

I have the excited sense that I'm about to learn something new. What's going on here?

Upvotes: 0

Views: 40

Answers (2)

Hahdin
Hahdin

Reputation: 51

I think it is because the ternary operation isn't correct in the first, and it isn't picking up on the initial value. Instead of addition (+), use += on the accumulator.

let a = 1, b = 2
let c = 0

c + a === 1 ? a : b //  fails, c = 0

c += a === 1 ? a : b //  success, c = 1

Upvotes: 0

Gilad Bar
Gilad Bar

Reputation: 1322

Your parentheses order is wrong. Try this:

function addressLengthWrong(address) {
  let keys = ['street', 'city', 'state', 'zip']
  return keys.reduce((acc, key) => acc + (address[key] ? address[key].length : 0), 0)
}

You should wrap the entire ternary expression with parentheses, else the acc will be included.

Also, to quote Andreas' answer:

... + ... precedence: 13, ... ? ... : ... precedence: 4; the higher value 'wins'

Upvotes: 2

Related Questions