Java Reference
In-Depth Information
name = name || "World";
This is using the logical OR operator to check if the name parameter has a truthy value.
If it does, then name will stay the same. If name is falsy (such as undefined ), it will
take the value of " World ". Be careful using this method, however; if the name argument
is a falsy value it will be set to the default value of " World ", and in some cases you might
want it to be the falsy value instead ( 0 , for example).
Default parameters should always come after non-default parameters, otherwise default
values will always have to be entered anyway. Consider the following function for calcu-
lating a discounted price in a store:
function discount(price, amount) {
if(amount === undefined) amount = 10;
return price*(100-amount)/100;
It takes two arguments: the price of an item and the percentage discount. The store's
most common discount is 10%, so this is provided as a default value. This means that the
amount argument can be omitted in most cases and a 10% discount will still be applied:
discount(20) // standard discount of 10%
<< 18
If a different discount is applied, the amount argument can be provided:
discount(15, 20) // discount of 20%
<< 12
This will fail to work, however, if the parameters are reversed:
function discount(amount, price) {
if (amount===undefined) amount = 10;
return price*(100-amount)/100;
Now if we try to use the function with just one argument, the function won't work, because
price has not been set:
Search WWH ::

Custom Search