Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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?
0
var a = typeof a !== 'undefined' ? a : '123';
Because || tests for truthiness, and 0 is among the values that are considered to be false.
||
false
Add a comment
Because the value 0 is a "falsy" value and is considered a false
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;
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
0is falsy. I'd usevar a = typeof a !== 'undefined' ? a : '123';