Home  >  Article  >  Web Front-end  >  Why Does My JavaScript Code Fail with `h.className = h.className ? \' error\' : \'error\'`?

Why Does My JavaScript Code Fail with `h.className = h.className ? \' error\' : \'error\'`?

DDD
DDDOriginal
2024-10-31 21:46:02805browse

Why Does My JavaScript Code Fail with `h.className  = h.className ? ' error' : 'error'`?

Operator Precedence Enigma: JavaScript's Ternary Operator and Concatenation

The use of the ternary operator in JavaScript can be perplexing, especially when mingled with other operators. Consider the following code snippet:

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

The purpose of this code is to append the string ' error' to the className property of the HTML element 'h'. However, the code fails with an error. To understand why, we need to dissect the operator precedence in JavaScript.

The ternary operator (?:) has a higher precedence than the assignment operator (=). Therefore, the above code is equivalent to:

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

This interpretation makes more sense. The ternary operator checks whether h.className is not null or undefined (a "truthy" value). If true, it appends ' error' to h.className. Otherwise, it appends 'error'.

To fix the original code, we need to explicitly add the assignment operator within parentheses:

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

By placing the assignment operator within parentheses, we override the precedence rules and ensure that the entire ternary expression is assigned to h.className.

The above is the detailed content of Why Does My JavaScript Code Fail with `h.className = h.className ? \' error\' : \'error\'`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn