DEV Community

Cover image for If/else statements
GiandoDev
GiandoDev

Posted on

If/else statements

The if/else statements

Alt Text
The if/ else statements in JavaScript decide the behavior of our program
in front of different scenarios.
Alt Text
if/else statement are also called control flow statement.
Sometimes we need to evaluate more than one condition in this case we may use else if statement before the else final statemet.
Alt Text
JavaScript evaluate the code until the condition is met.
To determine if true or false JavaScript uses the comparison operators and truthy and falsey values.

Comparison operators

Alt Text
In this first part we use this two symbols == and != to compare two values,JavaScript by default will try to convert each value in number,before starting the comparison. This can create bugs that are really hard to find, because the string "123" is not the same type of the number 123.
To avoid these annoying problems it is always better to use the strictly mode: === and !==
Alt Text
From now on life gets easier:

  • greater than >
  • greater than or equal to >=
  • smaller than <
  • smaller than or equal to <= We use this for numbers. If we try to compare this two objects: Alt Text In javaScript each object has its personal reference like our identity card. If we want have two equals objects we need that both point to the same reference: Alt Text #Truthy and Falsey Alt Text In the example above javaScript, inside the if statement run the automatic type conversion to truthy and falsey values, than check if the const peaches is true or false; in this case is true and run the argument inside the if statement otherwise run the else statement. This kind of type conversion help us to write a better and coincise code. In this example we see an example of falsey type conversion. Alt Text

Top comments (0)