Friday, May 17, 2024
83
rated 0 times [  89] [ 6]  / answers: 1 / hits: 99849  / 15 Years ago, tue, november 24, 2009, 12:00:00

I can’t seem to wrap my head around the first part of this code ( += ) in combination with the ternary operator.


h.className += h.className ? ' error' : 'error'

The way I think this code works is as follows:


h.className = h.className + h.className ? ' error' : 'error'

But that isn't correct, because that gives a error in my console.


How should I interpret this code correctly?


More From » variable-assignment

 Answers
4

Use:


h.className = h.className + (h.className ? ' error' : 'error')

You want the operator to work for h.className. Better be specific about it.


Of course, no harm should come from h.className += ' error', but that's another matter.


Also, note that + has precedence over the ternary operator: JavaScript Operator Precedence


[#98240] Friday, November 20, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lara

Total Points: 462
Total Questions: 100
Total Answers: 102

Location: Jersey
Member since Mon, Jun 14, 2021
3 Years ago
;