Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...