| by Arround The Web | No comments

Javascript Inline If

Conditional statements are one of the major building blocks of programming. They allow developers to add conditional logic and check for various parameters. When working with conditional logic, you will need to check for specific conditions and act if it’s either true or false.

In this tutorial, we will look at how we can create a minimal if check in JavaScript using various techniques.

JavaScript Inline if using Ternary Operators

The most common and best practice for introducing an inline if statement in JavaScript is using a ternary operator.

The ternary operator uses a colon and a question mark to introduce logic and action.

Let us illustrate how we can use ternary operator to create an inline if statement.

Suppose we have two numbers, and we want to get the largest value. Without ternary operator, we would write the code as shown:

let a = 10
let b = 2
if (a > b) {
    console.log(a)
 }
 else {
    console.log(b)
 }

However, using inline if statement, we can minimize the above code into a single line as shown in the code below:

let a = 10
let b = 2
console.log(a>b ? a : b);

In this case, we use the ternary operator to compare the condition we wish to check. If a is greater than b, we console.log(a) otherwise console.log(b).

Running the code above should return a result as shown:

$ node inline.js
10

As you can see, using the ternary operator, we are able to minimize the if else statement into a single statement.

JavaScript Inline If Using Logical Operators

The second method you can use is the logical and operator. It allows us to combine the condition we wish to check and the execution block in a single line as shown:

let a = 10
let b = 2
console.log(a>b && a || b)

Here, we can see the logical and in practice. We start by specifying the condition we wish to check on the left side of the operator. If true, the execution block is run. Otherwise, run the right-side operation.

JavaScript Inline if (Multiple Conditions) Using the Ternary Operator

You may ask, what happens if I have a nested condition such as multiple if..else blocks? We can implement them using the ternary operator as shown:

let a = 10
let b = 2
console.log(a>b ? a : a<b ? b: "NaN");

In the example above, we have multiple conditions. If a is greater than b, print a, if a is less than b, print b, otherwise NaN.

Closing

In this article, we discussed how to implement inline if statements using ternary and logical and operator.

Share Button

Source: linuxhint.com

Leave a Reply