Logical Operators in JavaScript - How to Use Them

Logical operators in JavaScript — how do you use them?

All values in JavaScript are either “truthy” or “falsy”.

  • a && b evaluates to the first falsy operand,
  • a || b evaluates to the first truthy operand.

Both operators will not evaluate any operands after the one the return.
If all operands don’t match, they will evaluate to the last one.

  • !a evaluates to true if a is falsy and false if a is truthy.

All values are truthy except the following, which are falsy:

  • null
  • undefined
  • false
  • +0
  • -0
  • NaN
  • 0n
  • ""
  • document.all

Javascript: Why use Logical Operators along with Comparison Operator?

if (0 <= totalMark < 40) {

This doesn't do what you think it does. You're expecting it to check whether totalMark is in the range from [0, 40). But what it's really going to do is evaluate it one piece at a time. It's going to check 0 <= totalMark and get either a true or a false.

Let's say totalMark is a negative number, so you get false from this piece. The next thing it will compare is false < 40. That doesn't make much sense, but javascript will do its best. Following the obscure rules of javascript type coercion, false gets treated as 0 so it checks 0 < 40 which is true. Therefore, 0 <= totalMark < 40 resolves to true when totalMark is a negative number. In fact, if you walk through the other possibilities, it will always result in true.

In short, these comparison operators can only look at 2 things at once. And then you use &&'s and ||'s to build up something larger.

The logical && and || operators in JavaScript

So what exactly is happening when you use the && and || operators with chaining values

&& is a binary operator, with one left-hand operand and one right-hand operand. The expression a && b && c && d && e is parsed based on associativity rules so that it looks like this:

if (a && (b && (c && (d && e)))) {

Based on the semantics of &&, if a is falsy, the entire condition immediately evaluates to a, which is falsy. If a is truthy, then the expression evaluates to the right side, which is b && (c && (d && e))). In that case if b is falsy, then that sub-expression, and thus the entire expression, immediately evaluates to b, which is falsy; if b is truthy, then that sub-expression evaluates to its right side, which is c && (d && e), and the process continues.

The net result is the intuitive behavior that for the entire expression to be falsy, and therefore for the if branch to not be taken, it suffices for any of the variables to be falsy. The evaluation will "short-circuit"--resulting in falsy--as soon as any falsy variable is encountered. For the entire expression to be truthy, and therefore for the if branch to be taken, all the variables must be truthy.

For ||, the logic is reversed. For the entire expression to be truthy, and therefore for the if branch to be taken, it suffices for any of the variables to be truthy. The evaluation will "short-circuit"--resulting in truthy--as soon as the first truthy value is encountered. For the entire expression to be falsy, and therefore for the if branch not to be taken, all the variables must be falsy.

You Don't Know JS has a good explanation too.

Logical OR in JavaScript

Just use | (Bitwise OR):

function first(){    console.log("First function");    return true;};
function second(){ console.log("Second function"); return false;};
console.log(!!(first()|second()));

returning the higher value in logical operators in javascript

From MDN on the && operator:

"If expr1 can be converted to true, returns expr2; else, returns
expr1."

So in this case, 1 can be converted to true, so it returns the second value, 5.

Use logical operator to assign a value or 0, otherwise assign alternative

Yes, || checks for the first operand to be falsy (false when coerced to a boolean), and 0 is exactly that.

If you want to check for null and undefined only, you can use the nullish-coalescing operator:

const qux = foo ?? bar;

If you want to check for exactly undefined, you should use the conditional operator as you did.

Javascript Logical OR operator in return statement of a function

(title) => !!title || "Title is required"]

This line is saying:
If title is present, return true, otherwise return "Title is required".

Let's break it down...


To start with, the arrow function is just shorthand for:

function xxxx (title) {
return !!title || "Title is required"];
}

Next, the !! is a double negation, effectively just the logical not opperator twice. The first negation converts the data (whatever it data type it may be) to a boolean. The second negation changes the boolean again to give the desired result.

E.g. !!'hello' --> true, !!0 --> false, !!undefined --> false


The next part is a comparison. The || is OR opperator, so if the first half is true / present, then it will be returned, if not, the part after the || will be returned.

E.g. true || 'some text' will return true, wheras false || 'some text' will return some text


Here are some example, try running the snippet to see the outputs

const checkTitle = (title) => !!title || "Title is required"

// 1. No parameters, should print "Title is required"
console.log('Test 1', checkTitle());

// 2. Parameter presentbut empty, should print "Title is required"
console.log('Test 2', checkTitle(""));

// 3. Title present, and valid, should preint 'true'
console.log('Test 3', checkTitle('Hello World!'));

Logical Operators (AND Operators)

Look at the documentation for the && operator:

&&; Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

In the first example, you provide the numbers 1 and 2 as the operands. 1 cannot be converted to false, therefore the second operand, which happens to be 2, is returned.

The two last examples are fairly straightforward, as booleans are involved. If either operand is false, you get back false. The reason only the third one gives you an error is because in the second, the second operand (X) is never checked due to short-circuiting. Short-circuiting means that once JS sees that the first value is false, it does not even bother to check the other value. JS sees false as the first operand and immediately returns.

What's the difference between ( ' ' || false) and (false || ' ' ) in JavaScript?

See in the same page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR

expr1 || expr2

If expr1 can be converted to true, returns expr1; else, returns expr2.



Related Topics



Leave a reply



Submit