[freeCodeCamp] Basic JavaScript - Conditional Logic, Logical Operators, switch statement
Tags: javascript, webdev, react, 100daysofcode
Published: 2020-06-28 10:06:19

Hey fellas! Guess what? This time we are going to dive into one of the main concepts in any programming language i.e. implement conditional logic. This is in continuation of my JavaScript learning from [freeCodeCamp](https://www.freecodecamp.org/). We've learned quite a few concepts in the series and going to know more about them. 

In the previous [post](https://dev.to/gutsytechster/freecodecamp-basic-javascript-queues-boolean-comparison-operators-47ce) in the series, we learned about `Boolean` and comparison operators which are used as the entry point for conditional logic.

Let's start without any delay!

# <u>Implement Conditional Logic</u>

- <h2><u>`if` statement</u></h2>

We can execute a statement when some condition meets using the `if` statement. If the condition is met, then the code within the `if` block would be executed.

The condition will always return either `true` or `false`. Let's see an example

```
function myCondition(condition) {
  if (condition) {
    return "True";
  return "False";
}
myCondition(true);  // returns "True"
myCondition(false);  // returns "False"
```

As you may see that when the condition is `true`, the statement `return "True"` is executed. When we provide the condition as `false`, the statement outside of `if` statement is executed.

- <h2><u>`else` statement</u></h2>

An `else` statement is used to execute some piece of code when the specified condition within the `if` statement does not hold `true`.  In such cases, we define an `else` statement along with an `if` statement.

For e.g.

```
var num = 5;
if (num < 5) {
  return true;
} else {
  return false:
}
```

Since the condition `num < 5` would return `false`, the block within the `if` statement is not executed, but the flow goes within the `else` block.

- <h2><u>`else if` statement</u></h2>

When we have multiple statements to be checked, we can create an `if` - `else if` - `else` ladder.

The first condition would go with `if` statement, subsequent conditions can go with multiple `else if` statements and finally an `else` statement, which would be executed if none of the conditions is met.

A small example of this can be seen as

```
if (num > 15) {
  return "Bigger than 15";
} else if (num < 5) {
  return "Smaller than 5";
} else {
  return "Between 5 and 15";
}
```

> Please ensure the order of statements when executing the `if`- `else if`- `else` ladder, the conditions are checked from top to bottom, and once entered in a block, all other conditions won't be checked. They will simply be skipped.

## <u>Ternary Operator</u>

JavaScript also provides an operator for a one-liner if-else statement. Its syntax is like

```
condition ? statement-if-true : statement-if-false;
```

Let's consider the following example

```
if (num < 5) {
  return true; 
} else { 
  return false;
}
```

This can be written using the ternary operator as

```
return num < 5 ? true : false;
```

If the condition evaluates to `true`, the expression after `?` is executed otherwise the expression after `:` is executed.

# <u>Logical Operators in JavaScript</u>

When we need to test more than one thing at a time, we can use logical operators instead of using multiple `if` statements.

- <h3><u>AND operator (`&&`)</u></h3>

The AND operator returns `true` if both of its operands returns `true`, `false` otherwise. It's pretty straightforward. Let's jump to an example.

Suppose we have the following piece of code

```
var num = 5;
if (num > 1) {
  if (num > 4) {
    return true;
  }
}
```

The above piece of code can be simplified and can be written in the following way

```
var num = 5;
if (num > 1 && num > 4) {
  return true;
}
```

Did you get it now? It will check for the two conditions provided to it and if they individually return `true`, the whole condition would return `true`.

- <h3><u>OR operator (`||`)</u></h3>

The OR operator returns `true` if any of the operands returns `true`.  For e.g.

```
var num = 5;
if (num > 1 || num < 4) {
   return true;
}
```

In the above example, the condition `num > 1` would return `true` as `5` is indeed greater than `1`. However, the other condition would return `false` as `5` is not less than `4`. But since one of the conditions used with OR operator evaluates to `true`, the whole condition would return `true`, and the statement within the `if` block will be executed.

# <u>Switch statement</u>

JavaScript provides a `switch` statement, which works as if you would use multiple `if` statements with each condition having a check against strict equality operator `===`.

The argument passed to the `switch` statement can have multiple values with each value would be treated as a case. Let's see an example

```
switch(lowercaseLetter) {
  case "a":
    console.log("A");
    break;
  case "b":
    console.log("B");
    break;
}
```

Here `lowercaseletter` can have multiple `case`(s), when a case is matched, the statement(s) under that case is executed. Please make sure to write a `break` statement at the end of each case, which tells JavaScript to stop executing, otherwise, all other cases after the matched case would be executed, until it finds the `break` statement or the number of cases ends.

If the value of `lowercaseletter` is `"a"`, then it would go with the first `case` statement and if it comes out to be `"b"`, then it would go with the second `case` statement.

## <u>Using `default` in the switch statement</u>

At times, we may not be able to decide all cases. In such a situation, we can define a `default` case that would be executed, if the `switch` value does not find any matching case. You can think of it as an `else` statement in an `if`-`else` ladder.

`default` is a keyword in JavaScript, i.e. it has a special meaning. Let's see an example of this

```
switch(value){
  case option1:
     statement1;
     break;
  case option2:
     statement2;
     break;
  default:
     defaultstatement;
     break;
}
```

## <u>Multiple Identical Options in the Switch statement</u>

It is possible that we have the same set of statements to be executed for multiple cases. If we represent that in an `if`-`else` statement, it would be a situation like this

```
var val;
if (val === 1 || val === 2 || val === 3) {
   console.log("Stop");
} else if (val === 4) {
    console.log("Start");
}
```

If we have to represent the above `if`-`else` statement using the `switch`-`case` statements, it would look something like this

```
switch(val) {
  case 1:
  case 2:
  case 3:
    console.log("Stop");
    break;
  case 4:
    console.log("Start");
}
```

Here we have used the quirk that in absence of a `break` statement, the subsequent `case`(s) are executed until a `break` statement is found or the number of cases ends.

## <u>Returning Boolean from a function</u>

We already know that a function can `return` value and it can be anything. However, when you want to return a boolean value i.e. either `true` or `false`. One way you'd think to do is like this

```
function isEqual(a, b) {
  if (a === b){
    return true;
  } else {
   return false;
  }
}
```

And this is perfectly fine and works, which matters the most. However, you can achieve the same with another better approach. Can you think of it? think, think...

Now, stop thinking. Let's see the better way

```
function isEqual(a, b) {
  return a === b;
}
```

Tada! We already know that `a === b` would return a boolean value, which is the only thing we want, don't we? :)

# <u>Conclusion</u>

With the end of this a bit long post, we have acquired knowledge about how we can implement the conditional logic using various JavaScript constructs. Apart from it, we found a better way to return a boolean from a function(trust me, you'd do this more often than you think.)

# <u>References</u>
- [Introduction to JavaScript](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/)
- [Conquering freeCodeCamp - Basic JavaScript (Part 2) - Live Stream #12](https://www.youtube.com/watch?v=lkOXlVgKHYM&list=PLgBH1CvjOA62oNEVgz-dECiCZCE_Q3ZFH&index=13&t=0s)

Let’s meet next time with another JavaScript post covering other JavaScript concepts. Till then be curious and keep learning!