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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With