0

I want to make default parameter in javascript , so can i ?

jm.toInt = function (num, base=10) {
    return parseInt(num,base);
}
  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters ... see the browser support... – Arun P Johny Sep 14 '15 at 12:27

5 Answers5

4

With a logical or, default values are possible.

jm.toInt = function (num, base) {
    return parseInt(num, base || 10);
}
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
3

ofcourse there is a way!

function myFunc(x,y)
{
   x = typeof x !== 'undefined' ? x : 1;
   y = typeof y !== 'undefined' ? y : 'default value of y';
   ...
}

in your case

    jm.toInt = function(num, base){
       return parseInt(num, arguments.length > 1 ? base: 'default value' );
    }
alamin
  • 1,791
  • 1
  • 22
  • 28
2

ES6 support default parameters, but ES5 not, you can use transpilers (like babel) to use ES6 today

Oleksandr T.
  • 69,412
  • 16
  • 152
  • 136
2

It is part of ES6, but as of now, not widely supported so you can do something like

jm.toInt = function(num, base) {
  return parseInt(num, arguments.length > 1 ? base : 10);
}
Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
0

Use typeof to validate that arguments exist (brackets added to make it easier to read):

jm.toInt = function (num, base) {
    var _base = (typeof base === 'undefined') ? 10 : base
    return parseInt(num, _base);
}
slomek
  • 4,197
  • 3
  • 13
  • 15