Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a default variable value in a function

I am doing a lot of front-end development and I see myself doing this a lot:

function doSomething(arg){
    var int = arg ? arg : 400
    //some code after
}

So I was wondering if the was a way to do this, but shorter and cleaner (I don't like to see arg twice in the same line).

I've seen some people doing something like that :

var int = arg || 400;

And since I don't know in which order I needed to place the value, I tried arg || 400 and 400 || arg, but it will always set int to the value at the right, even if arg is undefined.

I know in PHP you can do something like function doSomething(arg = 400) to set a default value and in a jQuery plugin you can use .extend() to have default property, but is there a short way with a single variable? Or do i have to keep using my way?

Thank for any help and if you can give me resources, it would be appreciated.

like image 240
Karl-André Gagnon Avatar asked May 22 '13 16:05

Karl-André Gagnon


1 Answers

There's really no shorter clean way than

var int = arg || 400;

In fact, the correct way would be longer, if you want to allow arg to be passed as 0, false or "":

var int = arg===undefined ? 400 : arg;

A slight and frequent improvement is to not declare a new variable but use the original one:

if (arg===undefined) arg=400;
like image 168
Denys Séguret Avatar answered Oct 06 '22 00:10

Denys Séguret