Knowing Branching In Javascript

Knowing Branching Available In Javascript

What is the meaning of branching in javascript and why is called branching?
For those of you who have never had a class at the time in school, college or learn about algorithms and flowcharts, perhaps for the first term you hear.
This branching actual term to describe the process flow of a program branching.
In the flow charts, logic "IF ... THEN" described in the form of branches.

Knowing Branching Available In Javascript

Because of that, this is called branching.
In addition to branching, these structures are also referred to: control flow , decision , structural condition, structure if, etc.
Branching will make the program be able to think and decisive action in accordance with the logic / conditions that we provide.
In the Javascript programming, there are a number of branching shape we need to know.
Discussion following ...

The first branching: IF

Branching if a ramification which has only one block selection when the condition is true.
Try to note the following flowchart:
Knowing Branching In Javascript

The flowchart can be read like this:
"If the total expenditure is greater than $100,000, then display a message Congratulations you get a prize"
If less than $100,000 how?
Yes messages are not displayed.
Let's try to program Javascript, you can try it here :

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Branching if</title>
</head>
<body>
    <script>
        var totalShoping = prompt("Total Shoping?", 0);
        if(totalShoping > 100000){
            document.write("<h2>Congratulations you get a prize</h2>");
        }
        document.write("<p>Thank you for shopping at our store</p>");
    </script>
</body>
</html>
The result:
Knowing Branching In Javascript
click image to enlarge
Note this section:
if(totalBelanja > 100000){
    document.write("<h2>Selamat Anda dapat hadiah</h2>");
}
This is called a block.
Block program in Javascript, begins with an opening brace { and end with a closing brace } .
Once inside there is only one row of blocks expression or statement, it can not be written with curly braces.
like this :
if(totalShoping > 100000)
            document.write("<h2>Congratulations you get a prize</h2>");

The second branching: if / else

Branching if / else is a ramification that has two blocks of choice.
The first choice to correct the condition, and the second choice for the condition is false (else).
Try to note this flowchart:
Knowing Branching In Javascript

It is a flowchart for checking a password.
If the password is correct, the message is on the green blocks will be shown: "Welcome boss!"
But if false, then the message is in the red block which will be displayed: "Password incorrect, please try again!"
Then, the message is in the gray blocks will still be displayed, because he was not part of the branching block if / else.
Note the direction arrows, each block if / else leading up to it.
Knowing Branching In Javascript

For more details, let's try the following program:
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Branching if/else</title>
</head>
<body>
    <script>
        var password = prompt("Password:");
        if(password == "coffee"){
            document.write("<h2>Welcome boss!</h2>");
        } else {
            document.write("<p>Incorrect password, try again!</p>");
        }
        document.write("<p>Thank you for using our application!</p>");
    </script>
</body>
</html>
The result:
Knowing Branching In Javascript
click image to enlarge

The third branching: if / else / if

Branching if / else / if a branch that has more than two blocks of choice.
Try to note the following flowchart:
Knowing Branching In Javascript

It is a block for branching if / else / if. We can add a lot of blocks in accordance with what we want.
Sample Program:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Branching if/else/if</title>
</head>
<body>
    <script>
        var nilai = prompt("Input the final Nilai:");
        var grade = "";
        if(nilai >= 90) grade = "A"
        else if(nilai >= 80) grade = "B+"
        else if(nilai >= 70) grade = "B"
        else if(nilai >= 60) grade = "C+"
        else if(nilai >= 50) grade = "C"
        else if(nilai >= 40) grade = "D"
        else if(nilai >= 30) grade = "E"
        else grade = "F";
        document.write(`<p>Your Grade: ${grade}</p>`);
    </script>
</body>
</html>

The result:
Knowing Branching In Javascript
click image to enlarge
In the program above, we do not use curly braces to create a block of code to if / else / if.
because there is only one command line only. Namely: grade = (a grade)
When we use curly braces, then the above program will be:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Branching if/else/if</title>
</head>
<body>
   <script>
    var nilai = prompt("Input the final nilai:");
    var grade = "";
    if (nilai >= 90){
        grade = "A"
    } else if(nilai >= 80) {
        grade = "B+"
    } else if(nilai >= 70) {
        grade = "B"
    } else if(nilai >= 60) {
        grade = "C+"
    } else if(nilai >= 50) {
        grade = "C"
    } else if(nilai >= 40) {
        grade = "D"
    } else if(nilai >= 30) {
         grade = "E"
    } else { 
        grade = "F";
    }
    document.write(`<p>Your Grade: ${grade}</p>`);
</script>
</body>
</html>

Branching fourth switch / case

Branching switch / case is another form of branching if / else / if.
The structure is like this:
switch(variabel){
    case <value>:
        // blok code
        break;
    case <value>:
        // blok code
        break;
    default:
        // blok code
}

We can create a block of code (case) as many times as desired in the switch block.
In <value>, we can fill with values ​​that will be compared with the variable.
Each case must end with a break. Especially for default, does not need to end with a break because he was located at the end.
Giving a break intended to make the program stop checking other cases when a case is met.

Example:
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Branching switch/case</title>
</head>
<body>
    <script>
        var answer = prompt("You are lucky! Please choose your gift by entering numbers 1 to 5");
        var gift = "";
        switch(answer){
            case "1":
                gift = "Tissue";
                break;
            case "2":
                gift = "1 Coffee Box";
                break;
            case "3":
                gift = "Sticker";
                break;
            case "4":
                gift = "Cooking oil";
                break;
            case "5":
                gift = "IDR 50,000";
                break;
            default:
                document.write("<p>Upps! you selected wrongly</p>");
        }
        if(gift === ""){
            document.write("<p>You failed to get a prize</p>");
        } else {
            document.write("<h2>Congratulations you get " + gift + "</h2>");
        }
    </script>
</body>
</html>

The result:
Knowing Branching In Javascript
click image to enlarge
Branching switch / case also can be made like this:

var nilai = prompt("input nilai");
var grade = "";
switch(true){
    case nilai < 90:
        grade = "A";
        break;
    case nilai < 80:
        grade = "B+";
        break;
    case nilai < 70:
        grade = "B";
        break;
    case nilai < 60:
        grade = "C+";
        break;
    case nilai < 50:
        grade = "C";
        break;
    case nilai < 40:
        grade = "D";
        break;
    case nilai < 30:
        grade = "E";
        break;
    default:
        grade = "F";
}
First of all, we give a true value on the switch, so that we can enter into the block switch.
Then in the switch block, we create the conditions by using a case.
The result will be the same as in the example of branching if / else / if.

Branching Fifth: Ternary Operator

Branching using ternary operator is another form of branching if / else.
Arguably the Ternary Operator is:
Abbreviated form of the if / else.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Branching Ternary</title>
</head>
<body>
    <script>
        var aswr = prompt("Is Jakarta the capital of Indonesia?");
        var answer = (aswr.toUpperCase() == "YES") ? "Right": "Wrong";
        document.write(`Your Answer : <b>${answer}</b>`);
    </script>
</body>
</html>

The function of the method toUpperCase () to change the text in the input into capital letters.
The result:
Knowing Branching In Javascript
click image for enlarge

Ternary operator acts as a branching if / else:
var answer = (aswr.toUpperCase () == "YES")? "True False"; 
If the condition is in parenthesis- (aswr.toUpperCase () == "YES") - is true, then later the contents of the variable will be the same answer with "Yes". 
But if it is false, then variable will contain the answer "False".

Branching Sixth: Nesting (Nested)

We also can make in branching branching block. This is called branching nested or nested if.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Branching Ternary</title>
</head>
<body>
    <script>
        var username = prompt("Username:");
        var password = prompt("Password:");
        if(username == "FajarYusuf"){
            if(password == "Coffee"){
                document.write("<h2>Welcome Boss!</h2>");
            } else {
                document.write("<p>Password Wrong, Try Again!</p>");
            }
        } else {
            document.write("<p>You are not registered!</p>");
        }
    </script>
</body>
</html>
The result:
Knowing Branching In JavascriptKnowing Branching In Javascript
click image for enlarge

Bonus: Using Logical Operators on Branching
Branching nesting, we can actually create more simply by using logical operators.

Example:

var username = prompt("Username:");
var password = prompt("Password:");
if(username == "FajarYusuf"){
    if(password == "coffee"){
        document.write("<h2>Welcome Boss!</h2>");
    } else {
        document.write("<p>Password Wrong, Try Again!</p>");
    }
} else {
    document.write("<p>You are not registered!</p>");
}
We can make this simpler with the logical AND operator (&&).
var username = prompt("Username:");
var password = prompt("Password:");
if(username == "FajarYusuf" && password == "Coffee"){
    document.write("<h2>Welcome Boss!</h2>");
} else {
    document.write("<p>Password wrong, Try Again!</p>");
}
However, this is not the best solution.
Since we can not check whether the user is registered or not.
Disqus Comments