puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

The && and || Operators in TypeScript #1

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

Similar to JS, there are also && and || operators in TS.

Based on the definitions, it borrowed the Logical Operators from JS, the function is to combine expressions.

Here are the defitions we are very familiar with

// Logical AND operation
true  && true;  // true
true  && false; // false
false && true;  // false
false && false; // false

// Logical OR operation
true  || true;  // true
true  || false; // true
false || true;  // true
false || false; // false

But let's take look what it is saying on the official MDN webpage,

The logical operators are described in the following table (the expressions may be of any type, not just boolean): operators

Notice here the description of

Logical And &&: if expr1 can be converted to true, returens expr2; else returns expr1.

This is actually not the function what I daily use.

Here is an example for detailed illustration.

const finalHtml = `${samleText && <li>}${sampleText}${sampleText && </li>`;

The value of sampleText plays a quite important role above. Therefore we have two possibilities.

Possibility 1

const sampleText = '';
console.log(finalHtml); // ''

Possibility 2

const sampleText = '<p>text</p>';
console.log(finalHtml); // <li><p>text</p></li>

The above codes are the explaination of the previous table.

During the daily practical work, this kind of usage seems not quite often. Afterall, above case we could directly use the Conditional (ternary) operator to express in a more clear way:

const finalHtml =sampleText ? '<li>'+sampleText+'</li>' : sampleText ;