Logic and Control Flow in Javascript

JavaScript , Thu Dec 29 2022

    Logic and Control Flow

    You might have read the title of the current section, "Logic and Control Flow", and you might have wondered what does that mean. It's much simpler than what it may seem.

    In every programming language, we have something known as an if statement.

    If statement is consisted of a condition that is evaluated to either true or false and of a block of code. If the condition is evaluated to true, then the code inside of the block will run, otherwise, it's going to be skipped.

    It's that simple. Let's explore it in an example:

    Let's think of where if statements appear in real life. They often appear in terms of some rules or laws.

    Let's say that there's a night club that only allows people over the age of 18 to enter.

    const age = 18;
    if (age >= 18) {
        console.log('You may enter, welcome!');
    }

    If statements can also have an else if and else statements. To continue with our example:

    const age = 18;
    if (age >= 18) {
        console.log('You may enter, welcome!');
    } else if (age === 18){     console.log('You just turned 18, welcome!');
    }

    This is how we add an if else statement. Notice how we have another condition there.

    If we run this code, what do you expect to see in your console?

    Some of you might expect the code that's under the else if statement, but currently, that would not be the case, let's test it out.

    "You may enter, welcome!"

    Why did the first block got logged out? For a really simple reason. It was the first one to pass the check. Our first condition specified that the age must be more than or EQUAL TO 18.

    18 is indeed equal to 18. So how could we fix this? We can simply exchange the more than and equal to to simply more than sign.

    if (age >= 18) {
        console.log('You may enter, welcome!');
    } else if (age === 18){     console.log('You just turned 18, welcome!');
    }

    If we test it out again, now we get exactly what we expected. Awesome!

    But what if the person is younger than 18? We currently aren't handling that case. That's where the else statement comes in handy.

    We implement it like this:

    const age = 18;
    if (age >= 18) {
        console.log('You may enter, welcome!');
    } else if (age === 18){     console.log('You just turned 18, welcome!');
    }else {     console.log('Go away!');
    }

    Try noticing the difference between the if and the if else opposed to the else statement.

    Can you see it?

    Truthy/Falsy Values

    In the previous section, we learned about the strict and loose equality in JavaScript. Equality always results in a boolean value, it can either be a boolean true or a boolean false.

    Unlike other languages, true and false values are not limited to boolean data types and comparisons. It can have many other forms.

    In JavaScript, we also have something known as truthy values and falsy values.

    Truthy expressions always evaluate to boolean true and falsy evaluate to boolean false.

    Knowledge of truthy and falsy values in JS is a must, if you don't know which values evaluate to truthy and which to falsy, you're going to have a hard time reading other people's code.

    Longtime JavaScript developers often toss around the terms "truthy" and "falsy", but for those who are newer to JavaScript these terms can be a bit hard to understand.

    When we say that a value is "truthy" in JavaScript, we don't just mean that the value is true.

    Rather, what we mean is that the value coerces to true when evaluated in a boolean context.

    Let's look at what that means.

    The easiest way to learn truthy and falsy values is to memorise falsy values only. There are only six falsy values, all the other values are truthy.

    Let's explore the list of falsy values:

    FALSY Values

    • false
    • 0 (zero)
    • ", '', `` (empty strings)
    • null
    • undefined
    • NaN (not a number)

    Notes: Empty array ([]) is not falsy

    TRUTHY Values

    • Everything that is not FALSY

    That's a pretty straightforward list. Everything else is truthy. That also includes:

    • '0' (a string containing a single zero)
    • 'false' (a string containing the text "false")
    • [] (an empty array)
    • {} (an empty object)
    • function(){} (an "empty" function)

    A single value can therefore be used within conditions. For example: →

    if (value) {
        // value is truthy
    } else {     value is falsy
        it could be false, 0, null, undefined or NaN
    }

    Taking advantage of truthiness can make your code a little bit more concise. We don't need to explicitly check for undefined, "", etc. Instead we can just check whether a value is truthy. However, there are some caveats to keep in mind.

    I hope this introduction to truthiness and falsiness helps you to write clearer and more concise JavaScript.

    Logical Operators Part 2

    And we're back to logical operators! Remember I've told you that we're going to return to them, I didn't forget!

    Let's do a quick recap and then we're going to see some real and more complex examples of all three logical operators.

    Logical operators are used to combine two or more conditions. If you remember correctly, JavaScript includes three logical operators:

    • && AND
    • || OR
    • ! NOT

    And Operator (&&)

    Double ampersand && is known as AND operator. It checks whether two operands are truthy values. And if they are truthy, it returns true, otherwise it returns false. They are often used as a condition in an if statement.

    So let's show that in an example.

    Lets say that we want to choose which people may enter our club. To enter, they need to be cool, and they also need to be older than 18.

    const age = 19; // age is represented by a number
    const isCool = true; // isCool is represented by a boolean
    if (isCool && age > 18) {
        // notice how we didn't say isCool === true
        console.log('You may enter.');
    } else {     console.log('You cannot enter.');
    }

    isCool is true, and age is greater than the 18, that means that we're going the if block of code is going to be executed.

    Now, the point of this section is not an if/else statement. Let's remove that so we can focus purely on the logical operators. The only thing that we're going to keep is the condition. Let's log it to the console:

    const age = 19;
    const isCool = true;
    console.log(isCool && age > 18); //true

    We got true which is not a surprise. But now, instead of these true boolean values, let's test it with some truthy values.

    console.log('truthy' && 1 && 'test' && 999); //999

    The output of this is 999, and why is that so? Shouldn't the logical operator AND return a boolean value? Here's how it works

    The AND && operator does the following:

    • It Evaluates opUrands from left to right.
    • It converts them to a boolean value. If the result is true, it continues to the next value. If the result is false, it stops and returns the original value of that operand
    • If all operands have been evaluated to true, it returns the last operand.

    Now you know why 999 was returned, all the values were truthy and it was the last one on the list. Now what if we change one value to be falsy?

    console.log('truthy' && 0 && 'test' && 999); //0

    As you can see, if even one falsy value exists, it's going to stop and immediately return that value.

    In other words, AND returns the first falsy value or the last truthy value if no falsy values have been found. Now let's move on to the OR operator.

    Or Operator (||)

    The syntax for the OR operator are two straight vertical lines || . It checks whether any one of the two operands is a truthy value.

    Lets's see it in action:

    console.log('truthy' || 0 || 'test' || 999); //truthy

    We get truthy, why is that? Well let's see how the OR operator works:

    The OR || operator does the following:

    • For each operand, it converts it to boolean.
    • If the result is true, it stops and returns thr original value of that operand.
    • If all operands have been rvaluatrd to falsy returns the last operand

    In other words, a chain of OR "||" returns the first truthy value or the last one if no truthy value is found. So now, if we change all of the values to be falsy, it is going to return the last one:

    console.log('' || 0 || null || undefined); //undefined

    As you can see, we get undefined.

    An exclamation sign ! is known as NOT operator. It reverses the boolean result of the condition.

    The syntax is pretty simple:

    console.log(!true); //false

    The operator accepts a single argument and does the following:

    • 1. Converts the operand to boolean type: true/false.
    • 2. Returns the inverse value.

    For instance:

    alert(!true); //false
    alert(!false); //true

    A double NOT !! is sometimes used for converting a value to boolean type:

    alert(!!'truthy'); //true
    alert(!!null); //false

    That is, the first NOT converts the value to boolean and returns the inverse, and the second NOT inverses it again. In the end, we have a plain value-to-boolean conversion.

    This was a long section, so let's try to summarize it and repeat what we've learned.

    JavaScript is lazy. It will want to do the least amount of work possible to get its return value.

    With the AND operator: JavaScript will first try to return the first falsy value. If none were found, it will return the last truthy value.

    And with the OR operator: JavaScript will first try to return the first truthy value. If none were found, it will return the last falsy value.

    Switch Statement

    Switch statement is extremely similar to the if statement. They can be used interchangeably, but there are some situations where switch is preferred.

    With if statements, you mostly have just a few conditions, one for the if, a few for the if else, and the final else statement.

    If you have a larger number of conditions, you might want consider using the switch statement. Let's explore how it works.

    The switch statement is used to perform different operations based on different conditions.

    Let's say that you have a variable called

    const superHero = 'Captain America';

    Based on the name of the super hero, you want to display his voice line.

    We can do that using the switch statement. Switch statement takes in a value, and then checks it on bunch of cases:

    switch (superHero) {
        case 'Iron Man':
            console.log('I am Iron Man...');
            break;
        case 'Thor':
            console.log('That is my hammer!');
            break;
        case 'Captain America':
            console.log('Nerver give up.');
            break;
        case 'Black Widow':
            console.log('One shot, one kill.');
            break;
    }

    Let's test it out to see what's the output and then we're going to explain it in more detail.

    "Nerver give up."

    Great, we get exactly what we expected.

    In this example, we passed the superHero variable to the switch statement. It executes the first check with triple equal sign.

    It looks something like this:

    'Captain America' === 'Iron Man'

    Since this evaluates to false, it skips it and goes to the next one. As soon as it finds the one that matches correctly, it prints the output.

    What is that break keyword? Break keyword ends the switch when we get the correct case.

    If we omit the break statement, the next case will be executed even if the condition does not match the case.

    And finally, what if none of the names in the switch match the name of our superHero, there must be something like an else statement, right? There is! That something is called default.

    If none of the cases match, the default case is going to be executed.

    We can implement it like this: →

    switch (superHero) {
        case 'Iron Man':
            console.log('I am Iron Man...');
            break;
        case 'Thor':
            console.log('That is my hammer!');
            break;
        case 'Captain America':
            console.log('Nerver give up.');
            break;
        case 'Black Widow':
            console.log('One shot, one kill.');
            break;
        default :
            console.log('Enter a valid superhero name');
            break;
    }

    That's it! Now you know how to use the switch statement. As always, I would advise going into the chrome console and playing with it yourself.

    You learn the most by trying things yourself.

    Ternary Operator

    You could say that the switch statement is a bit more complicated version of the if statement. There's yet another version of it. It's called the ternary operator. It should be used just for the simple true or false checks.

    To explain the ternary operator, let's first take a look at the syntax of a typical if statement:

    if(condition) {
        // value if true;
    } else {
        // value if false;
    }

    Now, the ternary operator:

    condition ? value if true : value if false

    Although this is just a pseudocode, meaning the code written in half english and half real syntax, I think you can still see how we would use the ternary operator.

    Let's use same old driver's licence example we had when we were learning about the if statement.

    if(person.age > 18) {
        console.log('You can drive');
    } else {
        console.log('You may not drive yet');
    }

    And now let's transfer it to a ternary.

    person.age > 18
        ? console.log('You can drive')     : console.log('You may not drive yet');

    Reading from left to right, we first have our condition. Following a question mark is the expression that is going to be executed if the condition evaluates to true. And finally, following the colon sign is the expression that is going to be executed if the condition evaluates to false.

    At the beginning, ternary operators may seem a bit weird and hard to read. But as you write more of them, you'll quickly get better at understanding them. They'll quickly become your go-to tool if you have just a simple true or false question.

    for and while loops

    Sometimes we want to repeat an action a number of times for example let's imagine we want to display numbers form zero to nine on the console.

    You may be thinking doing something like that:

    console.log(0);
    console.log(1);
    console.log(2);
    console.log(3);
    console.log(4);
    console.log(5);
    console.log(6);
    console.log(7);
    console.log(8);
    console.log(9);

    But that's not a good idea at all. So instead we use for or a while loop.

    for loop

    The for loop is more complex, but it's also the most commonly used loop.

    It's called a for loop because it runs “for” specific number of times. For loops are declared with three optional expressions separated by semicolons: initialization, condition and final-expression. Followed by a statement (usually a block statement).

    for ([initialization]; [condition]; [final - expression]) {
        statement;
    }

    The initialization statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.

    The condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to true. When condition is false at the start of the iteration, the loop will stop executing. This means if condition starts as false, your loop will never execute.

    The final-expression is executed at the end of each loop iteration, prior to the next condition check and is usually used to increment or decrement your loop counter.

    So we already know how to use for loop let's use it to print numbers from zero to nine:

    for (let i = 0; i < 10; i++){
        console.log(i);
    }

    First, we initialize our variable i=0 because we start to count from 0, "i" stand for index and it's kind of standard for loop variable.

    Next, we set our condition to i < 10. So every time before the loop execute the statement, it will check if the condition is true or in our example if variable 'i' is less than ten.

    If it's equal or greater than 10 then the condition will evaluate to false and terminate our loop.

    Final expression is our counter update and we set it to i++ which is shorthand for i=i+1. Each iteration i is increased by one.

    At the beginning we said that expressions are optional that mean we can skip parts, for example we can initialize loop variable before loop like that:

    let i = 0; //we have i already decleared and assigned

    for (; i < 10; i++){
        // no need for "initialization"
        console.log(i); // 0, 1, 2
    }

    We can actually remove everything, creating an infinite loop:

    for (;;){
        // repeats without limits
    }