JavaScript

JavaScript – If else Statements & Boolean Logic

photo-1540056145750-91179d279b66

 

var name = 'John';
//  var civilStatus = 'single';

//  if(civilStatus === 'married'){
//    console.log(name + ' is married');
//  } else {
//    console.log(name + ' is single.');
//  }

 var isMarried = true;

 if(isMarried) {
   console.log(name + ' is married.');
 } else {
   console.log(name + ' is single.');
 }

If the variable itself is the type of boolean, is not necessary to write like this:

if(isMarried === true){

}else {

}

as the variable itself already evaluates to a boolean value which in this case if true.


Boolean Logic

var name = 'John';
var age = 16;

if(age < 13) {
  console.log(name + ' is a boy.');
} else if(age >= 13 && age < 20 ) {
  console.log(name + ' is a teenager');
} else if (age >= 20 && age < 30 ){
  console.log(name + ' is a young man');
} else {
  console.log(name + ' is a man');
}

The second condition is evaluated to true so that block is executed.

Boolean logic is a branch of computer science that deals with true/false values

Basic boolean logic: not, and & or

AND(&&) -> true if ALL are true
OR (||) -> true if ONE is true
NOT (!) -> inverts true/false value

The operators must have a lower precedence than other comparison operators.


AND &&

Only if variable A is TRUE && variable b is TRUE, then this expression is TRUE.

TRUE && FALSE -> FALSE

–> Only if all the expressions are TRUE, then the end expression will be TRUE.


OR ||

If A OR B is TRUE then the final expression is TRUE.
The result will only be FALSE if both variables have false values.
It’s enough for the final result to be TRUE with only one TRUE boolean variables.


NOT !

if a = true;
then !a = false;

var age = 16;

age >= 20;  //false
age < 20 //true
!(age < 30); //false

age >= 20 && age < 30; //false
age >= 20 || age < 30; //true

 

 


Please note that this is my study notes that I took while taking the complete guide to JavaScript course on Udemy, if you are interested in understanding the language better, I highly recommend you to purchase the course 🙂 !

Standard

Leave a comment