loading...
Cover image for [freeCodeCamp] Basic JavaScript - Conditional Logic, Logical Operators, switch statement

[freeCodeCamp] Basic JavaScript - Conditional Logic, Logical Operators, switch statement

gutsytechster profile image Prashant Sharma Originally published at gutsytechster.wordpress.com ・5 min read

Learning JavaScript with freeCodeCamp (10 Part Series)

1) [freeCodeCamp] Basic JavaScript – Comments, Variables and Mathematical Operations 2) [freeCodeCamp] Basic JavaScript - Strings 3 ... 8 3) [freeCodeCamp] Basic JavaScript - Arrays 4) [freeCodeCamp] Basic JavaScript - Functions 5) [freeCodeCamp] Basic JavaScript - Queues, Boolean, Comparison Operators 6) [freeCodeCamp] Basic JavaScript - Conditional Logic, Logical Operators, switch statement 7) [freeCodeCamp] Basic JavaScript - Objects 8) [freeCodeCamp] Basic JavaScript - Loops 9) [freeCodeCamp] Basic JavaScript - Recursion, random numbers, parseInt function 10) [freeCodeCamp] ES6 - var, let and const

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. We've learned quite a few concepts in the series and going to know more about them. 

In the previous post 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!

Implement Conditional Logic

  • if statement

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.

  • else statement

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.

  • else if statement

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.

Ternary Operator

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.

Logical Operators in JavaScript

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

  • AND operator (&&)

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.

  • OR operator (||)

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.

Switch statement

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.

Using default in the switch statement

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;
}

Multiple Identical Options in the Switch statement

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.

Returning Boolean from a function

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? :)

Conclusion

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.)

References

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

Learning JavaScript with freeCodeCamp (10 Part Series)

1) [freeCodeCamp] Basic JavaScript – Comments, Variables and Mathematical Operations 2) [freeCodeCamp] Basic JavaScript - Strings 3 ... 8 3) [freeCodeCamp] Basic JavaScript - Arrays 4) [freeCodeCamp] Basic JavaScript - Functions 5) [freeCodeCamp] Basic JavaScript - Queues, Boolean, Comparison Operators 6) [freeCodeCamp] Basic JavaScript - Conditional Logic, Logical Operators, switch statement 7) [freeCodeCamp] Basic JavaScript - Objects 8) [freeCodeCamp] Basic JavaScript - Loops 9) [freeCodeCamp] Basic JavaScript - Recursion, random numbers, parseInt function 10) [freeCodeCamp] ES6 - var, let and const

Posted on by:

gutsytechster profile

Prashant Sharma

@gutsytechster

Hey everyone! I am an open source enthusiast who loves to code. I am an aspiring Full stack developer. My weapon of code is Python and I enjoy creating REST APIs through Django REST Framework.

Discussion

markdown guide