JavaScript Tips and Tricks - I

I decided to write a series of coding tips and tricks that I follow while writing my code. This series will help Javascript developers to have a good judgement when to use them and helps to build a quality application. Now, let's jump into the first one.

Ternary Operator:

It is commonly referred to as the conditional operator, inline if (iif), or ternary if. I personally use this one in most of my codes.

Before jumping into how to use them, let study why to use them. when you write an if block, first you declare the variable outside the if block, so that you can use them after the if block.

So a simple condition takes a two-block.  Block 1 for variable assignment and Block 2 for executing the condition.  A minimum of 6 to 7 lines of code required.

Let's see how ternary operator makes it more concise. 

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is false. 
This operator is frequently used as a shortcut for the if statement.
Let's rewrite the above code using ternary operator.

How to store the results in the admin variable. It's simple. We can declare, assign, and execute the condition in a single line. 


Popular posts from this blog

Save Location details to SharePoint Location column through SPFx and PnP JS

Get All content types from ContentTypeHub using SharePoint Rest API v2 using JavaScript

How To Create/ Generate QRcode In SPFx Web Part