Sunday, July 22, 2018

Learn Typescript Logical operators

Boolean operators

Logical operators are basic and simple operators in a programming language. They basically compare boolean expressions and returns boolean values. Basically, boolean expressions are multiple conditions where each condition returns true/false. Then these conditions can be combined using this logical operator and output result is boolean

The syntax and usage are the same in javascript too. This operator can be also called boolean operators in typescript

Syntax

Operand operator operand

The operand is an expression which always evaluates to true/false.operator is like boolean operators - And, OR and Not. There are three logical operators in typescript

Or - ||  Operator

The symbol for this operator is two vertical lines. the operand is conditional expression which boolean. We can combine multiple operands and precedence is from left to right
Here are the possible conditional values for OR operator examples


console.log(true  || true )      // returns true

console.log( false || true )      //  returns true

console.log( true  || false)     //  returns true

console.log('string1' || 'string2' )     //  returns "string1"

console.log( false || 'string3')      //  returns "string3"

console.log('string4' || false  )    //  returns "string4"

console.log(''    || false  )    //  returns false

console.log( false || '' )        //  returns ""

if one of the operators is true, and output is return else return false.
All the expressions return true except for both using false condition

Evaluation notes

  • Operator always calculate from left to right
  • If the first operand is true and remaining operand will not be evaluated, the operator returns true.
  • if all operand is evaluated, it means subsequent operands from left are false.

&& And operator

And the operator symbol is double ampersands.
This operator returns true if all the operands are evaluated as true. else return false.
console.log(true  && true )      // returns true

console.log( false && true )      //  returns false

console.log( true  && false)     //  returns false

console.log('string1' && 'string2' )     //  returns "string2"

console.log( false && 'string3')      //  returns "false"

console.log('string4' && false  )    //  returns "false"

console.log(''    && false  )    //  returns ""

console.log( false && '' )        //  returns false

Evaluation notes

  •  Always evaluates from left to right
  • if the first operand is evaluated as false, returns false and other operations are not evaluated
  • if all expressions are evaluated, it returns the last operand evaluated value as output

Not Operator

Not the operator symbol is exclamation mark !. This operator returns the inverse of the operand value.
console.log(!true)      // returns false
console.log(!false)      // returns true