Power & Versatility of Decisions in JavaScript

ยท

7 min read

Power & Versatility of Decisions in JavaScript

Introduction:

Making a lot of decisions is crucial not only in computer programming but also in our life [If this happens, I will do that, or something else]. So like every programming language, JavaScript offers various control structures to make decisions based on conditions, We will cover topics such as the if statement, the switch statement, and the ternary operator. These are the core components of making decisions in JavaScript and understanding how they work will help you write efficient and effective code. So, if you are ready to take your JavaScript skills to the next level, buckle up and let's get started!"

Before starting with this topic, you should be familiar with JavaScript basics. Here is my article Introduction to JavaScript, which you might want to check out. Okay! let's see how we going to use these conditional blocks of code in JavaScript:

An Analysis of if-else, switch, & Ternary Operator:

If-else statements:

The basic structure of an if-else the statement looks like this:

if (condition) {
  // code to run if the condition is true
} else {
  // code to run if the condition is false
}

The condition can be any expression that returns a boolean value either true or false. If the condition is true, the code inside the first set of curly braces {} will be executed and in that curly braces, you can write whatever you want to do when the given condition is true. If the condition is false, the code inside the second set of curly braces will be executed. This is how if-else statement work, It's very simple to use.

For example, The following code checks if a variable x is greater than 10, and if it is, it logs a message to the console or otherwise else statement gets hit:

let x = 9;
if (x > 10) {
  console.log("x is greater than 10");
} else {
  console.log("x is not greater than 10");
}
// You can expect the result of this condition

See the Output in Browser's console:

So what happens here? we defined a variable x and assign value 9. then we made a condition x > 10 . As you expected this condition returns a boolean false value and therefore code in the first curly braces did not get executed instead else statement code returned the line x is not greater than 10.

You can also use multiple if-else statements to make more complex decisions. For example:

let x = "Sunny" ;
if (x == "Snowy") {
  console.log(`It's ${x}, let's wear Sweater.`);
} else if (x == "Sunny") {
  console.log(`It's bright & ${x} day, let's wear somthing light.`);
} else if (x == "Rainy"){
  console.log(`It's ${x}, let's wear Raincoat.`);
} else {
    console.log(`No right data of weather.`)
}
// Guess which statement will get executed.

See the Output in Browser's console:

In the above example: if statement's condition return false value, so the next else if condition is checked and got true value & logs a message inside that statement to the console and the remaining conditions didn't get checked.

Note that only one of the code blocks will be executed depending on the condition being true or false, and once a true condition is found, the rest of the conditions will not be checked.

Switch statements:

Switch statements are very much similar to if-else statements, used to perform different actions based on different conditions. A switch statement tests a single value against multiple cases and executes the case's code block that matches the given value or expression. If all cases don't match the value, the code inside the default block is executed.

Syntax:

switch (expression) {
  case value1:
    // code block to be executed if expression === value1
    break;
  case value2:
    // code block to be executed if expression === value2
    break;
  default:
    // code block to be executed if no case is matched
    break;
}

The expression inside the switch statement is checked once and compared with each case value. If any code block matches with the expression that case gets executed, and if the code block contains a break statement is encountered it will be out of the switch statement and return the statement inside it, if it's not encountered the execution will continue to the next case until a break is encountered. If no case matches the expression then a default the case is executed if it's present in the switch case.

We can do the same example of if-else statement using the switch statement:

let weather = "windy";
switch (weather) {
    case "Snowy":
        console.log(`It's ${weather}, let's wear Sweater.`);
        break;
    case "Sunny":
        console.log(`It's bright & ${weather} day, let's wear someIthing light.`);
        break;
    case "Rainy":
        console.log(`It's ${weather}, let's wear Raincoat.`);
        break;
    default:
        console.log(`No right data of "${weather}" weather. `);
        break;
}

// Guess which statement is going to excute in the example?

What we did here: We held some value in variable weather and wrote the switch statement. And if we run this piece of code, What will happen is the value of the variable weather will check whether the cases are matching or not. In our example, there is no case match with the given value. In the end, the default statement is going to execute.

See the Output in Browser's console:

Switch statements can be used as a cleaner alternative to if-else statements in certain situations, especially when multiple conditions need to be tested against the same value.

Ternary operators:

Ternary operators are used to make simple decisions in a shorthand way. Ternary operators are often used as a concise alternative to if-else statements, especially when the decision to be made is quick and simple and the expressions to be executed are short.

Syntax:

condition ? expression1 : expression2;

Here, the condition is evaluated first. If it's true, expression1 is executed, otherwise expression2 is executed (when given condition return false value).

Here's an example of a ternary operator:

let age = 18;
(age > 17) ? console.log("Eligible to vote") : console.log("Not eligible to vote");

In this example, the ternary operator checks if the value of age is greater than 17. If it is, the operator returns the string "Eligible to vote" otherwise, it returns "Not eligible to vote". The result of this expression is logged into the console.

See the output in Browser's console:

Ternary operators can also be nested to handle more complex conditions. For example:

// Example 1
let age = 11;
let remainYear = 18 - age;
let eligibility = (age >= 18) ? `Eligible` : `Not eligible. ${((remainYear == 1) ? `You will be eligible to vote in One year`: `You will be eligible to vote in ${remainYear} years`)}`;
console.log(eligibility);

// Example 2
let age = 17;
let remainYear = 18 - age;
let eligibility = (age >= 18) ? `Eligible` : `Not eligible. ${((remainYear == 1) ? `You will be eligible to vote in One year`: `You will be eligible to vote in ${remainYear} years`)}`;
console.log(eligibility);

Here in above examples:

We used ternary operators and in that nested on more ternary operators to get a precise number of years to require for eligibility to vote.

Let's see example 1: the variable age has an 11 value that is less than 18, which means the first expression will not return instead the second expression will hit, and it contains a further ternary operator which remainYear is equal to (18-11)= 7. So condition will return false value and therefore in nested ternary operator second expression will return and get attached to the string 'Not eligible. '.

In example 2: remainYear is equal to (18-1)= 1. that means the condition returns a true value and therefore in a nested ternary operator the first expression will return and get attached to the string 'Not eligible. '.

See the Output in Browser's console:

Conclusion:

Understanding decisions in JavaScript is critical for writing programs that can make choices and take actions based on different conditions. By studying the different decision-making tools in JavaScript, including the if-else statement, switch statement, and ternary operator, you can gain a deeper understanding of the language and use it to build more complex and dynamic applications. Whether you are a beginner or an experienced developer, it is important to keep exploring and practising these concepts to continually improve your skills and knowledge. So keep pushing the limits of what you can do with JavaScript, and continue to learn and grow as a developer.

A Decision is one of the six fundamentals of JavaScript. In this article, we have learned about it. I have also covered the other five fundamentals in my articles individually. You can find them below:

Thank you for reading. Feel free to comment on this, if found it useful.

Happy learning.๐Ÿ˜‡๐Ÿ˜‡๐Ÿ˜‡

ย