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

What Do You Get Back When You Use Logical Operators in JavaScript?

Barbara Streisand
Release: 2024-11-22 10:02:16
Original
916 people have browsed it

What Do You Get Back When You Use Logical Operators in JavaScript?

Navigating the Non-Boolean Returns of Logical Operators in JavaScript

While the question focuses on the absence of boolean returns in specific logical expressions, it highlights a broader concept in JavaScript regarding the behavior of the logical operators || (OR) and && (AND).

In JavaScript, || and && are short-circuit operators that terminate early once they encounter a fully determined logical value. This means that the evaluation of the second operand is skipped if the first operand is sufficient to determine the outcome.

For example, in the expression X || Y, if X evaluates to a truthy value (anything that is not explicitly falsey: true, an object, a string, etc.), then X is returned immediately, rendering the evaluation of Y unnecessary.

Similarly, in X && Y, if X evaluates to falsey, then the evaluation stops and X is returned, again bypassing Y.

The quirk arises when the expression evaluates to a falsey value. Prior to JavaScript 1.2, the operator would return the boolean value false. However, from JavaScript 1.2 onwards, the actual evaluated value is returned.

Therefore, in the provided expressions:

  1. (obj.fn && obj.fn()) || obj._ || (obj._ = {}): If obj.fn exists and evaluates to a truthy value, the expression will return the result of obj.fn(). Otherwise, it will return obj._ if it's defined or create a new object and assign it to obj._ if obj._ is undefined.
  2. obj && obj._: This simply results in obj._ if obj is truthy, otherwise obj is returned.

The above is the detailed content of What Do You Get Back When You Use Logical Operators in JavaScript?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template