-1

In typescript, what is the difference between

if (x)
if (!x)
if (!!x) 

Could this have different behaviors depends on the type of variable? (string, number, object, etc...). What I mean with the sentence above is:

const myString = 'hello';
const myObject = new MyClass(10, 'Luke');
const ten = 10;

if(myString) 
if(!myString)
if(!!myString)

if(myObject)
if(!myObject)
if(!!myObject)

if(ten)
if(!ten)
if(!!ten)

In this example, when the code enters in one if instead of another?

syroman
  • 55
  • 3
  • 1
    [check this](https://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript) – Stutje Jul 22 '20 at 07:19

1 Answers1

2

Typescript has nothing to do with it, it's javascript.

if...else

The if statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement can be executed.

  • ! - logical not operator, can convert value to inverted boolean
  • !! - convert value to boolean (analog Boolean)

falsy values: number 0, BigInt 0n, null, undefined, boolean false, number NaN, string ''

const myString = 'hello';
const myObject = { test: 123 };
const ten = 10;

console.log(myString);
console.log(!myString);
console.log(!!myString, Boolean(myString));

console.log(myObject);
console.log(!myObject);
console.log(!!myObject, Boolean(myObject));

console.log(ten);
console.log(!ten);
console.log(!!ten, Boolean(ten));
Nikita Madeev
  • 4,284
  • 9
  • 20