Maizere Pathak.Nepal
Maizere Pathak.Nepal

Reputation: 2413

Functions argument default value

function foo( a, b ) {

  a = a || '123';
  b = b || 55;  
  document.write( a + ',' + b );
}

foo(); // prints: 123,55
foo('bar'); // prints: bar,55
foo('x', 'y'); // prints x,y

but:

foo(0,''); // prints: 123,55

why dont it print 0 ,55?

Upvotes: 2

Views: 65

Answers (3)

Parthik Gosar
Parthik Gosar

Reputation: 11646

0 and "" also compute to false when checked. Hence you need to change your condition to

a = a != null ? a : '123';
b = b != null ? a : 55;  

Upvotes: 2

Joseph
Joseph

Reputation: 119837

Because the value 0 is a "falsy" value and is considered a false

Upvotes: 3

deceze
deceze

Reputation: 522016

Because || tests for truthiness, and 0 is among the values that are considered to be false.

Upvotes: 4

Related Questions