Anthony Yershov
Anthony Yershov

Reputation: 307

How to pass 0 to TypeScript optional parameters?

The following function prints out "null"

function foo(x?: number): void {
  alert(x || null);
}

foo(0);

I know that 0==null is false, so shouldn't this print 0?

Upvotes: 1

Views: 1396

Answers (3)

Mahamudul Hasan
Mahamudul Hasan

Reputation: 2823

// Logical AND operation

true  && true;  // Result=>true
true  && false; // Result=>false
false && true;  // Result=>false
false && false; // Result=>false

// Logical OR operation

true  || true;  // Result=>true
true  || false; // Result=>true
false || true;  // Result=>true
false || false; // Result=>false

your alert code based on below rules:

false || true;  // Result=>true
false || false; // Result=>false

or,

false || any_data;  // Result=> any_data
false || any_data; // Result=> any_data

For more clarification:

alert( 1 || 0 ); // 1 (1 is truthy)
alert( true || 'no matter what' ); // (true is truthy)

alert( null || 1 ); // 1 (1 is the first truthy value)
alert( null || 0 || 1 ); // 1 (the first truthy value)
alert( undefined || null || 0 ); // 0 (all falsy, returns the last value)

So when x=0, it means x is false in boolean context,

x || null //Result=>null

So we can conclude alert will show null

Upvotes: 2

maazadeeb
maazadeeb

Reputation: 6112

If you're trying to make sure the default value of x should be null, if nothing is passed, then you could do this

function foo(x: number | null = null): void {
  alert(x);
}

foo(0);

Upvotes: 0

k0hamed
k0hamed

Reputation: 502

change the check from (x || null) to x !== null ? x : null

as 0 is falsy but doesn't equal to null

Upvotes: 1

Related Questions