Menu Close

Articles

JavaScript: decision

One of the most important feature of a computer language is the logical decision. Without decisions and loops one program is linear. That means it has a single path of execution from top to bottom. Complex programs have many decisions and loops. So the logical path of execution can be complex and intelligent.

What is a decision?

Decision statements are used to do different actions based on different conditions. This is also known as logical inference. A condition is a logic expression that can be evaluated to a Boolean value true or false. Depending on the result of this expression the program can execute one logical path from two possible.

Logical expressions

To create a condition or logical expression we use variables, value literals and logical operators. For example numbers can be compared using operators: “<” and “>” or a combination of simbols like: <=, >=, ==, !=

Bang symbol “!” is used for not. Can be used in front of an exression to negate. !(a==b) is equivalent for (a!=b).

Sometimes we combine expressions using two operators: “||” is used for or logic while “&&” for logic and.

Note: Never use single simbol “=” into a logical expression. We use “==” or “!=” to compare two variables or values.

Decision Statement

In JavaScript we have several decision statements:

  • if: specify a block of code to be executed, if a condition is true;
  • else: specify a block of code to be executed, if a condition is false;
  • else if specify a new condition to test, when the earlier condition is false;
  • switch specify many alternative logical routes for program depending on a value.

IF/ELSE Example :

In this example we use condition (x < y)  to compare two numbers and calculate value for message.

In this case the message will be “good” because indeed  x is less than y.

 

Switch Example:

In this example for each day number from 0 to 6 we get the day name in English.

We use break statement for each case to exit the switch and do not check all cases.

 

Fallthrough Example:

In this example we detect a workday from a weekend day. The cases are executed top down if a break do not exist. In all cases 1,2,3,4,5 we have workday in cases 0 or 7 we have WeekDay. This technique is called fall through.

 

Note: The switch statement is not the same in all languages. For example Go language execute one single case by default and break automatically. The fallthrough is a keyword that must be used for this effect in Go.