Home > Web Front-end > JS Tutorial > body text

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

DDD
Release: 2024-10-31 21:46:02
Original
804 people have browsed it

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'
Copy after login

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')
Copy after login
Copy after login

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')
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!