Home >Web Front-end >JS Tutorial >JavaScript's `||` Operator: How Does it Differ from a Standard Logical OR?
Understanding the Double Pipe Operator (||)
In most programming languages, the double pipe operator (||) represents the logical OR operator. It evaluates two Boolean values and follows these rules:
JavaScript's Interpretation
However, JavaScript handles || differently because it's a loosely typed language. This means:
Example:
(function(){}) || {} // True (empty function is truthy)
Practical Usage in JavaScript
Default Function Parameters:
function (title, msg) { var title = title || 'Error'; // Assigns 'Error' if title is falsy var msg = msg || 'Error on Request'; // Assigns 'Error on Request' if msg is falsy }
Bad Programming Practice:
Assigning || expressions directly to variables is discouraged because it prevents passing falsey values as parameters. Consider this function:
function badFunction(flagA) { flagA = flagA || true; // FlagA always becomes true, even if passed false }
Better Practice:
Use explicit checks for falsiness instead:
function goodFunction(flagA) { flagA = typeof flagA !== "undefined" ? flagA : true; // Sets to true only if undefined }
ES6 Syntax for Default Parameters:
function goodFunction(flagA = true) { // Sets to true only if omitted }
Conclusion:
JavaScript's || operator has a unique behavior compared to other languages. While convenient for setting default values, it should be used cautiously to avoid unexpected outcomes and falsey value overrides.
The above is the detailed content of JavaScript's `||` Operator: How Does it Differ from a Standard Logical OR?. For more information, please follow other related articles on the PHP Chinese website!