0

Can anyone explain this expression (in detail) to me? What does it do? What do the !! mean?

const foo = useState(props.index ? !!props.formikContext.values.foobar?.[props.index]?.foofoo: false);
metodribic
  • 1,561
  • 17
  • 27
Lin
  • 11
  • 2

1 Answers1

1

Forget the useState function, just focus on the expression.

let result = props.index ? !!props.formikContext.values.foobar?. 
[props.index]?.foofoo: false;

Means if props.index is not null/0/false/undefined, result equals

!!props.formikContext.values.foobar?.[props.index]?.foofoo.

! can convert data to boolean type and invert it.

!! can convert data to Boolean type but no invert.

let a = 0;
let b = !a;
let c = !!a;
console.log(b, c);  // b equal true, c equal false

? use in typescript means this property is optional.

let data: {a?: string, b: string} = {b: "abc"};
// now a is optional ,if we want get length of a.
let len = data.a?.length;
Jian Zhong
  • 451
  • 3
  • 10