Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
128 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...