Stack Overflow Asked by syroman on November 20, 2021
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?
Typescript has nothing to do with it, it's javascript.
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));
Answered by Nikita Madeev on November 20, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP