JS short circuit principle application example simplified code approach

  • 2020-03-30 00:51:31
  • OfStack

In js logic, 0, "", null, false, undefined, NaN are all declared false, and everything else is true.

|| evaluates the first operand, if it can be converted to true, returns the value of the expression on the left, otherwise evaluates the second operand. Even if the operator of the | | operator is not a Boolean, it can still be considered a Boolean OR operation because it can be converted to a Boolean regardless of the type of value it returns.
Take advantage of the feature it returns for non-boolean values: use || for non-boolean operands to select the first defined and non-null value (the first non-false value) in a set of alternative values

Ex. :
Var Max = max_width || obj.max_width || 500;
Var attr = attr || ""; This operation is often used to determine whether a variable is defined or not, and if it is not, give it an initial value, which is useful when defining a default value for a function's arguments.

It evaluates the first expression, and if it is false, it will not process the second expression. Otherwise proceed with the subsequent expression. Select the value of the first non-true expression of the expression from left to right, and return the value of the last expression if it was never found.

The taste needs careful study.

The value of the 2 && 's1' && '123' && 'SSS' expression is equal to 'SSS'.
The value of the 2 && 's1' && '&' SSS 'expression is equal to ''
The value of the 2 && 's1' && NaN && 'SSS' expression is equal to NaN

If (a > {= 5)
Alert (" hello ");
It can be simplified as:
A. > = 5 && alert(" hello ");

Typeof 5 and typeof!! 5 difference, this is a more rigorous way to write,!! Is used to convert a variable of another type to a bool type. For example, the if (!!!!! Attr) = > If (attr)

The || and && features in js help us to simplify the code, but also reduce the readability of the code. It's up to us to weigh that.

A clever implementation of the startWith function in JS, alert(! 'asdf'. IndexOf (' s)) = "! 0 = true

Related articles: