Booleans, Comparisons and Conditionals

Comparing? Who? Me and my sibling again?

While making any sort of decisions in your code, these are going to be you best friends.

Comparison

Comparison operators return 'true' or 'false'.

image.png

5>1  //true
0.1>0.5  //false
0<-10  //false
32==32  //true
45<=45  //true
'a' === 'a'  //true

Double Equality ==

Checks only if values are equal, but not the types. It coerces both values to same type and them compares.

5 == 5  //true
3 == '3'  //true
0 == ' ' //true
0 == false  //true
null == undefined  //true
true == false  //false

Triple Equality ===

Checks if both value and type is same.

5 === 5  //true
3 === '3'  //false
0 === ' ' //false
0 === false  //false
null === undefined  //false
true === false  //false

Conditional

Evaluates the given condition and runs respective blocks of code based on whether its 'true' or 'false'. Took me a while to wrap my head around it, but basically for the block of code to run the expression in the parenthesis must evaluate to true. Any value, expression, comparison must finally evaluate to true for the code under it to run.

image.png

IF


let breed = 'dog'

if (breed === 'dog') {
  console.log('Woof')
}

---------------------------
let gameOver = false

//!gameOver evaluates to 'true'
if(!gameOver) {
  console.log("Keep playing")
}

ELSE IF


let breed = 'dog'

if (breed === 'dog') {
  console.log('Woof')
} else if (breed === 'cat') {
  console.log('Meow')
}

ELSE


let breed = 'dog'

if (breed === 'dog') {
  console.log('Woof')
} else if (breed === 'cat') {
  console.log('Meow')
} else {
  console.log('Hello Alien')
}

Truthy and Falsy Values

When encountered in boolean context, values that are considered false are 'falsy'. Values that are true are 'truthy'.

image.png

Logical Operators

image.png

AND - &&

Both sides of the expression must evaluate to 'true' for the whole expression to be 'true'

(2<=5) && ('g' === 'g');  //true
9>=9 && '9' === 9;  //false
'shivrav'.length === 7 && 2+2 ===4;  //true

OR - | |

Any one side of the expression must evaluate to 'true' for the whole expression to be 'true'.

(2<=5) || ('g' === 'g');  //true
9>=9 || '9' === 9;  //true
'shivrav'.length === 7 || 2+2 ==1;  //true
0 || undefine  //false

NOT - !

Negates the result of the expression. Will return true if false and false if true.

!null  //true
!('g' == 'g')  //false

Operator Precedence

Specified the order in which expressions will get evaluate. Can be altered using parens ().

! > && > ||

Ternary Operator

This operator helps shorten your conditional code drastically. It improves readability and makes basic if/else much easier.

condition ? expIfTrue : expIfFalse

let name = 'Wifi'
let surname;

name == 'Wifi' ? surname = 'kumar' : surname = 'meh'
//surname = kumar