最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript default parameter - Stack Overflow

programmeradmin4浏览0评论

I was reading the Three.js code when a silly question arose: Is there any difference between the codes below?

frameHeight = frameHeight !== undefined ? frameHeight : 24;

and

frameHeight = frameHeight || 24;

(frameHeight is a parameter of the function)

Thanks

I was reading the Three.js code when a silly question arose: Is there any difference between the codes below?

frameHeight = frameHeight !== undefined ? frameHeight : 24;

and

frameHeight = frameHeight || 24;

(frameHeight is a parameter of the function)

Thanks

Share Improve this question asked Aug 15, 2012 at 17:29 mccraveiromccraveiro 553 bronze badges 2
  • 1 Not a javascript expert, but I believe the first will only return 24 if frameHeight is undefined where as the second will return 24 if frameHeight has any "falsey" value, like null, '', etc. – sellmeadog Commented Aug 15, 2012 at 17:32
  • They are different, but if(frameHeight===undefined)frameHeight=24; IS equivalent but it is more readable and performs better since its value will only change when needed – ajax333221 Commented Aug 15, 2012 at 17:48
Add a ment  | 

4 Answers 4

Reset to default 9

Yes, they are different.

frameHeight = frameHeight || 24;

This will coerce frameHeight to a boolean value. If it is 0, '', false, null, undefined, or NaN it will be false and frameHeight will be defaulted to 24.

frameHeight = frameHeight !== undefined ? frameHeight : 24;

This will explicitly check if frameHeight is not undefined and ONLY for undefined will it default it to 24.

frameHeight = frameHeight || 24;

^ Will do a null check as well. Will also do a check for 0, false, empty string ('') NaN and undefined

frameHeight = frameHeight !== undefined ? frameHeight : 24;

^ Will just check for undefined.

Yes, there is a difference and that difference can be significant depending upon the circumstances.

frameHeight = frameHeight || 24

will assign 24 to frame if frameHeight is initially ANY falsey value such as "", 0, null, undefined, NaN or false.

Whereas:

frameHeight = frameHeight !== undefined ? frameheight : 24

will only assign it 24 if the initial value is exactly undefined.

So, of possible significance in this particular function, the second method will allow you to pass 0 for the frameHeight to set a zero height, but the first method will not because it will override that 0 to 24.

frameHeight = frameHeight || 24;

fails for frameHeight = 0 works for frameHeight = null

frameHeight = frameHeight !== undefined ? frameHeight : 24;

fails for frameHeight = null works for frameHeight = 0

发布评论

评论列表(0)

  1. 暂无评论