Stack Exchange
JavaScript function default parameter is not working properly
As per ES6, we can provide the default value of parameters (here I provide value 0 to the second parameter). Now, if I am providing values of 20 & null in function, as per ES6, it should take now values as 20 & 0 so alert must ping 20, but it is alerting NaN. Can someone help me out? 


function alpha(a, b = '0') {
  return (a != null ? '$' + (parseFloat(a) + parseFloat(b)) : "");
}

alert(alpha(20, null)); //output is NaN



Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters

That documentation you link to explicitly mentions that null and other falsey values are not replaced…


Now, if I am providing values of 20 & null in function, as per ES6, it should take now values as 20 & 0

Nope. :-) null isn't replaced by the default. The only value replaced by the default is undefined (whether you give it explicitly, or just leave off that parameter).
So:


function alpha(a, b = '0') {
  return (a != null ? '$' + (parseFloat(a) + parseFloat(b)) : "");
}

console.log(alpha(20));            // Gets default
console.log(alpha(20, undefined)); // Gets default
console.log(alpha(20, null));      // Does not get default




You are passing null in parameter b so null is assigned to b. To get the default value work you should omit the second parameter in your function.


function alpha(a, b ='0'){
 return (a!=null ?  '$' + (parseFloat(a) + parseFloat(b)) :  ""); 
}

alert(alpha(20));



